• HttpUtil工具类,发送Get/Post请求,支持Http和Https协议


    HttpUtil工具类,发送Get/Post请求,支持Http和Https协议

    使用用Httpclient封装的HttpUtil工具类,发送Get/Post请求

    1. maven引入httpclient依赖

      <dependency>
          <groupId>org.apache.httpcomponents</groupId>
          <artifactId>httpclient</artifactId>
          <version>4.5.12</version>
      </dependency>
    

    2. GET请求

    public static String doGet(String path, Map<String, String> param, Map<String, String> headers) {
        HttpGet httpGet = null;
        CloseableHttpResponse response = null;
        CloseableHttpClient httpClient = wrapClient(path);
        // 创建uri
        URIBuilder builder = null;
        try {
            builder = new URIBuilder(path);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();
            // 创建http GET请求
            httpGet = new HttpGet(uri);
            if (headers != null && headers.size() > 0) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    httpGet.addHeader(entry.getKey(), entry.getValue());
                }
            }
    
            // 执行请求
            response = httpClient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                return EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            throw new RuntimeException("[发送Get请求错误:]" + e.getMessage());
        } finally {
            try {
                httpGet.releaseConnection();
                response.close();
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    

    3. POST请求

    public static String doPostJson(String url, String jsonParam, Map<String, String> headers) {
        HttpPost httpPost = null;
        CloseableHttpResponse response = null;
        CloseableHttpClient httpClient = wrapClient(url);
        try {
            httpPost = new HttpPost(url);
            //addHeader,如果Header没有定义则添加,已定义则不变,setHeader会重新赋值
            httpPost.addHeader("Content-type","application/json;charset=utf-8");
            httpPost.setHeader("Accept", "application/json");
            StringEntity entity = new StringEntity(jsonParam, StandardCharsets.UTF_8);
    //            entity.setContentType("text/json");
    //            entity.setContentEncoding(new BasicHeader("Content-Type", "application/json;charset=UTF-8"));
            httpPost.setEntity(entity);
            //是否有header
            if (headers != null && headers.size() > 0) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    httpPost.addHeader(entry.getKey(), entry.getValue());
                }
            }
            // 执行请求
            response = httpClient.execute(httpPost);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                return EntityUtils.toString(response.getEntity(), "UTF-8");
            }
    
        } catch (Exception e) {
            throw new RuntimeException("[发送POST请求错误:]" + e.getMessage());
        } finally {
            try {
                httpPost.releaseConnection();
                response.close();
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    

    3. 获取httpclient的方法

    这里会根据url自动匹配需要的是http的还是https的client

      private static CloseableHttpClient wrapClient(String url) {
          CloseableHttpClient client = HttpClientBuilder.create().build();
          if (url.startsWith("https")) {
              client = getCloseableHttpsClients();
          }
          return client;
      }
    

    4. 对于https的需要自己实现一下client

    private static CloseableHttpClient getCloseableHttpsClients() {
        // 采用绕过验证的方式处理https请求
        SSLContext sslcontext = createIgnoreVerifySSL();
        // 设置协议http和https对应的处理socket链接工厂的对象
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.INSTANCE)
                .register("https", new SSLConnectionSocketFactory(sslcontext)).build();
        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        HttpClients.custom().setConnectionManager(connManager);
        // 创建自定义的httpsclient对象
        CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).build();
        return client;
    }
    private static SSLContext createIgnoreVerifySSL() {
            // 创建套接字对象
            SSLContext sslContext = null;
            try {
                //指定TLS版本
                sslContext = SSLContext.getInstance("TLSv1.2");
            } catch (NoSuchAlgorithmException e) {
                throw new RuntimeException("[创建套接字失败:] " + e.getMessage());
            }
            // 实现X509TrustManager接口,用于绕过验证
            X509TrustManager trustManager = new X509TrustManager() {
                @Override
                public void checkClientTrusted(java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
                                               String paramString) throws CertificateException {
                }
    
                @Override
                public void checkServerTrusted(java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
                                               String paramString) throws CertificateException {
                }
    
                @Override
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            };
            try {
                //初始化sslContext对象
                sslContext.init(null, new TrustManager[]{trustManager}, null);
            } catch (KeyManagementException e) {
                throw new RuntimeException("[初始化套接字失败:] " + e.getMessage());
            }
            return sslContext;
        }
    

    以上全部都测试通过,如果有错误,欢迎大佬们指出,感谢!!!

    备注:完整版的点这里

    让坚持成为品质,让优秀成为习惯!加油!

  • 相关阅读:
    面试题 33 把数组排成最小的数
    面试题32 1的数目
    面试题29 数组中出现次数超过一半的数字
    LeetCode_Combination Sum II
    LeetCode_Combination Sum
    面试题27 二叉搜索树转换为双向链表
    面试题26 复杂链表的复制
    面试题24 二叉搜索树的后序遍历序列
    LeetCode_Binary Tree Inorder Traversal
    省选模拟57 题解
  • 原文地址:https://www.cnblogs.com/baijinqiang/p/13072050.html
Copyright © 2020-2023  润新知