如何解决httpclient调用https请求报错

public static String postJson(String url, String body, Map<String, String> headers) throws IOException {
  CloseableHttpClient httpclient = getClient();
  HttpPost httpPost = new HttpPost(url);
  httpPost.setHeader("Content-type", "application/json; charset=utf-8");

  if (headers != null && !headers.isEmpty()) {
    for (Map.Entry<String, String> entry : headers.entrySet()) {
      httpPost.addHeader(entry.getKey(), entry.getValue());
    }
  }

  StringEntity entity1 = new StringEntity(body, ENCODING);
  entity1.setContentType("application/json;charset=UTF-8");
  httpPost.setEntity(entity1);
  HttpResponse response = httpclient.execute(httpPost);
  HttpEntity entity = response.getEntity();
  String content = EntityUtils.toString(entity, ENCODING);
  EntityUtils.consume(entity);
  return content;
}

public static CloseableHttpClient getClient() {

        SSLContext sslContext = null;

        try {

            sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {

                // 信任所有

                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {

                    return true;

                }

            }).build();

        } catch (NoSuchAlgorithmException ex) {

            Logger.getLogger(VerfiyCodeUtils.class.getName()).log(Level.SEVERE, null, ex);

        } catch (KeyStoreException ex) {

            Logger.getLogger(VerfiyCodeUtils.class.getName()).log(Level.SEVERE, null, ex);

        } catch (KeyManagementException ex) {

            Logger.getLogger(VerfiyCodeUtils.class.getName()).log(Level.SEVERE, null, ex);

        }

        //NoopHostnameVerifier类:  作为主机名验证工具,实质上关闭了主机名验证,它接受任何有效的SSL会话并匹配到目标主机。

        HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;

        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);

        CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();

        return httpClient;

    }

public static void main(String[] args){

    HttpPost httpPost = new HttpPost("https:abc");

  CloseableHttpClient httpClient = getClient();

   CloseableHttpResponse response = httpClient.execute(httpPost);

    }

biaodan 
// 发送POST请求
public static String sendPost(String url, String data) throws Exception {
    // 创建连接
    URL connUrl = new URL(url);
    HttpURLConnection conn = (HttpURLConnection) connUrl.openConnection();
    // 判断是否为HTTPS请求
    if (conn instanceof HttpsURLConnection) {
        // 跳过HTTPS证书验证
        SSLContext sslContext = SSLContext.getInstance("SSL");
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
            public void checkClientTrusted(X509Certificate[] certs, String authType) {}
            public void checkServerTrusted(X509Certificate[] certs, String authType) {}
        } };
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        ((HttpsURLConnection) conn).setSSLSocketFactory(sslContext.getSocketFactory());
        ((HttpsURLConnection) conn).setHostnameVerifier((hostname, session) -> true);
    }
    // 设置请求头
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setRequestProperty("Accept-Charset", "utf-8");
    // 发送POST请求
    conn.setDoOutput(true);
    try (OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), "UTF-8")) {
        writer.write(data);
        writer.flush();
    }
    // 读取响应
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"))) {
        StringBuilder response = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        return response.toString();
    }
}
// 发送POST请求(参数为Map)
public static String sendPost(String url, Map<String, String> params) throws Exception {
    StringBuilder data = new StringBuilder();
    for (Map.Entry<String, String> entry : params.entrySet()) {
        if (data.length() > 0) {
            data.append("&");
        }
        data.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
        data.append("=");
        data.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
    }
    return sendPost(url, data.toString());
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值