HttpClient封装

一、maven地址

		
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.5.2</version>
		</dependency>



二、代码

package com.wuage.wechat.service.center.utils;

import java.io.IOException;
import java.nio.charset.Charset;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
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.config.ConnectionConfig;
import org.apache.http.config.SocketConfig;
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.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 类HttpClientUtil.java的实现描述:TODO 类实现描述
 * 
 * @author wangpeng 2016年9月8日 下午2:23:07
 */
public class HttpClientUtil {

    private static Logger                                   logger                             = LoggerFactory.getLogger(HttpClientUtil.class);

    private static final PoolingHttpClientConnectionManager CONN_MGR;
    private static final CloseableHttpClient                HTTP_CLIENT;
    private static final SocketConfig                       DEFAULT_SOCKET_CONFIG;
    private static final ConnectionConfig                   DEFAULT_CONN_CONFIG;
    private static final RequestConfig                      DEFAULT_REQ_CONFIG;
    private static final int                                DEFAULT_BUFFER_SIZE                = 1024 * 1024;
    private static final Charset                            DEFAULT_CHARSET                    = Consts.UTF_8;
    private static final int                                DEFAULT_CONNECTION_REQUEST_TIMEOUT = 5 * 1000;
    private static final int                                DEFAULT_CONNECT_TIMEOUT            = 5 * 1000;
    private static final int                                DEFAULT_SOCKET_TIMEOUT             = 15 * 1000;
    private static final int                                DEFAULT_MAX_TOTAL                  = 512;
    private static final int                                DEFAULT_MAX_PER_ROUTE              = 2;

    static {
        DEFAULT_SOCKET_CONFIG = SocketConfig.DEFAULT;
        DEFAULT_CONN_CONFIG = ConnectionConfig.custom().setBufferSize(DEFAULT_BUFFER_SIZE).setCharset(DEFAULT_CHARSET).build();
        DEFAULT_REQ_CONFIG = RequestConfig.custom().setConnectionRequestTimeout(DEFAULT_CONNECTION_REQUEST_TIMEOUT).setConnectTimeout(DEFAULT_CONNECT_TIMEOUT).setSocketTimeout(DEFAULT_SOCKET_TIMEOUT).build();
        CONN_MGR = new PoolingHttpClientConnectionManager();
        CONN_MGR.setMaxTotal(DEFAULT_MAX_TOTAL);
        CONN_MGR.setDefaultMaxPerRoute(DEFAULT_MAX_PER_ROUTE);
        CONN_MGR.setDefaultConnectionConfig(DEFAULT_CONN_CONFIG);
        CONN_MGR.setDefaultSocketConfig(DEFAULT_SOCKET_CONFIG);
        HTTP_CLIENT = HttpClients.custom().setConnectionManager(CONN_MGR).setDefaultRequestConfig(DEFAULT_REQ_CONFIG).build();
    }

    private static final HttpEntity baseHttpGetService(String url) {
        HttpGet httpGet = new HttpGet(url);
        httpGet.addHeader("Accept", "text/html");
        httpGet.addHeader("Accept-Charset", "utf-8");
        httpGet.addHeader("Accept-Encoding", "gzip");
        httpGet.addHeader("Accept-Language", "en-US,en");
        httpGet.addHeader("User-Agent",
                          "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.160 Safari/537.22");
        logger.info("Executing request" + httpGet.getRequestLine());
        try {
            CloseableHttpResponse response = HTTP_CLIENT.execute(httpGet);
            logger.info(url, response.getStatusLine());
            return response.getEntity();
        } catch (ClientProtocolException e) {
            logger.info(url);
            logger.error(e.getMessage());
        } catch (IOException e) {
            logger.info(url);
            logger.error(e.getMessage());
        }
        return null;
    }

    public static String HttpGetService(String url) {
        HttpEntity entity = baseHttpGetService(url);
        try {
            return EntityUtils.toString(entity, "utf-8");
        } catch (ParseException e) {
            logger.error("parse utf-8 exception:{}", e);
        } catch (IOException e) {
            logger.info(url);
            logger.error(e.getMessage());
        }
        return "";
    }

    public static byte[] HttpGetByteService(String url) {
        HttpEntity entity = baseHttpGetService(url);
        try {
            return EntityUtils.toByteArray(entity);
        } catch (ParseException e) {
            logger.error("parse utf-8 exception:{}", e);
        } catch (IOException e) {
            logger.info(url);
            logger.error(e.getMessage());
        }
        return "".getBytes();
    }

    public static String HttpPostService(String url, HttpEntity httpentity) {
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(httpentity);
        // logger.info("Executing request" + httpPost.getRequestLine());
        try {
            CloseableHttpResponse response = HTTP_CLIENT.execute(httpPost);
            // logger.info(response.getStatusLine());
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // 正常返回
                String result = EntityUtils.toString(response.getEntity());
                return result;
            } else {
                logger.error(url, response.getEntity());
            }
            HttpEntity entity = response.getEntity();
            return EntityUtils.toString(entity);
        } catch (ClientProtocolException e) {
            logger.info(url);
            logger.error(e.getMessage());
        } catch (IOException e) {
            logger.info(url);
            logger.error(e.getMessage());
        }
        return "";
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值