• 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请求短连接工具类

    世界上所有的不公平都是由于当事人能力不足造成的.
  • 相关阅读:
    小程序_递归求年纪
    小程序_递归求阶层
    把字符串复制到剪贴板
    主流的三种RF方案及其优缺点比较
    CC1100E的ESD指标?
    delphi怎样打开一个文本文件
    CC1100模块 250K的速率的问题
    delphi 中显示access数据库表怎么实现
    delphi与Access数据库连接的步骤
    数据库基本语句
  • 原文地址:https://www.cnblogs.com/javayida/p/13347099.html
Copyright © 2020-2023  润新知