189 8069 5689

Http、Https请求工具类-创新互联

1. maven引入httpclient依赖
  org.apache.httpcomponents   httpclient  4.5.12
2. GET请求
public static String doGet(String path, Mapparam, Mapheaders) {
    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.Entryentry : 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, Mapheaders) {
    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.Entryentry : 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

创新互联于2013年开始,先为固阳等服务建站,固阳等地企业,进行企业商务咨询服务。为固阳企业网站制作PC+手机+微官网三网同步一站式服务解决您的所有建站问题。
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链接工厂的对象
    RegistrysocketFactoryRegistry = RegistryBuilder.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;
    }

你是否还在寻找稳定的海外服务器提供商?创新互联www.cdcxhl.cn海外机房具备T级流量清洗系统配攻击溯源,准确流量调度确保服务器高可用性,企业级服务器适合批量采购,新人活动首月15元起,快前往官网查看详情吧


新闻标题:Http、Https请求工具类-创新互联
文章位置:http://cdxtjz.cn/article/hjcoe.html

其他资讯