httpclient工具类分享

本文介绍了一个基于HTTPClient的工具类实现,包括依赖的jar包、初始化连接池、获取SSLContext的方法、获取客户端连接对象及POST和GET请求的实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

因最近在做一个下载功能,所以学习了一下httpClient,现在给大家分享一下我写的httpClient工具类:

该工具类依赖以下jar包:

<!-- httpclient begin -->
<dependency>
    <groupId>commons-httpclient</groupId>
    <artifactId>commons-httpclient</artifactId>
    <version>${commons-httpclient.version}</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>${httpclient.version}</version>
</dependency>
<dependency>
    <groupId>org.javassist</groupId>
    <artifactId>javassist</artifactId>
    <version>${javassist.version}</version>
</dependency>
<!-- httpclient end -->
<!-- apache common util -->
<dependency>
   <groupId>org.apache.commons</groupId>
   <artifactId>commons-lang3</artifactId>
   <version>3.3.1</version>
</dependency>
<dependency>
   <groupId>commons-io</groupId>
   <artifactId>commons-io</artifactId>
   <version>2.4</version>
</dependency>
<!-- log -->
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>${log4j.version}</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>${slf4j-api.version}</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>${slf4j-log4j12.version}</version>
</dependency>

接下来就是上代码了:

public class HttpClientUtil {
    static Logger logger = LoggerFactory.getLogger (HttpClientUtil.class);
    /** 连接池 **/
    private static PoolingHttpClientConnectionManager connectionManager;
    /** 编码 **/
    private final static String CHARSET_UTF_8 = "UTF-8";
    /** 出错返回结果 **/
    private static final String RESULT = "-1";
    /** 连接池最大连接数 **/
    private static final int MAX_TOTAL = 2000;
    /** 每个路由最大连接数 **/
    private static final int DEFAULT_MAX_PER_ROUTE = 20;
    /** 超时时间 **/
    private static final int DEFAULT_TIME_OUT = 3000;
    /** 请求超时重试次数 **/
    private static final int RETRY_TIMES = 3;
    private static final String DEFAULT_SAVE_PATH = Constant.filePath;
    /**
     * 初始化连接池管理器
     * 配置SSL
     */
    static {
        if (connectionManager == null){
            try {
                //创建SSL安全访问连接
                //获取创建ssl上下文对象
                SSLContext sslContext = getSSLContext (true, null, null);
                //注册
                Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create ()
                        .register ("http", PlainConnectionSocketFactory.INSTANCE)
                        .register ("https", new SSLConnectionSocketFactory (sslContext))
                        .build ();
                //ssl注册到连接池
                connectionManager = new PoolingHttpClientConnectionManager (socketFactoryRegistry);
                connectionManager.setMaxTotal (MAX_TOTAL);
                connectionManager.setDefaultMaxPerRoute (DEFAULT_MAX_PER_ROUTE);
            } catch (IOException e) {
                e.printStackTrace ();
            } catch (CertificateException e) {
                e.printStackTrace ();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace ();
            } catch (UnrecoverableKeyException e) {
                e.printStackTrace ();
            } catch (KeyStoreException e) {
                e.printStackTrace ();
            } catch (KeyManagementException e) {
                e.printStackTrace ();
            }
        }
    }

    /**
     * 获取SSLContext
     * @param isDeceive
     * @param creFile
     * @param crePwd
     * @return
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     * @throws KeyStoreException
     * @throws IOException
     * @throws CertificateException
     * @throws UnrecoverableKeyException
     */
    private static SSLContext getSSLContext(boolean isDeceive, File creFile,String crePwd) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, IOException, CertificateException, UnrecoverableKeyException {
        SSLContext sslContext = null;
        if(isDeceive){
            sslContext = SSLContext.getInstance ("SSLv3");
            //实现一个X509TrusManager接口,用于绕过证书,不用修改里面的方法
            X509TrustManager x509TrustManager = new X509TrustManager (){
                @Override
                public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {}
                @Override
                public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {                }
                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            };
            sslContext.init (null, new TrustManager[]{x509TrustManager}, null);
        }else{
            if(null != creFile && creFile.length () > 0){
                if(null != crePwd){
                    KeyStore keyStore = KeyStore.getInstance (KeyStore.getDefaultType ());
                    keyStore.load (new FileInputStream (creFile),crePwd.toCharArray ());
                    sslContext = SSLContexts.custom().loadTrustMaterial(keyStore, new TrustSelfSignedStrategy ()).build();
                }else{
                    throw new SSLHandshakeException ("数字密码为空");
                }
            }
        }
        return sslContext;
    }

