package com.xkrs.utils; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.config.Registry; import org.apache.http.config.RegistryBuilder; import org.apache.http.conn.socket.ConnectionSocketFactory; import org.apache.http.conn.socket.PlainConnectionSocketFactory; import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.TrustSelfSignedStrategy; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.ssl.SSLContexts; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; /** * http工具类 */ public class HttpClientUtils { private static final Logger log = LoggerFactory.getLogger(HttpClientUtils.class); /** * 发送http+get请求 * * @param url * @return 返回结果 * @throws Exception */ public static String sendHttpGet(String url) throws Exception { CloseableHttpClient httpClient = HttpClients.createDefault(); return doGet(url, httpClient); } /** * 发送https+get请求,绕过证书 * * @param url 请求地址 * @return 返回结果 * @throws Exception */ public static String sendHttpsGet(String url) throws Exception { // CloseableHttpClient httpClient = createIgnoreVerifyHttpClient(); //CloseableHttpClient httpClient = HttpClients.createDefault(); SSLConnectionSocketFactory scsf = new SSLConnectionSocketFactory(SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(), NoopHostnameVerifier.INSTANCE); CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(scsf).build(); return doGet(url, httpClient); } /** * 发送http+post请求 * * @param url 请求地址 * @param params 请求参数 json字符串 * @return 返回结果 * @throws Exception */ public static String sendHttpPost(String url, String params) throws Exception { CloseableHttpClient httpClient = HttpClients.createDefault(); return doPost(httpClient, url, params); } public static String sendHttpPostTextPlain(String url, String params) throws Exception { CloseableHttpClient httpClient = HttpClients.createDefault(); return doPostTextPlain(httpClient, url, params); } private static String doPostTextPlain(CloseableHttpClient httpClient, String url, String params) throws Exception { log.info("Post请求url:{}", url); log.info("Post请求params:{}", params); HttpPost httpPost = new HttpPost(url); httpPost.addHeader("Content-Type", "application/json; charset=utf-8"); StringEntity requestEntity = new StringEntity(params, "UTF-8"); requestEntity.setContentType("text/plain"); requestEntity.setContentEncoding("UTF-8"); httpPost.setEntity(requestEntity); return execute(httpClient, httpPost); } /** * 发送https+post请求 * * @param url 请求地址 * @param params 请求参数 json字符串 * @return 返回结果 * @throws Exception */ public static String sendHttpsPost(String url, String params) throws Exception { // CloseableHttpClient httpClient = createIgnoreVerifyHttpClient(); // CloseableHttpClient httpClient = null; SSLConnectionSocketFactory scsf = new SSLConnectionSocketFactory(SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(), NoopHostnameVerifier.INSTANCE); CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(scsf).build(); // CloseableHttpClient httpClient = HttpClients.createDefault(); return doPost(httpClient, url, params); } /** * 封装get请求方式的处理 */ private static String doGet(String url, CloseableHttpClient httpClient) throws Exception { log.info("HGet请求url={}", url); HttpGet httpGet = new HttpGet(url); return execute(httpClient, httpGet); } /** * 封装post请求方式的处理 */ private static String doPost(CloseableHttpClient httpClient, String url, String params) throws Exception { log.info("Post请求url:{}", url); log.info("Post请求params:{}", params); HttpPost httpPost = new HttpPost(url); httpPost.addHeader("Content-Type", "application/json; charset=utf-8"); httpPost.setEntity(new StringEntity(params)); return execute(httpClient, httpPost); } /** * 执行发送 */ private static String execute(CloseableHttpClient httpClient, HttpRequestBase requestBase) throws Exception { String result = null; CloseableHttpResponse response = null; try { response = httpClient.execute(requestBase); int statusCode = response.getStatusLine().getStatusCode(); log.info("HttpClient响应码={}", statusCode); final int success = 200; if (statusCode == success) { result = EntityUtils.toString(response.getEntity(), "utf-8"); } else { log.error("HttpClient请求失败,错误码={}", statusCode); } } catch (Exception e) { log.error("HttpClient请求异常:", e); } finally { if (null != httpClient) { httpClient.close(); } if (null != response) { response.close(); } } log.info("HttpClient请求结果:{}", result); return result; } /** * 绕过验证 * * @return * @throws NoSuchAlgorithmException * @throws KeyManagementException */ public static CloseableHttpClient createIgnoreVerifyHttpClient() throws Exception { SSLContext sslContext = SSLContext.getInstance("TLS"); // 实现一个X509TrustManager接口 X509TrustManager trustManager = new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] paramArrayOfX509Certificate, String paramString) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] paramArrayOfX509Certificate, String paramString) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return null; } }; sslContext.init(null, new TrustManager[]{trustManager}, null); Registry socketFactoryRegistry = RegistryBuilder.create().register("http", PlainConnectionSocketFactory.INSTANCE).register("https", new SSLConnectionSocketFactory(sslContext)).build(); PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry); CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connManager).build(); return httpClient; } }