util-HttpClientUtil

HttpClientUtil 可根据需求修改

import hk.org.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.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.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() {
            @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<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;
    }

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值