admin管理员组文章数量:1794759
util
HttpClientUtil 可根据需求修改
import hk.ha.epr.exception.CommException;
import org.apache.http.Header;
import org.apache.http.client.config.RequestConfig;
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.SSLConnectionSocketFactory;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;import javax.ssl.SSLContext;
import javax.ssl.TrustManager;
import javax.ssl.X509TrustManager;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;public class HttpClientUtils {private static final Logger log = LoggerFactory.getLogger(HttpClientUtils.class);public static InputStream doGet(String url) throws IOException, GeneralSecurityException {return doGet(url, null, -1);}public static InputStream doGet(String url, int timeOut) throws IOException, GeneralSecurityException {return doGet(url, null, timeOut);}public static InputStream doGet(String url, Map<String, String> headers) throws IOException, GeneralSecurityException {return doGet(url, headers, -1);}public static InputStream doGet(String url, Map<String, String> headers, int timeOut) throws IOException, GeneralSecurityException {url = url.trim().replace("\\", "/");CloseableHttpClient client = getClient(url);HttpGet httpGet = new HttpGet(url);RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeOut).build();httpGet.setConfig(requestConfig);addHeaders(httpGet, headers);return execute(client, httpGet);}public static InputStream doPost(String url, String entity) throws GeneralSecurityException, IOException {return doPost(url, entity, null, null, -1);}public static InputStream doPost(String url, String entity, int timeOut) throws GeneralSecurityException, IOException {return doPost(url, entity, null, null, timeOut);}public static InputStream doPost(String url, String entity, Map<String, String> headers) throws GeneralSecurityException, IOException {return doPost(url, entity, headers, null, -1);}public static InputStream doPost(String url, String entity, Map<String, String> headers, String charset, int timeOut) throws GeneralSecurityException, IOException {if (!StringUtils.hasText(charset)) {charset = "UTF-8";}url = url.trim().replace("\\", "/");CloseableHttpClient client = getClient(url);HttpPost httpPost = new HttpPost(url);RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeOut * 1000).build();httpPost.setConfig(requestConfig);addHeaders(httpPost, headers);Header contentType = httpPost.getFirstHeader("Content-Type");if (contentType == null) {httpPost.addHeader("Content-Type", "application/json; charset=utf-8");}httpPost.setEntity(new StringEntity(entity, charset));return execute(client, httpPost);}private static CloseableHttpClient getClient(String url) throws GeneralSecurityException {if (!StringUtils.hasText(url)) {throw new CommException("url is empty");}CloseableHttpClient httpClient;if (url.toUpperCase().contains("HTTPS")) {httpClient = createIgnoreVerifyHttpClient();} else {httpClient = HttpClients.createDefault();}return httpClient;}private static void addHeaders(HttpRequestBase http, Map<String, String> headers) {if (headers == null) {return;}for (Map.Entry<String, String> entry : headers.entrySet()) {http.addHeader(entry.getKey(), entry.getValue());}}private static InputStream execute(CloseableHttpClient httpClient, HttpRequestBase requestBase) throws IOException {InputStream result = null;CloseableHttpResponse response = null;try {response = httpClient.execute(requestBase);int statusCode = response.getStatusLine().getStatusCode();log.info("HttpClient statusCode={}", statusCode);if (statusCode == 200) {result = response.getEntity().getContent();} else {log.error("HttpClient is fail,errorCode={}", statusCode);}} catch (Exception e) {log.error("HttpClient error:{}", e);}return result;}/*** To bypass validation** @return* @throws NoSuchAlgorithmException* @throws KeyManagementException*/public static CloseableHttpClient createIgnoreVerifyHttpClient() throws GeneralSecurityException {SSLContext sslContext = SSLContext.getInstance("TLS");X509TrustManager trustManager = new X509TrustManager() {@Overridepublic void checkClientTrusted(X509Certificate[] paramArrayOfX509Certificate,String paramString) throws CertificateException {}@Overridepublic void checkServerTrusted(X509Certificate[] paramArrayOfX509Certificate,String paramString) throws CertificateException {}@Overridepublic X509Certificate[] getAcceptedIssuers() {return null;}};sslContext.init(null, new TrustManager[]{trustManager}, null);Registry<ConnectionSocketFactory> socketFactoryRegistry =RegistryBuilder.<ConnectionSocketFactory>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;}}
本文标签: util
版权声明:本文标题:util 内容由林淑君副主任自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.xiehuijuan.com/baike/1731043857a969586.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论