HttpURLConnection Get和Post发送数据

Get

URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setReadTimeout(5000);

Post

byte [] entity=("id=1&name="+URLEncoder.encode("您好","utf-8")).getBytes();  
HttpURLConnection conn=(HttpURLConnection)new URL(path).openConnection();  
conn.setConnectTimeout(5000);  
conn.setRequestMethod("POST");  
conn.setDoOutput(true);  
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); //用于指导实体数据的内容类型 (表单类型)
conn.setRequestProperty("Content-Length",String.valueOf(entity.length)); //entity为要传输的数据格式为  title=hello&time=20 (可以对该数据编码) 
OutputStream outStream=conn.getOutputStream();  
outStream.write(entity);  

Post xml

conn.setRequestProperty("Content-Type","text/xml; charset=UTF-8");
posted @ 2015-11-06 10:41  thomas_blog  阅读(133)  评论(0编辑  收藏  举报