    /**
     * 获取客户端连接对象
     * @return
     */
    private static CloseableHttpClient getHttpClient(){
        return getHttpClient(DEFAULT_TIME_OUT);
    }

    /**
     * 获取客户端连接对象
     * @param timeOut
     * @return
     */
    private static CloseableHttpClient getHttpClient(Integer timeOut){
        //配置请求参数
        RequestConfig requestConfig = RequestConfig.custom ()
                .setConnectionRequestTimeout (timeOut)
                .setConnectTimeout (timeOut)
                .setSocketTimeout (timeOut)
                .build ();
        //配置超时回调机制
        HttpRequestRetryHandler httpRequestRetryHandler = new HttpRequestRetryHandler () {
            @Override
            public boolean retryRequest(IOException e, int i, HttpContext httpContext) {
                //如果已经重试三次则放弃请求
                if (i >= RETRY_TIMES){
                    return false;
                }
                // 如果服务器丢掉了连接,那么就重试
                if (e instanceof NoHttpResponseException){
                    return true;
                }
                // 不要重试SSL握手异常
                if (e instanceof SSLHandshakeException) {
                    return false;
                }
                // 超时
                if (e instanceof InterruptedIOException) {
                    return true;
                }
                // 目标服务器不可达
                if (e instanceof UnknownHostException) {
                    return false;
                }
                // 连接被拒绝
                if (e instanceof ConnectTimeoutException) {
                    return false;
                }
                // ssl握手异常
                if (e instanceof SSLException) {
                    return false;
                }
                HttpClientContext adapt = HttpClientContext.adapt (httpContext);
                HttpRequest request = adapt.getRequest ();
                //如果请求是幂等的,就再次尝试
                return !(request instanceof HttpEntityEnclosingRequest);
            }
        };
        CloseableHttpClient httpClient = HttpClients.custom ().setConnectionManager (connectionManager)
                .setDefaultRequestConfig (requestConfig)
                .setRetryHandler (httpRequestRetryHandler)
                .build ();
        return httpClient;
    }

    /**
     * http post请求
     * @param url
     * @param headers
     * @param params
     * @param timeOut
     * @param isStream
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String httpPost(String url,Map<String,String> headers, Map<String,Object> params,Integer timeOut,boolean isStream) throws UnsupportedEncodingException {
        //创建post请求
        HttpPost httpPost = new HttpPost (url);
        //添加请求头信息
        if(null != headers && !headers.isEmpty ()){
            for(Map.Entry<String, String> header : headers.entrySet ()){
                httpPost.addHeader (header.getKey (),header.getValue ());
            }
        }
        //添加参数
        if(null != params && !params.isEmpty ()){
            httpPost.setEntity (new UrlEncodedFormEntity (covertParams2NVPS(params)));
        }
        String result;
        if(null == timeOut){
            result = getResult(httpPost,DEFAULT_TIME_OUT,isStream);
        }else{
            result = getResult(httpPost,timeOut,isStream);
        }
        return  result;
    }

    /**
     * http post请求
     * @param url
     * @param headers
     * @param params
     * @param timeOut
     * @return
     */
    public static String httpPost(String url, Map<String,String> headers,Map<String,Object> params,Integer timeOut) throws UnsupportedEncodingException {
        //创建post请求
        HttpPost httpPost = new HttpPost (url);
        //添加请求头信息
        if(null != headers && !headers.isEmpty ()){
            for(Map.Entry<String, String> header : headers.entrySet ()){
                httpPost.addHeader (header.getKey (),header.getValue ());
            }
        }
        //添加参数
        if(null != params && !params.isEmpty ()){
            httpPost.setEntity (new UrlEncodedFormEntity (covertParams2NVPS(params)));
        }
        String result;
        if(null == timeOut){
            result = getResult(httpPost,DEFAULT_TIME_OUT,false);
        }else{
            result = getResult(httpPost,timeOut,false);
        }
        return  result;
    }

    /**
     * http get 请求
     * @param url
     * @param headers
     * @param params
     * @param timeOut
     * @param isStream
     * @return
     * @throws UnsupportedEncodingException
     * @throws URISyntaxException
     */
    public static String httpGet(String url,Map<String,String> headers, Map<String,Object> params,Integer timeOut,boolean isStream) throws UnsupportedEncodingException, URISyntaxException {
        URIBuilder uriBuilder = new URIBuilder (url);
        if(null != params && !params.isEmpty ()) {
            uriBuilder.addParameters (covertParams2NVPS (params));
        }

        //创建post请求
        HttpGet httpGet = new HttpGet (url);
        //添加请求头信息
        if(null != headers && !headers.isEmpty ()){
            for(Map.Entry<String, String> header : headers.entrySet ()){
                httpGet.addHeader (header.getKey (),header.getValue ());
            }
        }
        String result;
        if(null == timeOut){
            result = getResult(httpGet,DEFAULT_TIME_OUT,isStream);
        }else{
            result = getResult(httpGet,timeOut,isStream);
        }
        return  result;
    }

