码迷,mamicode.com
首页 > Web开发 > 详细

HttpUrlConnection发起POST请求

时间:2015-05-20 21:58:54      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:

 1 StringBuffer str=new StringBuffer();
 2             Map<String,Object> requestParamsMap = new HashMap<String, Object>();  
 3             requestParamsMap.put("type",0);//添加绑定参数
 4             Iterator it=requestParamsMap.entrySet().iterator();//获取迭代器
 5             while(it.hasNext()){
 6                 Map.Entry<String, Object> element=(Entry<String, Object>) it.next();
 7                 str.append(element.getKey());
 8                 str.append("=");
 9                 str.append(element.getValue());
10                 str.append("&");
11             }
12             if(str.length()>0)
13                 str.deleteCharAt(str.length()-1);//删除末尾多余的一个&
14              try {
15                  URL url=new java.net.URL(URLStr);
16                  URLConnection connection=url.openConnection();
17                  HttpURLConnection con=(HttpURLConnection)connection;
18                  con.setDoOutput(true);
19                  con.setRequestMethod("POST");
20                  PrintWriter writer =new PrintWriter(con.getOutputStream());
21                  writer.write(str.toString());
22                  writer.flush();
23                  writer.close();
24                  BufferedReader reader=new BufferedReader(new InputStreamReader(con.getInputStream()));
25                  String line=null;
26                  String result="";
27                  while((line=reader.readLine())!=null){
28                      result+=line;
29                  }
30                  System.out.println(result);
31              } catch (Exception e) {
32                  // TODO Auto-generated catch block
33                  e.printStackTrace();
34          }

和get请求类似,但是post请求时,相关参数是保存在 HTML HEADER中。所以必须要输出这个参数,并且读取服务器返回的数据。我们依然按照keyname=value的顺序将要输出的参数格式化为string。为了输出参数,需要通过con获取PrintWriter对象 writer,然后利用writer输出前面格式化的string。获取服务器返回的结果和get请求操作一样,不说了。

HttpUrlConnection发起POST请求

标签:

原文地址:http://www.cnblogs.com/zhoudayang/p/4518155.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!