美文网首页
httpclient

httpclient

作者: wangpeng123 | 来源:发表于2018-05-31 16:23 被阅读0次
package com.wuage.wxapp.center.common.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();
    }

    /**
     * 基础get请求,包含头部信息等
     *
     * @param url
     * @return
     */
    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 (IOException e) {
            logger.info(url);
            logger.error(e.getMessage());
        }
        return null;
    }

    /**
     * 基础post请求
     *
     * @param url
     * @param httpEntity
     * @return
     */
    private static final HttpEntity baseHttpPostService(String url, HttpEntity httpEntity) {
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(httpEntity);
        try {
            CloseableHttpResponse response = HTTP_CLIENT.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // 正常返回
                return response.getEntity();
            } else {
                logger.error(url, response.getEntity());
            }
        } catch (ClientProtocolException e) {
            logger.info(url);
            logger.error(e.getMessage());
        } catch (IOException e) {
            logger.info(url);
            logger.error(e.getMessage());
        }
        return null;
    }

    /**
     * get请求
     *
     * @param url
     * @return
     */
    public static String httpGetService(String url) {
        HttpEntity entity = baseHttpGetService(url);
        try {
            return EntityUtils.toString(entity);
        } catch (IOException e) {
            logger.info(url);
            logger.error(e.getMessage());
        }
        return "";
    }

    /**
     * 返回流的get请求
     *
     * @param url
     * @return
     */
    public static byte[] httpGetByteService(String url) {
        HttpEntity entity = baseHttpGetService(url);
        try {
            return EntityUtils.toByteArray(entity);
        } catch (IOException e) {
            logger.info(url);
            logger.error(e.getMessage());
        }
        return "".getBytes();
    }

    /**
     * 返回流的post请求
     *
     * @param url
     * @param httpEntity
     * @return
     */
    public static byte[] httpPostByteService(String url, HttpEntity httpEntity) {
        HttpEntity entity = baseHttpPostService(url, httpEntity);
        try {
            return EntityUtils.toByteArray(entity);
        } catch (IOException e) {
            logger.info(url);
            logger.error(e.getMessage());
        }
        return "".getBytes();
    }

    /**
     * 普通post请求
     *
     * @param url
     * @param httpEntity
     * @return
     */
    public static String httpPostService(String url, HttpEntity httpEntity) {
        HttpEntity entity = baseHttpPostService(url, httpEntity);
        try {
            return EntityUtils.toString(entity);
        } catch (ParseException e) {
            logger.error("parse utf-8 exception:{}", e);
        } catch (IOException e) {
            logger.info(url);
            logger.error(e.getMessage());
        }
        return "";
    }
}

相关文章

网友评论

      本文标题:httpclient

      本文链接:https://www.haomeiwen.com/subject/pynqsftx.html