CloseableHttpResponse

最近在使用Apache的httpclient的时候,maven引用了最新版本4.3,发现Idea提示DefaultHttpClient等常用的类已经不推荐使用了,之前在使用4.2.3版本的时候,还没有被deprecated。去看了下官方文档,确实不推荐使用了,点击此处详情

  • DefaultHttpClient —> CloseableHttpClient
  • HttpResponse —> CloseableHttpResponse

官方给出了新api的样例,如下。

Get方法:

    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet("http://targethost/homepage");
    CloseableHttpResponse response1 = httpclient.execute(httpGet);
    // The underlying HTTP connection is still held by the response object
    // to allow the response content to be streamed directly from the network socket.
    // In order to ensure correct deallocation of system resources
    // the user MUST either fully consume the response content  or abort request
    // execution by calling CloseableHttpResponse#close().
    //建立的http连接,仍旧被response1保持着,允许我们从网络socket中获取返回的数据
    //为了释放资源,我们必须手动消耗掉response1或者取消连接(使用CloseableHttpResponse类的close方法)

    try {
        System.out.println(response1.getStatusLine());
        HttpEntity entity1 = response1.getEntity();
        // do something useful with the response body
        // and ensure it is fully consumed
        EntityUtils.consume(entity1);
    } finally {
        response1.close();
    }

Post方法:

    HttpPost httpPost = new HttpPost("http://targethost/login");
    //拼接参数
    List <NameValuePair> nvps = new ArrayList <NameValuePair>();
    nvps.add(new BasicNameValuePair("username", "vip"));
    nvps.add(new BasicNameValuePair("password", "secret"));
    httpPost.setEntity(new UrlEncodedFormEntity(nvps));
    CloseableHttpResponse response2 = httpclient.execute(httpPost);

    try {
        System.out.println(response2.getStatusLine());
        HttpEntity entity2 = response2.getEntity();
        // do something useful with the response body
        // and ensure it is fully consumed
        //消耗掉response
        EntityUtils.consume(entity2);
    } finally {
        response2.close();
    }

再往下看HttpClients的源码,具体的实现都在HttpClientBuilderbuild方法中,有兴趣的可以去apache看源码。

    /**
    * Creates {@link CloseableHttpClient} instance with default
    * configuration.
    */
    public static CloseableHttpClient createDefault() {
        return HttpClientBuilder.create().build();
    }


开发环境:Maven3.3.9

   IDEA2016.2.1

[java]  view plain  copy
  1. import net.sf.json.JSONArray;  
  2. import net.sf.json.JSONObject;  
  3. import org.apache.http.HttpEntity;  
  4. import org.apache.http.HttpResponse;  
  5. import org.apache.http.client.methods.HttpGet;  
  6. import org.apache.http.impl.client.CloseableHttpClient;  
  7. import org.apache.http.impl.client.HttpClientBuilder;  
  8. import org.apache.http.util.EntityUtils;  
  9.   
  10. import java.io.IOException;  
  11. import java.util.ArrayList;  
  12. import java.util.List;  
  13.   
  14. /** 
  15.  * Created by 清水66 on 2017/8/28. 
  16.  */  
  17. public class JsonGet {  
  18.     public static void main(String[] args){  
  19.         //创建HttpClientBuilder  
  20.         HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();  
  21.         //HttpClient  
  22.         CloseableHttpClient closeableHttpClient = httpClientBuilder.build();  
  23.         HttpGet httpGet = new HttpGet("http://android.myapp.com/myapp/app/comment.htm?apkName=com.youcash.ZYWallet&apkCode=157&p=1&fresh=0.02709822286851704&contextData=");  
  24.         System.out.println(httpGet.getRequestLine());  
  25.         try {  
  26.             //执行get请求  
  27.             HttpResponse httpResponse = closeableHttpClient.execute(httpGet);  
  28.             //获取响应消息实体  
  29.             HttpEntity entity = httpResponse.getEntity();  
  30.             //响应状态  
  31.             System.out.println("status:" + httpResponse.getStatusLine());  
  32.             //判断响应实体是否为空  
  33.             if (entity != null) {  
  34.                 System.out.println("contentEncoding:" + entity.getContentEncoding());  
  35.                 parseJsonGet(EntityUtils.toString(entity));  
  36.             }  
  37.         } catch (IOException e) {  
  38.             e.printStackTrace();  
  39.         } finally {  
  40.             try {                //关闭流并释放资源  
  41.                 closeableHttpClient.close();  
  42.             } catch (IOException e) {  
  43.                 e.printStackTrace();  
  44.             }  
  45.         }  
  46.     }  
  47.     //解析Json数据  
  48.     public static void parseJsonGet(String jsonString){  
  49.         JSONObject jsonObject = JSONObject.fromObject(jsonString);  
  50.         //AppCommentsData类,存放评论的作者、评论内容等  
  51.         List<AppCommentsData> list = new ArrayList<AppCommentsData>();  
  52.         JSONObject obj= jsonObject.getJSONObject("obj");  
  53.         //商品评论信息  
  54.         JSONArray jsonArray = obj.getJSONArray("commentDetails");  
  55.         for(int i =0;i<jsonArray.size();i++){  
  56.             AppCommentsData appCommentsData = new AppCommentsData();  
  57.             appCommentsData.setApp_id(1);  
  58.             appCommentsData.setStore_id(1011);  
  59.             //评论作者  
  60.             appCommentsData.setAuthor(jsonArray.getJSONObject(i).getString("nickName"));  
  61.             //商品评论内容  
  62.             appCommentsData.setData(jsonArray.getJSONObject(i).getString("content"));  
  63.             //评分  
  64.             appCommentsData.setScore(jsonArray.getJSONObject(i).getInt("score"));  
  65.             list.add(appCommentsData);  
  66.         }  
  67.         System.out.println("输出appCommentsData//");  
  68.         for (int i=0;i<list.size();i++){  
  69.             AppCommentsData appCommentsData = list.get(i);  
  70.             System.out.println("name: ="+appCommentsData.getAuthor());  
  71.             System.out.println("content: ="+appCommentsData.getData());  
  72.             System.out.println("score: ="+appCommentsData.getScore());  
  73.         }  
  74.     }  
  75. }  
类AppCommentsData如下:

[html]  view plain  copy
  1. /**  
  2.  * Created by 清水66 on 2017/8/22.  
  3.  */  
  4. public class AppCommentsData {  
  5.     int id;  
  6.     int app_id;//app的id  
  7.     int store_id;//应用商店id  
  8.     String author;//评论人  
  9.     int score;//评分  
  10.     String  data;//评论内容  
  11.     //生成getter.setter方法  
  12. }  
注意;1)在获取评论内容时,并把评论内容插入MySQL数据库时,由于评论内容有表情符号会报 Incorrect string value: '\xF0\x9F\x98\xAD",...'  错误,

2)网络上建议把UTF-8改为utf8mb4,但是尝试了几个帖子上的操作没有成功,

        3)本人把评论内容的表情去掉插入数据库中了

[java]  view plain  copy
  1. String content = jsonArray.getJSONObject(i).getString("content").replaceAll("[\\x{10000}-\\x{10FFFF}]""");  
  2.             appCommentsData.setData(content);  

  • 6
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值