java httpclient https 请求

java 使用httpClient 进行http请求报错:

java.lang.AssertionError: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

后添加如下方法:跳过ssl验证

public static CloseableHttpClient createSSLClientDefault() {
        try {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                //信任所有
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            }).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

            return HttpClients.custom().setSSLSocketFactory(sslsf).build();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        }
        return HttpClients.createDefault();
    }

post请求:

 public static String doHttpsPost(String url, Map<String, Object> paramMap,String proxyIp,int proxyPort,String proxyScheme,String... authori) throws Exception {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        String result = "";
        // 创建httpClient实例
        httpClient = createSSLClientDefault();
        // 创建httpPost远程连接实例
        HttpPost httpPost = new HttpPost(url);
        if(authori !=null && authori.length > 0 && StringUtils.isNotEmpty(authori[0])) {
            httpPost.addHeader("token", authori[0]);
        }
        else{
            httpPost.addHeader("token", "");

        }

        // 配置请求参数实例


        HttpHost proxy = new HttpHost(proxyIp, proxyPort, proxyScheme);
        RequestConfig requestConfig = RequestConfig.custom()
                .setProxy(proxy)//
                .setConnectTimeout(35000)// 设置连接主机服务超时时间
                .setConnectionRequestTimeout(35000)// 设置连接请求超时时间
                .setSocketTimeout(60000)// 设置读取数据连接超时时间
                .build();
        // 为httpPost实例设置配置
        httpPost.setConfig(requestConfig);
        // 设置请求头
        httpPost.addHeader("Content-type", "application/json; charset=utf-8");
        //httpPost.addHeader("Proxy-Connection", "keep-alive");

        // 为httpPost设置封装好的请求参数
        if(paramMap != null && paramMap.size() > 0) {
            StringEntity entityRequest = new StringEntity(JSONObject.fromObject(paramMap).toString(), Charset.forName("UTF-8"));
            entityRequest.setContentType("application/json");
            httpPost.setEntity(entityRequest);

        }

        try {
            // httpClient对象执行post请求,并返回响应参数对象


            httpResponse = httpClient.execute(httpPost);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK || statusCode == 201 || statusCode == 401) {
                // 从响应对象中获取响应内容
                HttpEntity entity = httpResponse.getEntity();

                result = EntityUtils.toString(entity);
            }
            else{
                Assert.assertTrue(false,"接口调用失败,返回code=" + statusCode);
            }
        } catch (ClientProtocolException e) {
            Assert.assertTrue(false,e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            Assert.assertTrue(false,e.getMessage());

            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != httpResponse) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    Assert.assertTrue(false,e.getMessage());

                    e.printStackTrace();
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    Assert.assertTrue(false,e.getMessage());

                    e.printStackTrace();
                }
            }
        }
        return result;
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要使用Java HttpClient发起请求,你可以按照以下步骤进行操作: 1. 首先,创建一个HttpPost对象,将请求的URL作为参数传递给它。可以使用引用中的示例代码中的以下行完成此步骤: ``` HttpPost httpPost = new HttpPost(url); ``` 2. 接下来,创建一个CloseableHttpClient对象,可以使用引用中的示例代码中的以下行完成此步骤: ``` CloseableHttpClient httpClient = HttpClientBuilder.create().build(); ``` 3. 设置请求的数据格式和内容。你可以使用StringEntity类创建一个包含请求数据的实体。可以使用引用中的示例代码中的以下行完成此步骤: ``` StringEntity entity = new StringEntity(jsonData, "utf-8"); entity.setContentEncoding("UTF-8"); entity.setContentType("application/json"); httpPost.setEntity(entity); ``` 4. 执行POST请求并获取响应结果。可以使用httpClient的execute方法来执行请求,并使用HttpResponse对象接收响应结果。你可以根据需要使用不同的方法来处理响应结果。例如,可以使用BasicResponseHandler类的实例来处理响应结果字符串。可以使用引用中的示例代码中的以下行完成此步骤: ``` BasicResponseHandler handler = new BasicResponseHandler(); result = httpClient.execute(httpPost, handler); ``` 5. 最后,记得释放连接。可以使用httpClient的close方法来关闭连接。可以使用引用中的示例代码中的以下行完成此步骤: ``` httpClient.close(); ``` 综上所述,以上步骤提供了一个示例的Java HttpClient发起请求的过程。根据你的需求,你还可以根据具体的情况进行适当的调整和扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值