    /**
     * http get 请求
     * @param url
     * @param headers
     * @param params
     * @param timeOut
     * @return
     * @throws UnsupportedEncodingException
     * @throws URISyntaxException
     */
    public static String httpGet(String url,Map<String,String> headers, Map<String,Object> params,Integer timeOut) throws UnsupportedEncodingException, URISyntaxException {
        URIBuilder uriBuilder = new URIBuilder (url);
        if(null != params && !params.isEmpty ()) {
            uriBuilder.addParameters (covertParams2NVPS (params));
        }

        //创建get请求
        HttpGet httpGet = new HttpGet (url);
        //添加请求头信息
        if(null != headers && !headers.isEmpty ()){
            for(Map.Entry<String, String> header : headers.entrySet ()){
                httpGet.addHeader (header.getKey (),header.getValue ());
            }
        }
        String result;
        if(null == timeOut){
            result = getResult(httpGet,DEFAULT_TIME_OUT,false);
        }else{
            result = getResult(httpGet,timeOut,false);
        }
        return  result;
    }

    /**
     * http get 请求
     * @param url
     * @param headers
     * @return
     * @throws UnsupportedEncodingException
     * @throws URISyntaxException
     */
    public static String httpGet(String url,Map<String,String> headers) {
        //创建post请求
        HttpGet httpGet = new HttpGet (url);
        //添加请求头信息
        if(null != headers && !headers.isEmpty ()){
            for(Map.Entry<String, String> header : headers.entrySet ()){
                httpGet.addHeader (header.getKey (),header.getValue ());
            }
        }
        return  getResult(httpGet,false);
    }

    /**
     * http get请求
     * @param url
     * @return
     * @throws UnsupportedEncodingException
     * @throws URISyntaxException
     */
    public static String httpGet(String url) throws UnsupportedEncodingException, URISyntaxException {
        //创建post请求
        HttpGet httpGet = new HttpGet (url);
        return  getResult(httpGet,false);
    }

    /**
     * http get 请求下载文件
     * @param url
     * @param headers
     * @param params
     * @param timeOut
     * @throws URISyntaxException
     */
    public static void httpGetDownload(String url, Map<String,String> headers, Map<String,Object> params,int timeOut) throws URISyntaxException {
        URIBuilder uriBuilder = new URIBuilder (url);
        if(null != params && !params.isEmpty ()) {
            uriBuilder.addParameters (covertParams2NVPS (params));
        }
        //创建post请求
        HttpGet httpGet = new HttpGet (url);
        //添加请求头信息
        if(null != headers && !headers.isEmpty ()){
            for(Map.Entry<String, String> header : headers.entrySet ()){
                httpGet.addHeader (header.getKey (),header.getValue ());
            }
        }
        downLoadFile (httpGet,timeOut);
    }

    /**
     * http get 请求
     * @param url
     * @param headers
     * @return
     * @throws UnsupportedEncodingException
     * @throws URISyntaxException
     */
    public static void httpGetDownload(String url,Map<String,String> headers) {
        //创建get请求
        HttpGet httpGet = new HttpGet (url);
        //添加请求头信息
        if(null != headers && !headers.isEmpty ()){
            for(Map.Entry<String, String> header : headers.entrySet ()){
                httpGet.addHeader (header.getKey (),header.getValue ());
            }
        }
        downLoadFile(httpGet,DEFAULT_TIME_OUT);
    }

    /**
     * http get 请求
     * @param url
     * @return
     * @throws UnsupportedEncodingException
     * @throws URISyntaxException
     */
    public static void httpGetDownload(String url) {
        //创建get请求
        HttpGet httpGet = new HttpGet (url);
        downLoadFile(httpGet,DEFAULT_TIME_OUT);
    }

    /**
     * 获取请求结果
     * @param httpRequest
     * @param isStream
     * @return
     */
    private static String getResult(HttpRequestBase httpRequest,boolean isStream){
        return getResult (httpRequest,DEFAULT_TIME_OUT,isStream);
    }

