HttpURLConnection和HttpClient获取Json数据

Android中提供的HttpURLConnection(JDK自带)和HttpClient(Apache提供)接口可以用来开发HTTP程序。

服务器端有如下json数据

[plain] view plaincopy
  1. [  
  2. {  
  3. "image": "http://222.22.254.223:8080/web/a.jpg",  
  4. "title": "新闻标题1",  
  5. "content": "新闻内容1",  
  6. "conut": "跟帖人数1"  
  7. },  
  8. {  
  9. "image": "http://222.22.254.223:8080/web/b.jpg",  
  10. "title": "新闻标题2",  
  11. "content": "新闻内容2",  
  12. "conut": "跟帖人数2"  
  13. },  
  14. {  
  15. "image": "http://222.22.254.223:8080/web/c.jpg",  
  16. "title": "新闻标题3",  
  17. "content": "新闻内容3",  
  18. "conut": "跟帖人数3"  
  19. },  
  20. {  
  21. "image": "http://222.22.254.223:8080/web/d.jpg",  
  22. "title": "新闻标题4",  
  23. "content": "新闻内容4",  
  24. "conut": "跟帖人数4"  
  25. },  
  26. {  
  27. "image": "http://222.22.254.223:8080/web/e.jpg",  
  28. "title": "新闻标题5",  
  29. "content": "新闻内容5",  
  30. "conut": "跟帖人数5"  
  31. }  
  32. ]  


1.首先来看HttpURLConnection的Get方法获取json数据:

[java] view plaincopy
  1. public List<HeadNews> HttpURLConnection_GET()throws Exception{  
  2.   
  3.         List<HeadNews>list=new ArrayList<HeadNews>();  
  4.   
  5.         String path="http://222.22.254.223:8080/web/HeadNewsJson";  
  6.         //参数直接加载url后面  
  7.         path+="?username="+URLEncoder.encode("我是大帅哥HttpClientGET","utf-8");  
  8.         URL url=new URL(path);  
  9.         HttpURLConnection conn=(HttpURLConnection) url.openConnection();  
  10.         conn.setRequestMethod("GET");  
  11.         conn.setConnectTimeout(5000);  
  12.         if(conn.getResponseCode()==200){                //200表示请求成功  
  13.             InputStream is=conn.getInputStream();       //以输入流的形式返回  
  14.             //将输入流转换成字符串  
  15.             ByteArrayOutputStream baos=new ByteArrayOutputStream();  
  16.             byte [] buffer=new byte[1024];  
  17.             int len=0;  
  18.             while((len=is.read(buffer))!=-1){  
  19.                 baos.write(buffer, 0, len);  
  20.             }  
  21.             String jsonString=baos.toString();  
  22.             baos.close();  
  23.             is.close();  
  24.             //转换成json数据处理  
  25.             JSONArray jsonArray=new JSONArray(jsonString);  
  26.             for(int i=0;i<jsonArray.length();i++){       //一个循环代表一个headnews对象  
  27.                 HeadNews headnews=new HeadNews();  
  28.                 JSONObject jsonObject = jsonArray.getJSONObject(i);  
  29.                 headnews.setTitle(jsonObject.getString("title"));  
  30.                 headnews.setContent(jsonObject.getString("content"));  
  31.                 headnews.setConut(jsonObject.getString("conut"));  
  32.                 headnews.setImage(jsonObject.getString("image"));  
  33.                 list.add(headnews);  
  34.             }  
  35.               
  36.         }  
  37.         return list;  
  38.     }  

2.HttpURLConnection的POST方法获取json数据:

[java] view plaincopy
  1. public List<HeadNews>HttpURLConnection_POST() throws Exception{  
  2.     List<HeadNews>list=new ArrayList<HeadNews>();  
  3.       
  4.     String path="http://222.22.254.223:8080/web/HeadNewsJson";  
  5.     URL url=new URL(path);  
  6.     HttpURLConnection conn=(HttpURLConnection) url.openConnection();  
  7.   
  8.     conn.setDoOutput(true);             //允许向服务器输出数据  
  9.     conn.setDoInput(true);              //允许接收服务器数据  
  10.     conn.setRequestMethod("POST");  
  11.     conn.setUseCaches(false);           // Post 请求不能使用缓存  
  12.     conn.setConnectTimeout(5000);  
  13.     // 参数前面不能加?号  
  14.     String urlParas="username="+URLEncoder.encode("admin""UTF-8");  
  15.     byte [] entity=urlParas.getBytes();  
  16.     //设置请求参数  
  17.     conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");    //实体参数类型  
  18.     conn.setRequestProperty("Content-Length", entity.length+"");                    //实体参数长度  
  19.       
  20.     // 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成,  
  21.        // 要注意的是connection.getOutputStream会隐含的进行connect。  
  22.     conn.connect();  
  23.     //将要上传的参数写入流中  
  24.     conn.getOutputStream().write(entity);  
  25.       
  26.     if(conn.getResponseCode()==200){  
  27.         InputStream is=conn.getInputStream();  
  28.         //将输入流转换成字符串  
  29.         ByteArrayOutputStream baos=new ByteArrayOutputStream();  
  30.         byte [] buffer=new byte[1024];  
  31.         int len=0;  
  32.         while((len=is.read(buffer))!=-1){  
  33.             baos.write(buffer, 0, len);  
  34.         }  
  35.         String json=baos.toString();  
  36.         baos.close();  
  37.         is.close();  
  38.         //json处理  
  39.         JSONArray jsonArray=new JSONArray(json);  
  40.         for(int i=0;i<jsonArray.length();i++){  
  41.             HeadNews headnews=new HeadNews();  
  42.             JSONObject jsonObject = jsonArray.getJSONObject(i);  
  43.             headnews.setTitle(jsonObject.getString("title"));  
  44.             headnews.setContent(jsonObject.getString("content"));  
  45.             headnews.setConut(jsonObject.getString("conut"));  
  46.             headnews.setImage(jsonObject.getString("image"));  
  47.             list.add(headnews);  
  48.         }  
  49.     }  
  50.     return list;  
  51. }  
