Java后端发起https忽略SSL证书,防止报错

#记录一下工作中遇到的小问题#

HttpPost method = new HttpPost(url);
BasicCookieStore store = new BasicCookieStore();
HttpClient httpClient = null;
String result = null;
long requestTime = 0L;

//https 请求忽略证书
try {
    SSLContextBuilder builder = new SSLContextBuilder();
    builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
    SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(builder.build(), NoopHostnameVerifier.INSTANCE);
    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", new PlainConnectionSocketFactory()).register("https", sslConnectionSocketFactory).build();
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
    cm.setMaxTotal(100);

    httpClient = HttpClientBuilder.create().setSSLSocketFactory(sslConnectionSocketFactory).setConnectionManager(cm).setDefaultCookieStore(store).build();
} catch (NoSuchAlgorithmException e) {
    logger.error("https忽略SSL证书错误  错误信息:"+e.getMessage(),e);
    throw new RuntimeException(e);
} catch (KeyStoreException e) {
    logger.error("https忽略SSL证书错误  错误信息:"+e.getMessage()+" 请求Url="+url ,e);
    throw new RuntimeException(e);
} catch (KeyManagementException e) {
    logger.error("https忽略SSL证书错误 错误信息:"+e.getMessage()+" 请求Url="+url ,e);
    throw new RuntimeException(e);
}


if (method != null) {
    try {
       // 建立一个NameValuePair数组,用于存储欲传送的参数
       method.addHeader("Content-type",
             "application/json; charset=utf-8");
       method.setHeader("Accept", "application/json");
       method.setHeader("Connection", "close");

       long start = System.currentTimeMillis();
       HttpResponse response = httpClient.execute(method);

       requestTime = System.currentTimeMillis() - start;
       int statusCode = response.getStatusLine().getStatusCode();
       if (statusCode != HttpStatus.SC_OK) {
          logger.error("http请求失败:url=" + url + "----response=" + response.getStatusLine());

       } else {
          result = EntityUtils.toString(response.getEntity());
       }

    } catch (Exception e) {
       logger.info("URL = "+url+ " 返回结果 = ");
       logger.error("https请求错误! 错误信息:"+e.getMessage()+" 请求Url="+url ,e);
    } finally {
       if (method != null) {
          try {
             method.releaseConnection();
             // 关闭连接
             if (httpClient != null) {
                httpClient.getConnectionManager().shutdown();
             }
          } catch (Exception re) {
             logger.error(re.getMessage(),re);
          }
       }

    }

}
logger.info("https请求成功! 耗时={}ms Url={} return={}",requestTime, url,  result);
logger.info("URL = "+url+ " 返回结果 = "+result);

return result;
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java后端发起POST请求可以使用Java提供的HttpURLConnection类或者第三方库如Apache的HttpClient等。 下面是使用HttpURLConnection类发起POST请求的示例代码: ```java import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class HttpPostExample { public static void main(String[] args) throws Exception { String url = "http://example.com/api/endpoint"; // 请求的URL URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // 设置请求方法为POST con.setRequestMethod("POST"); // 设置请求头信息 con.setRequestProperty("User-Agent", "Mozilla/5.0"); con.setRequestProperty("Content-Type", "application/json"); // 设置POST请求参数 String requestBody = "{\"key\": \"value\"}"; con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(requestBody); wr.flush(); wr.close(); // 发起请求并获取响应 int responseCode = con.getResponseCode(); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // 输出响应结果 System.out.println("Response Code : " + responseCode); System.out.println("Response : " + response.toString()); } } ``` 其中,必须设置请求方法为POST,设置Content-Type为application/json等需要根据实际情况进行调整。 另外,如果需要进行HTTPS请求,需要额外设置SSL证书验证等操作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值