    /**
     * 获取请求结果,返回内容为字符串
     * @param httpRequest
     * @param timeOut
     * @param isStream
     * @return
     */
    private static String getResult(HttpRequestBase httpRequest,Integer timeOut,boolean isStream){
        //响应结果
        StringBuilder responseStr = null;
        CloseableHttpResponse response = null;
        //获取连接客户端
        CloseableHttpClient httpClient = getHttpClient (timeOut);
        try {
            //发起请求
            response = httpClient.execute (httpRequest);
            int statusCode = response.getStatusLine ().getStatusCode ();
            //判断是否为重定向
            if(HttpStatus.SC_MOVED_TEMPORARILY == statusCode){
                String locationUrl = response.getLastHeader ("Location").getValue ();
                return getResult (new HttpPost (locationUrl),timeOut,isStream);
            }
            //判断是否成功响应
            if(HttpStatus.SC_OK == statusCode){
                //获得响应实体
                HttpEntity entity = response.getEntity ();
                responseStr = new StringBuilder ();
                //判断是否以流的形式获取
                if(isStream){
                    BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent(), CHARSET_UTF_8));
                    String len = "";
                    while ((len = br.readLine()) != null) {
                        responseStr.append(len);
                    }
                }else{
                    responseStr.append(EntityUtils.toString(entity, CHARSET_UTF_8));
                    if (responseStr.length() < 1) {
                        responseStr.append("-1");
                    }
                }
            }
        }catch (SocketTimeoutException e) {
            logger.error ("响应超时:{}",e);
            e.printStackTrace();
        } catch (ConnectTimeoutException e) {
            logger.error ("请求超时:{}",e);
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            logger.error ("http协议错误:{}",e);
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            logger.error ("不支持的字符编码:{}",e);
            e.printStackTrace();
        } catch (UnsupportedOperationException e) {
            logger.error ("不支持的请求操作:{}",e);
            e.printStackTrace();
        } catch (ParseException e) {
            logger.error ("解析错误:{}",e);
            e.printStackTrace();
        } catch (IOException e) {
            logger.error ("IO错误:{}",e);
            e.printStackTrace();
        }finally {
            IOUtils.closeQuietly (response);
        }
        return StringUtils.isBlank (responseStr) ? RESULT : responseStr.toString();
    }

    /**
     *
     * @param httpRequest
     * @param timeOut
     */
    private static void downLoadFile(HttpRequestBase httpRequest,Integer timeOut){
        //响应结果
        CloseableHttpResponse response = null;
        //获取连接客户端
        CloseableHttpClient httpClient = getHttpClient (timeOut);
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            //发起请求
            response = httpClient.execute (httpRequest);
            int statusCode = response.getStatusLine ().getStatusCode ();
            //判断是否为重定向
            if(HttpStatus.SC_MOVED_TEMPORARILY == statusCode){
                String locationUrl = response.getLastHeader ("Location").getValue ();
                downLoadFile (new HttpPost (locationUrl),timeOut);
            }
            String urlPath = httpRequest.getURI ().getRawPath ();
            String fileName = urlPath.substring (urlPath.lastIndexOf ("/") + 1);
            logger.info ("正在下载的文件为:"+fileName);
            //判断是否成功响应
            if(HttpStatus.SC_OK == statusCode){
                //创建一个图片
                File file = new File (DEFAULT_SAVE_PATH + fileName);
                if(!file.exists()){
                    file.createNewFile();
                }
                outputStream = new FileOutputStream (file);
                //获得响应实体
                HttpEntity entity = response.getEntity ();
                inputStream = entity.getContent ();
                IOUtils.copy (inputStream,outputStream);
                outputStream.flush ();
            }
        }catch (SocketTimeoutException e) {
            logger.error ("响应超时:{}",e);
            e.printStackTrace();
        } catch (ConnectTimeoutException e) {
            logger.error ("请求超时:{}",e);
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            logger.error ("http协议错误:{}",e);
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            logger.error ("不支持的字符编码:{}",e);
            e.printStackTrace();
        } catch (UnsupportedOperationException e) {
            logger.error ("不支持的请求操作:{}",e);
            e.printStackTrace();
        } catch (ParseException e) {
            logger.error ("解析错误:{}",e);
            e.printStackTrace();
        } catch (IOException e) {
            logger.error ("IO错误:{}",e);
            e.printStackTrace();
        }finally {
            IOUtils.closeQuietly (outputStream);
            IOUtils.closeQuietly (inputStream);
            IOUtils.closeQuietly (response);
        }
    }

    /**
     * Map转换成NameValuePair List集合
     *
     * @param params map
     * @return NameValuePair List集合
     */
    public static List<NameValuePair> covertParams2NVPS(Map<String, Object> params) {
        List<NameValuePair> paramList = new LinkedList<> ();
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            paramList.add(new BasicNameValuePair (entry.getKey(), entry.getValue().toString()));
        }
        return paramList;
    }
}

不当之处请大家指出,互相学习!谢谢

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值