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

HttpUrlConnection get方式通信

时间:2015-05-20 22:02:37      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:

       StringBuffer str=new StringBuffer(URLStr+"?");
            Map<String,Object> requestParamsMap = new HashMap<String, Object>();  
            requestParamsMap.put("type",0);
            Iterator it=requestParamsMap.entrySet().iterator();
            while(it.hasNext()){
                Map.Entry<String,Object> element=(Entry<String, Object>) it.next();
                str.append(element.getKey());
                str.append("=");
                str.append(element.getValue());
                str.append("&");
            }
            if(str.length()>0)
                str.deleteCharAt(str.length()-1);//删除末尾多余的一个&
       try { URL url=new java.net.URL(str.toString()); URLConnection connection=url.openConnection(); HttpURLConnection con=(HttpURLConnection)connection; con.setDoOutput(false); //get请求能使用缓存 con.setUseCaches(true); con.setRequestMethod("GET"); con.connect(); BufferedReader reader=new BufferedReader(new InputStreamReader(con.getInputStream())); String line=null; String result=""; while((line=reader.readLine())!=null){ result+=line; } System.out.println(result); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }

  因为是get请求,需要把请求参数附加到url中,这里用到了hashmap,将绑定的参数放置在map对象中,然后依次遍历取出map对象,按照顺序填充url,然后执行url.openConnection()操作获取URLConnection对象。

  接下来把上面的URLconnection对象强转为HttpUrlConnection对象。con.setDoOutput(false)表明不进行output操作。con.setRequestMethod("GET")表明发起的是GET请求。

  最后一步是获取服务器返回的数据,这里用到了BufferedReader ,将返回的inputstream对象缓存好,最后利用BufferedReader 对象的read方法,将buffer中的数据按照行的顺序提取出来,保存在result。

  

HttpUrlConnection get方式通信

标签:

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

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