zoukankan      html  css  js  c++  java
  • http连接池

    <!-- 开始:http连接池PoolingClientConnectionManager配置  -->
        <beans:bean id="connManager" class="org.apache.http.impl.conn.PoolingClientConnectionManager">
           <beans:property name="maxTotal" value="50"/>
           <beans:property name="defaultMaxPerRoute" value="35"/>
        </beans:bean>
    
        <beans:bean id="httpclient" class="org.apache.http.impl.client.DefaultHttpClient">
           <beans:constructor-arg>
              <beans:ref bean="connManager"/>
           </beans:constructor-arg>
        </beans:bean>
    
        <beans:bean id="httpClientUtil" class="com.api.pms.util.dilian.HttpClientUtil" init-method="initClient" destroy-method="destroyClient">
           <beans:property name="httpclient" ref="httpclient"/>
        </beans:bean> 
        <!-- 结束: http连接池PoolingClientConnectionManager配置 -->

    HttpClientUtil源码:

    package com.api.pms.util.dilian;
    
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Map;
    import java.util.Set;
    
    import org.apache.http.Header;
    import org.apache.http.HeaderElement;
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpRequest;
    import org.apache.http.HttpRequestInterceptor;
    import org.apache.http.HttpResponse;
    import org.apache.http.HttpResponseInterceptor;
    import org.apache.http.HttpStatus;
    import org.apache.http.NameValuePair;
    import org.apache.http.ParseException;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.entity.GzipDecompressingEntity;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.HttpDelete;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.client.methods.HttpPut;
    import org.apache.http.entity.ContentType;
    import org.apache.http.entity.StringEntity;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
    import org.apache.http.message.BasicNameValuePair;
    import org.apache.http.params.CoreConnectionPNames;
    import org.apache.http.protocol.HttpContext;
    import org.apache.http.util.EntityUtils;
    import org.apache.log4j.Logger;
    /*import org.apache.http.entity.mime.MultipartEntity;
    import org.apache.http.entity.mime.content.ByteArrayBody;
    import org.apache.http.entity.mime.content.ContentBody;*/
    
    /**
     * http请求工具类 get,post
     * 
     * 
     */
    public class HttpClientUtil {
        private static Logger logger = Logger.getLogger(HttpClientUtil.class.getName());
        //private  static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
        private  static final String HEADER_ACCEPT_ENCODING = "Accept-Encoding";
        private  static final String ENCODING_GZIP = "gzip";
        private DefaultHttpClient httpclient;
        public void setHttpclient(DefaultHttpClient httpclient) {
            this.httpclient = httpclient;
        }
    
        /**
         * 通过post提交方式获取url指定的资源和数据
         * 
         * @param url
         * @return
         * @throws DajieHttpRequestException
         */
        public  String postData(String url) throws Exception {
    
            return postData(url, null);
        }
    
        /**
         * 通过post提交方式获取url指定的资源和数据
         * 
         * @param url
         * @param nameValuePairs
         *            请求参数
         * @return
         * @throws DajieHttpRequestException
         */
        public  String postData(String url, Map<String, String> params)
                throws Exception {
            return postData(url, params, null);
        }
    
        /**
         * 通过post提交方式获取url指定的资源和数据
         * 
         * @param url
         * @param nameValuePairs
         *            请求参数
         * @param headers
         *            请求header参数
         * @return
         * @throws DajieHttpRequestException
         */
        public  String postData(String url,Map<String, String> params,
                 Map<String, String> headers)
                 {
            long start = System.currentTimeMillis();
            logger.info("postData url:"+url);
            String info="";
            HttpPost httpPost = new HttpPost(url);
            try {
                if (headers != null && headers.size() > 0) {
                    Set<Map.Entry<String, String>> set = headers.entrySet();
                    for (Iterator<Map.Entry<String, String>> it = set.iterator(); it
                            .hasNext();) {
                        Map.Entry<String, String> header = it.next();
                        if (header != null) {
                            httpPost.setHeader(header.getKey(), header.getValue());
                        }
                    }
                }
                List<NameValuePair> nameValuePairs=null;
                if(params!=null){
                    nameValuePairs = new ArrayList <NameValuePair>();  
    
                    Set<String> keySet = params.keySet();  
                    for(String key : keySet) {  
                        nameValuePairs.add(new BasicNameValuePair(key, params.get(key)));  
                    }  
                }
                if (nameValuePairs != null && nameValuePairs.size() > 0) {
                    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));
                }
                //请求超时
                httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,50000);
                //读取超时
                httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,50000); 
    
                HttpResponse response = httpclient.execute(httpPost);
    
                if(HttpStatus.SC_OK==response.getStatusLine().getStatusCode()){
                    HttpEntity entity = response.getEntity();
                    if(entity == null){
                         return null;
                    }
                    info = EntityUtils.toString(entity, "UTF-8");
                }else{
                    info="请求目标服务器链接失败,http状态码:"+response.getStatusLine().getStatusCode();
                }
                return info;
            }catch(ClientProtocolException e){
                info="协议错误";
                // LogUtil.getLogger().error("该异常通常是协议错误导致,比如构造HttpGet对象时传入的协议不对(将'http'写成'htp')或者服务器端返回的内容不符合HTTP协议要求等,堆栈信息如下", e);
            }catch(ParseException e){
                info=e.getMessage();
                //  LogUtil.getLogger().error(e.getMessage(), e);
            }catch(IOException e){
                info="网络异常";
                //  LogUtil.getLogger().error("该异常通常是网络原因引起的,如HTTP服务器未启动等,堆栈信息如下", e);
            }  finally {
                httpPost.releaseConnection();
                long interval = System.currentTimeMillis() - start;
                logger.debug("{} 请求耗时:{} "+url+interval);
            }
            return info;
        }
    
        /**
         * 通过ContentType 为json的格式进行http传输
         * @param url 远程url
         * @param content 传输内容
         * @return
         * @throws DajieHttpRequestException
         */
        public  String postJSONData(String url, String content) throws Exception {
            long start = System.currentTimeMillis();
            HttpPost httpPost = new HttpPost(url);
            try {
                if (content != null && content.length() > 0) {
                    httpPost.setEntity(new StringEntity(content,ContentType.APPLICATION_JSON));
                }
                HttpResponse response = httpclient.execute(httpPost);
                HttpEntity entity = response.getEntity();
                if(entity == null){
                     return null;
                }
                String info = EntityUtils.toString(entity, "UTF-8");
                return info;
            } catch (Exception e) {
                logger.debug("postData Exception url: {}"+url);
                throw new Exception(url
                        + "dajie postDataByJson exception:", e);
            } finally {
                httpPost.releaseConnection();
                long interval = System.currentTimeMillis() - start;
                logger.debug("{} 请求耗时:{} "+url+interval);
            }
        }
    
        /**
         * 通过get方法获取url资源的数据
         * 
         * @param url
         *            服务器地址
         * @return 返回响应的文本,如果请求发生异常,抛出DajieHttpRequestException
         * @throws DajieHttpRequestException
         */
        public  String getData(String url) throws Exception {
            return getData(url, null);
        }
        public static void main(String[] args) throws Exception {
            HttpClientUtil hcu=new HttpClientUtil();
    
            String r=hcu.getData("http://www.baidu.com");
            System.out.println(r);
        }
        /**
         * 带header的get请求
         * 
         * @param url
         *            服务器地址
         * @param headers
         *            添加的请求header信息
         * @return 返回服务器响应的文本,出错抛出DajieHttpRequestException异常
         * @throws DajieHttpRequestException
         */
        public  String getData(String url, Map<String, String> headers)
                {
            long start = System.currentTimeMillis();
            logger.info("getData url:"+url);
            System.out.println("url:"+url);
            HttpGet httpGet = new HttpGet(url);
            if (headers != null && headers.size() > 0) {
                Set<Map.Entry<String, String>> set = headers.entrySet();
                for (Iterator<Map.Entry<String, String>> it = set.iterator(); it
                        .hasNext();) {
                    Map.Entry<String, String> header = it.next();
                    if (header != null) {
                        httpGet.setHeader(header.getKey(), header.getValue());
                    }
                }
            }
            String info="";
            try {
                  httpclient.getParams().setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, true);
    
                //请求超时
                httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,50000);
                //读取超时
                httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,50000); 
                //在提交请求之前 测试连接是否可用
                //HttpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(0, false));
                HttpResponse response =  httpclient.execute(httpGet);
    
                if(HttpStatus.SC_OK==response.getStatusLine().getStatusCode()){
                    HttpEntity entity = response.getEntity();
                    if(entity == null){
                         return null;
                    }
                    info = EntityUtils.toString(entity, "UTF-8");
                }else{
                    info="请求目标服务器链接失败,http状态码:"+response.getStatusLine().getStatusCode();
                }
                return info;
            }catch(ClientProtocolException e){
                info="协议错误";
                // LogUtil.getLogger().error("该异常通常是协议错误导致,比如构造HttpGet对象时传入的协议不对(将'http'写成'htp')或者服务器端返回的内容不符合HTTP协议要求等,堆栈信息如下", e);
            }catch(ParseException e){
                info=e.getMessage();
                //  LogUtil.getLogger().error(e.getMessage(), e);
            }catch(IOException e){
                info="网络异常";
                //  LogUtil.getLogger().error("该异常通常是网络原因引起的,如HTTP服务器未启动等,堆栈信息如下", e);
            }finally {
                httpGet.releaseConnection();
                long interval = System.currentTimeMillis() - start;
                logger.debug("{} 请求耗时:{} "+url+interval);
            }
            return info;
        }
    
        /**
         * 对httpclient 做压缩处理和解压缩处理
         * 
         * @param httpclient
         */
        public void initClient() {
            ((DefaultHttpClient)httpclient).addRequestInterceptor(new HttpRequestInterceptor() {
                @Override
                public void process(HttpRequest request, HttpContext context) {
                    if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                        request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
                    }
                }
            });
    
            ((DefaultHttpClient)httpclient).addResponseInterceptor(new HttpResponseInterceptor() {
                @Override
                public void process(HttpResponse response, HttpContext context) {
                    final HttpEntity entity = response.getEntity();
                    if(entity == null){
                        return;
                    }
                    final Header encoding = entity.getContentEncoding();
                    if (encoding != null) {
                        for (HeaderElement element : encoding.getElements()) {
                            if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                                response.setEntity(new GzipDecompressingEntity(
                                        response.getEntity()));
                                break;
                            }
                        }
                    }
                }
            });
            //设置重试3次
            httpclient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(0, true));
            httpclient.getParams().setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, true);
    
        }
    
        /**
         * 关闭客户端
         */
        public void destroyClient(){
            httpclient.getConnectionManager().shutdown();
        }
        /**
         * post方式处理文件和图片上传
         * 
         * @param url
         *            服务器地址
         * @param data
         *            byte数组数据
         * @param fileName
         *            文件名
         * @return 返回服务器响应信息,否则抛出DajieHttpRequestException异常
         * @throws DajieHttpRequestException
         */
        /*public  String postMultipartData(String url, byte[] data,
                String fileName) throws Exception {
            long start = System.currentTimeMillis();
            HttpPost httpPost = new HttpPost(url);
            try {
                if (data != null && data.length > 0) {
                    MultipartEntity reqEntity = new MultipartEntity();
                    ContentBody contentBody = new ByteArrayBody(data, fileName);
                    reqEntity.addPart("file", contentBody);
                    httpPost.setEntity(reqEntity);
                }
                HttpResponse response = httpclient.execute(httpPost);
                HttpEntity entity = response.getEntity();
                String info = EntityUtils.toString(entity, "UTF-8");
                return info;
            } catch (Exception e) {
                logger.debug("postMultipartData Exception url: {}", url, e);
                throw new Exception(url
                        + "dajie postMultipartData exception:", e);
            } finally {
                httpPost.releaseConnection();
                long interval = System.currentTimeMillis() - start;
                logger.debug("{} 请求耗时:{} ", url, interval);
            }
        }
    */
        /**
         * put 方式提交数据
         * 
         * @param url
         *            :服务器地址
         * @param nameValuePairs
         *            :参数
         * @return 返回 服务器返回的文本信息,报错会抛出异常
         * @throws DajieHttpRequestException
         */
        public  String putData(String url, List<NameValuePair> nameValuePairs)
                throws Exception {
            long start = System.currentTimeMillis();
            HttpPut httpPut = new HttpPut(url);
    
            try {
                if (nameValuePairs != null && nameValuePairs.size() > 0) {
                    httpPut.setEntity(new UrlEncodedFormEntity(nameValuePairs,
                            "UTF-8"));
                }
                HttpResponse response = httpclient.execute(httpPut);
                HttpEntity entity = response.getEntity();
                if(entity == null){
                     return null;
                }
                String info = EntityUtils.toString(entity, "UTF-8");
                return info;
            } catch (Exception e) {
                logger.debug("putData Exception url {} "+url);
                throw new Exception(url
                        + "dajie putData exception:", e);
            } finally {
                httpPut.releaseConnection();
                long interval = System.currentTimeMillis() - start;
                logger.debug("{} 请求耗时:{} "+url+interval);
            }
        }
    
        /**
         * delete 方式提交数据
         * 
         * @param url
         *            服务器地址
         * @return 返回 服务器返回的文本信息,报错会抛出异常
         * @throws DajieHttpRequestException
         */
        public  String deleteData(String url)
                throws Exception {
            return deleteData(url, null);
        }
    
        /**
         * delete 方式提交数据
         * 
         * @param url
         *            服务器地址
         * @return 返回 服务器返回的文本信息,报错会抛出异常
         */
        public  String deleteData(String url, Map<String, String> headers)
                throws Exception {
            long start = System.currentTimeMillis();
            HttpDelete httpDelete = new HttpDelete(url);
    
            if (headers != null && headers.size() > 0) {
                Set<Map.Entry<String, String>> set = headers.entrySet();
                for (Iterator<Map.Entry<String, String>> it = set.iterator(); it
                        .hasNext();) {
                    Map.Entry<String, String> header = it.next();
                    if (header != null) {
                        httpDelete.setHeader(header.getKey(), header.getValue());
                    }
                }
            }
            try {
                HttpResponse response = httpclient.execute(httpDelete);
                HttpEntity entity = response.getEntity();
                String info = EntityUtils.toString(entity, "UTF-8");
                return info;
            } catch (Exception e) {
                logger.debug("putData Exception url {} "+url);
                throw new Exception(url
                        + "dajie deleteDate exception:", e);
            } finally {
                httpDelete.releaseConnection();
                long interval = System.currentTimeMillis() - start;
                logger.debug("{} 请求耗时:{} "+url+interval);
            }
        }
    
        /**
         * 下载媒体资源
         * @param url
         * @return
         * @throws DajieHttpRequestException
         */
        public byte[] getMultipartData(String url) throws Exception{
            long start = System.currentTimeMillis();
            HttpGet httpGet = new HttpGet(url);
            try {
                HttpResponse response =  httpclient.execute(httpGet);
                byte[] result = EntityUtils.toByteArray(response.getEntity());
                return result;
            }catch(Exception e){
                logger.debug("putData Exception url {} "+url);
                throw new Exception(url+ "dajie getMultipartData exception:", e);
            }finally{
                httpGet.releaseConnection();
                long interval = System.currentTimeMillis() - start;
                logger.debug("{} 请求耗时:{} "+url+interval);
            }
        }
    
    
    }
    
    
    
  • 相关阅读:
    函数式语言(老师作业)
    session/cookie
    Linux根目录下各个目录的功能介绍
    Navicat12安装文件和破解补丁
    正则表达式验证示例
    RequestDispatcher接口示例
    hello2部分源码解析
    Introduction of Servlet Filter
    关于hello1中的web.xml解析
    Annotation解释
  • 原文地址:https://www.cnblogs.com/hzcya1995/p/13310658.html
Copyright © 2011-2022 走看看