3.使用HttpClient的get方法获取Json:

[java] view plaincopy
  1. public List<HeadNews>HttpClient_GET() throws Exception{  
  2.   
  3.     List<HeadNews>list=new LinkedList<HeadNews>();  
  4.   
  5.     String path="http://222.22.254.223:8080/web/HeadNewsJson";  
  6.     //get方法设置参数要?号  
  7.     StringBuilder sb=new StringBuilder(path);  
  8.     sb.append("?");  
  9.     sb.append("username=").append(URLEncoder.encode("我是大帅哥HttpClientGET","utf-8"));  
  10.       
  11.     //1.得到浏览器  
  12.     HttpClient httpClient=new DefaultHttpClient();//浏览器   
  13.     //2指定请求方式  
  14.     HttpGet httpGet=new HttpGet(sb.toString());  
  15.     //3.执行请求  
  16.     HttpResponse httpResponse=httpClient.execute(httpGet);  
  17.     //4 判断请求是否成功  
  18.     int status=httpResponse.getStatusLine().getStatusCode();  
  19.       
  20.     if(status==200){  
  21.         //读取响应内容  
  22.         String result=EntityUtils.toString(httpResponse.getEntity(), "UTF-8");  
  23.         //json处理  
  24.         JSONArray jsonArray=new JSONArray(result);  
  25.         for(int i=0;i<jsonArray.length();i++){  
  26.             HeadNews headnews=new HeadNews();  
  27.             JSONObject jsonObject = jsonArray.getJSONObject(i);  
  28.             headnews.setTitle(jsonObject.getString("title"));  
  29.             headnews.setContent(jsonObject.getString("content"));  
  30.             headnews.setConut(jsonObject.getString("conut"));  
  31.             headnews.setImage(jsonObject.getString("image"));  
  32.             list.add(headnews);  
  33.         }  
  34.     }  
  35.     return list;  
  36. }  

4.使用HttpClient的post方法获取Json:

[java] view plaincopy
  1. public List<HeadNews>HttpClient_POST() throws Exception{  
  2.     List<HeadNews>list=new ArrayList<HeadNews>();  
  3.     String path="http://222.22.254.223:8080/web/HeadNewsJson";  
  4.   
  5.     //1.得到浏览器  
  6.     HttpClient httpClient=new DefaultHttpClient();  
  7.   
  8.     //2指定请求方式  
  9.     HttpPost httpPost=new HttpPost(path);  
  10.   
  11.     //3.构建请求实体的数据  
  12.     List<NameValuePair> paras=new ArrayList<NameValuePair>();  
  13.     paras.add(new BasicNameValuePair("username""我是帅哥httpclientPost"));  
  14.   
  15.     //4.构建实体  
  16.     UrlEncodedFormEntity entity=new UrlEncodedFormEntity(paras,"utf-8");  
  17.   
  18.     //5。。把实体放入请求对象  
  19.     httpPost.setEntity(entity);  
  20.   
  21.     //6.执行请求  
  22.     HttpResponse httpResponse=httpClient.execute(httpPost);  
  23.       
  24.     int status=httpResponse.getStatusLine().getStatusCode();  
  25.       
  26.     if(status==200){  
  27.         //读取响应内容  
  28.         String result=EntityUtils.toString(httpResponse.getEntity(), "UTF-8");  
  29.         //  
  30.         JSONArray jsonArray=new JSONArray(result);  
  31.         for(int i=0;i<jsonArray.length();i++){  
  32.             HeadNews headnews=new HeadNews();  
  33.             JSONObject jsonObject = jsonArray.getJSONObject(i);  
  34.             headnews.setTitle(jsonObject.getString("title"));  
  35.             headnews.setContent(jsonObject.getString("content"));  
  36.             headnews.setConut(jsonObject.getString("conut"));  
  37.             headnews.setImage(jsonObject.getString("image"));  
  38.             list.add(headnews);  
  39.         }  
  40.     }  
  41.     return list;  
  42. }  

另外提一点:

Get方式提交不论是HttpURLConnection还是HttpClient,传递中文参数会产生乱码,(传递方法看上面代码)

虽然已经用URLEncoder.encode("中文参数","utf-8")转成utf-8格式,在servlet端也使用spring过滤中文乱码,

但是仍然要这样子接收,不然会中文乱码(不知为何):


[java] view plaincopy
  1. new String(request.getParameter("username").getBytes("ISO-8859-1"),"UTF-8")  

Post方式接收中文参数则没有这个问题,直接:

[java] view plaincopy
  1. request.getParameter("username"


原文出处:HttpURLConnection和HttpClient获取Json数据

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值