java httpClient 禁用证书验证
/** * post调用禁用ssl * @param url--请求url * @param param--入参 * @param overTime--超时时间 * @param contentType--http内容类型 * @return * @throws Exception */ public static String doHttpPostNoSsl(String url,String param,int overTime,String contentType) throws Exception { CloseableHttpResponse response = null; String resultString = ""; CloseableHttpClient httpClient = null; try { // 创建SSLContext并禁用证书验证 /** SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, null, new java.security.SecureRandom()); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( sslContext, NoopHostnameVerifier.INSTANCE); **/ SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null,new TrustStrategy(){ //信任所有证书 public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { return true; } }).build(); //创建主机名验证器,用于绕过主机名验证 HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE; //创建SSL连接套接字工厂,将自定义的SSL上下文和主机名验证器应用于HTTPS连接 SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,hostnameVerifier); RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(overTime).setConnectTimeout(overTime).setConnectionRequestTimeout(overTime).build(); //这个超时可以设置为客户端级别,作为所有请求的默认值 httpClient = HttpClients.custom() //.setDefaultRequestConfig(defaultRequestConfig) .setSSLSocketFactory(sslsf) .build(); //Request不会继承客户端级别的请求配置,所以在自定义Request的时候,需要将客户端的默认配置拷贝过去 RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig).build(); //创建Http post请求 HttpPost httpPost = new HttpPost(url); httpPost.setHeader("Content-Type", contentType); httpPost.setConfig(requestConfig); if(StringUtils.isNotBlank(param)){ StringEntity se = new StringEntity(param,"utf-8"); se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,contentType)); httpPost.setEntity(se); } //执行http请求 response = httpClient.execute(httpPost); resultString = EntityUtils.toString(response.getEntity(), "utf-8"); log.info(sep + ">>>>>>>>>>>>>>>>>>>post调用>>>>>>>>>>>>>>>>>>>>>>>>" + sep + "【url】:{}" + sep + "【param】:{}" + sep + "【response】:{}" + sep + "<<<<<<<<<<<<<<<<<<<<<post调用<<<<<<<<<<<<<<<<<<<<<<<",url,param,resultString); } catch (Exception e) { logger.error(e.getMessage()); throw new Exception(e.getMessage()); } finally { try { if (response != null) { response.close(); } if (httpClient != null) { httpClient.close(); } } catch (IOException e) { logger.error(e.getMessage()); } } return resultString; }
好记性不如烂笔头
浙公网安备 33010602011771号