使用HttpClient访问https请求
获取CloseableHttpClient对象
public static CloseableHttpClient getCloseableHttpClent() throws KeyManagementException, NoSuchAlgorithmException { //采用绕过验证的方式处理https请求 SSLContext sslcontext = createIgnoreVerifySSL(); SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslcontext, NoopHostnameVerifier.INSTANCE); //创建自定义的httpclient对象 HostnameVerifier hostnameVerifier = new HostnameVerifier() { @Override public boolean verify(String s, SSLSession sslSession) { return true; } }; CloseableHttpClient client = HttpClients.custom(). setSSLHostnameVerifier(hostnameVerifier). setSSLContext(sslcontext). setSSLSocketFactory(sslConnectionSocketFactory).build(); return client; }
绕过验证
public static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException { SSLContext sc = SSLContext.getInstance(“SSLv3”); // 实现一个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; } }; sc.init(null, new TrustManager[]{trustManager}, null); return sc; }
自己封装一个调用接口的方法 在该方法里 我们调用了getCloseableHttpClent方法 获取了一个CloseableHttpClient 对象 该对象就可以直接访问https请求
public static HttpResponse get(String requestUrl, Map<String, Object> headers) throws Exception {
HttpGet httpget = new HttpGet(requestUrl);
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(9000).setConnectTimeout(9000).setConnectionRequestTimeout(9000).build();// 设置请求和传输超时时间
httpget.setConfig(requestConfig);
/**设置请求头**/
if (headers != null) {
Set<String> keySet = headers.keySet();
for (String key : keySet) {
httpget.addHeader(key, headers.get(key).toString());
}
}
CloseableHttpClient client = getCloseableHttpClent();
CloseableHttpResponse response = client.execute(httpget);
return response;
}
调用方法
public static void main(String[] args) throws Exception { HttpResponse httpResponse = get(“https://www.baidu.com”, null); if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { HttpEntity entity = httpResponse.getEntity(); if (entity != null) { String result = EntityUtils.toString(entity, “UTF-8”); System.out.println(result); } } }
访问结果如下 百度访问通了
|