zoukankan      html  css  js  c++  java
  • HttpClient 模拟发送Post和Get请求 并用fastjson对返回json字符串数据解析,和HttpClient一些参数方法的deprecated(弃用)的综合总结

    最近在做一个接口调用的时候用到Apache的httpclient时候,发现引入最新版本4.5,DefaultHttpClient等老版本常用的类已经过时了,不推荐使用了;去官网看了一下在4.3之后就抛弃了。

    可以参考:

    点击此处详情 推荐使用 CloseableHttpClient

    点击此处详情 设置过时参数等类也已经在4.3过后不推荐使用

      DefaultHttpClient --> CloseableHttpClient

    HttpClient httpClient=new DefaultHttpClient(); --> CloseableHttpClient httpClient = HttpClients.createDefault();

    HttpResponse --> CloseableHttpResponse
    HttpResponse httpResponse = httpClient.execute(httpPost); --> CloseableHttpResponse httpResponse = httpClient.execute(httpPost);

    Post请求

    /**
         * Post方式 得到JSONObject
         *
         * @param paramsHashMap post参数
         * @param url
         * @param encoding 编码utf-8
         * @return
         */
        public JSONObject getJSONObjectByPost(Map<String, String> paramsHashMap, String url, String encoding) {
            //创建httpClient连接
            CloseableHttpClient httpClient = HttpClients.createDefault();
    
            JSONObject result = null;
        //json方式
        //JSONObject jsonParam = new JSONObject();
        //jsonParam.put("name", "admin");
        //jsonParam.put("pass", "123456");
        //StringEntity entity = new StringEntity(jsonParam.toString(),"utf-8");
        //解决中文乱码问题
        //entity.setContentEncoding("UTF-8");
        //entity.setContentType("application/json");
        //httpPost.setEntity(entity);

        //表单方式 List
    <NameValuePair> nameValuePairArrayList = new ArrayList<NameValuePair>(); // 将传过来的参数添加到List<NameValuePair>中 if (paramsHashMap != null && !paramsHashMap.isEmpty()) { //遍历map for (Map.Entry<String, String> entry : paramsHashMap.entrySet()) { nameValuePairArrayList.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } }
         try { // 利用List<NameValuePair>生成Post请求的实体数据 HttpPost httpPost = new HttpPost(url); // 为HttpPost设置实体数据 UrlEncodedFormEntity 把输入数据编码成合适的内容   httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairArrayList, encoding)); // HttpClient 发送Post请求 CloseableHttpResponse httpResponse = httpClient.execute(httpPost); if (httpResponse.getStatusLine().getStatusCode() == 200) { // CloseableHttpResponse HttpEntity httpEntity = httpResponse.getEntity(); if (httpEntity != null) { BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(httpEntity.getContent(), "UTF-8"), 10 * 1024); StringBuilder strBuilder = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { strBuilder.append(line); } // 用fastjson的JSON将返回json字符串转为json对象 result = JSON.parseObject(strBuilder.toString()); } catch (Exception e) { e.printStackTrace(); } finally { if (reader != null) { try { //关闭流 reader.close(); } catch (IOException e) { e.printStackTrace(); } } } } } } catch (Exception e) { e.printStackTrace(); } return result; }

    Get请求

    public JSONObject getJSONObjectByGet(String url){
            JSONObject resultJsonObject=null;
           
            //创建httpClient连接
            CloseableHttpClient httpClient = HttpClients.createDefault();
    
            StringBuilder urlStringBuilder=new StringBuilder(url);
            StringBuilder entityStringBuilder=new StringBuilder();
            //利用URL生成一个HttpGet请求
            HttpGet httpGet=new HttpGet(urlStringBuilder.toString());
            // HttpClient 发送Post请求
            CloseableHttpResponse httpResponse = null;
            try {
                httpResponse=httpClient.execute(httpGet);
            } catch (Exception e) {
                e.printStackTrace();
            }
            //得到httpResponse的状态响应码
            if (httpResponse.getStatusLine().getStatusCode()== HttpStatus.SC_OK) {
                //得到httpResponse的实体数据
                HttpEntity httpEntity=httpResponse.getEntity();
                if (httpEntity!=null) {
                    BufferedReader reader=null;
                    try {
                        reader=new BufferedReader(new InputStreamReader(httpEntity.getContent(), "UTF-8"), 8*1024);
                        String line=null;
                        while ((line=reader.readLine())!=null) {
                            entityStringBuilder.append(line);
                        }
                        // 从HttpEntity中得到的json String数据转为json
                        String json=entityStringBuilder.toString();
                        resultJsonObject=JSON.parseObject(json);
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        if (reader != null) {
                            try {
                                //关闭流
                                reader.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
            return resultJsonObject;
        }
    本文结合自己经历及收集网络知识综合个人总结,只为分享技术,方便解决问题,如有侵犯版权信息等,请联系我!
  • 相关阅读:
    [导入]匹配正则表达式的函数BOOL型(修正一下)
    [导入]得到当前网页文件名(不含路径)的小函数,如果有效率更高的请回帖评论
    [导入]约瑟夫环VC2005
    [导入]《菊花台》的歌词LRC文件
    [导入]一段不太好的代码:IE主页不是本站地址就不充许访问或下载
    [导入]ALASTART.EXE木马清除
    [导入]编程意识
    [导入]人若其名
    vueresource安装与使用
    com复合文档存储及持久化
  • 原文地址:https://www.cnblogs.com/boris-et/p/7922267.html
Copyright © 2011-2022 走看看