http请求长连接工具类

http请求长连接

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.conn.ConnectionKeepAliveStrategy;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HttpContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PoolingHttpClients {

    private final static Logger log = LoggerFactory.getLogger(PoolingHttpClients.class);

    private final static PoolingClientConnectionManager cm;

    private final static DefaultHttpClient httpClient;

    private final static ResponseHandler<HttpInvokeResult> responseHandler = new DefaultResponseHandler();

    static {
        cm = new PoolingClientConnectionManager();
        cm.setMaxTotal(HttpClientConfig.HTTP_MAX_TOTAL_CONN);
        cm.setDefaultMaxPerRoute(HttpClientConfig.HTTP_MAX_CONN_PER_ROUTE);
        httpClient = new DefaultHttpClient(cm);
        // 增加 keep alive 策略
        httpClient.setKeepAliveStrategy(new ConnectionKeepAliveStrategy() {
            @Override
            public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
                return HttpClientConfig.HTTP_KEEPIDLE_DURATION;
            }
        });

        final HttpParams httpParams = httpClient.getParams();
        HttpProtocolParams.setContentCharset(httpParams, HttpClientConfig.HTTP_CHARSET);
        HttpProtocolParams.setHttpElementCharset(httpParams, HttpClientConfig.HTTP_CHARSET);
        HttpConnectionParams.setSoTimeout(httpParams, HttpClientConfig.HTTP_SO_TIMEOUT);
        HttpConnectionParams.setConnectionTimeout(httpParams, HttpClientConfig.HTTP_CONN_TIMEOUT);
        HttpConnectionParams.setSoKeepalive(httpParams, HttpClientConfig.HTTP_KEEPALIVE);
        HttpConnectionParams.setStaleCheckingEnabled(httpParams, HttpClientConfig.HTTP_STALE_CHECK);
        HttpConnectionParams.setTcpNoDelay(httpParams, true);
    }

    public static HttpInvokeResult get(final String url) {
        return get(url, 0);
    }

    public static HttpInvokeResult get(final String url, final long timeout) {
        return get(url, timeout, null);
    }

    public static HttpInvokeResult get(final String url, final long timeout, final List<Header> headers) {
        final HttpGet httpGet = new HttpGet(url);
        addHeaders(headers, httpGet);
        return invoke(httpGet, timeout);
    }

    private static void addHeaders(final List<Header> headers, final HttpRequestBase request) {
        if (headers != null) {
            for (final Header header : headers) {
                if (header == null) {
                    continue;
                }
                request.addHeader(header);
            }
        }
    }

    public static HttpInvokeResult post(final String url, final Map<String, String> params) {
        return post(url, params, 0);
    }

    public static HttpInvokeResult post(final String url, final Map<String, String> params, final long timeout) {
        final HttpPost httpPost = new HttpPost(url);
        final List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        if (params != null) {
            for (final Map.Entry<String, String> entry : params.entrySet()) {
                nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
        }

        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
        } catch (final UnsupportedEncodingException e) {
            log.error("UnsupportedEncodingException", e);
        }

        return invoke(httpPost, timeout);
    }

    public static HttpInvokeResult postString(final String url, final Map<String, String> params) {
        final HttpPost httpPost = new HttpPost(url);
        StringBuilder builder = new StringBuilder();
        if (params != null) {
            int i = 0;
            for (final Map.Entry<String, String> entry : params.entrySet()) {
                builder.append(i == 0 ? "" : "&");
                builder.append(entry.getKey()).append("=").append(entry.getValue());
                i++;
            }
        }
        httpPost.setEntity(new StringEntity(builder.toString(), ContentType.TEXT_PLAIN));

        return invoke(httpPost, 0);
    }

    public static HttpInvokeResult postraw(final String url, final Map<String, String> params, String content,
                                           final long timeout) {
        final HttpPost httpPost = new HttpPost(url);
        final List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        if (params != null) {
            for (final Map.Entry<String, String> entry : params.entrySet()) {
                nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
        }

        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nvps));
            httpPost.setEntity(new StringEntity(content, ContentType.APPLICATION_JSON));
        } catch (final UnsupportedEncodingException e) {
            log.error("UnsupportedEncodingException", e);
        }

        return invoke(httpPost, timeout);
    }

    public static HttpInvokeResult post(String url, byte[] body) {
        return post(url, body, 0);
    }

    public static HttpInvokeResult post(String url, byte[] body, long timeout) {
        return post(url, body, 0, body.length, timeout);
    }


    public static HttpInvokeResult post(String url, byte[] body, int off, int len) {

        return post(url, body, off, len, 0);
    }

    public static HttpInvokeResult post(String url, byte[] body, int off, int len, long timeout) {
        final HttpPost httpPost = new HttpPost(url);

        httpPost.setEntity(new ByteArrayEntity(body, off, len, ContentType.APPLICATION_JSON));

        return invoke(httpPost, timeout);
    }

    /***
     * 新增posturl type方式
     *
     * @param url
     * @param body
     * @param timeout
     * @return
     */
    public static HttpInvokeResult postForm(String url, byte[] body, long timeout) {
        return postForm(url, body, 0, body.length, timeout);
    }

    public static HttpInvokeResult postForm(String url, byte[] body, int off, int len, long timeout) {
        final HttpPost httpPost = new HttpPost(url);

        httpPost.setEntity(new ByteArrayEntity(body, off, len, ContentType.APPLICATION_FORM_URLENCODED));

        return invoke(httpPost, timeout);
    }

    static HttpInvokeResult invoke(final HttpRequestBase request, final long timeout) {
        final String url = request.getURI().toString();
//        log.info("invoke url:" + url);

        HttpInvokeResult result;

        if (timeout > 0) {
            request.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, (int) timeout);
            HttpConnectionParams.setConnectionTimeout(request.getParams(), (int) timeout);
        }

        try {
            result = httpClient.execute(request, responseHandler);
            if (result.getException() != null) {
                request.abort();
                log.error("请求失败,statusCode=" + result.getStatusCode() + ",url=" + url + ","
                        + result.getException().getMessage());
            }
            result.setUrl(request.getURI().toString());
            request.releaseConnection();
            return result;
        } catch (final Throwable e) {
            request.abort();
            log.error("请求失败,url=" + url + "," + e.getMessage());
            result = new HttpInvokeResult();
            result.setUrl(url);
            result.setException(e);
            result.setReason(e.getMessage());
            return result;
        } finally {
            request.reset();
        }
    }

}

短连接参考文章:http请求短连接工具类

posted @ 2018-11-03 22:49  你就像甜甜的益达  阅读(202)  评论(0编辑  收藏  举报