轻松把玩HttpClient之封装HttpClient工具类(六),封装输入参数,简化工具类

       在写这个工具类的时候发现传入的参数太多,以至于方法泛滥,只一个send方法就有30多个,所以对工具类进行了优化,把输入参数封装在一个对象里,这样以后再扩展输入参数,直接修改这个类就ok了。


       不多说了,先上代码:

[java]  view plain  copy
 print ?
  1. /**  
  2.  * 请求配置类 
  3.  *  
  4.  * @author arron 
  5.  * @date 2016年2月2日 下午3:14:32  
  6.  * @version 1.0  
  7.  */  
  8. public class HttpConfig {  
  9.       
  10.     private HttpConfig(){};  
  11.       
  12.     /** 
  13.      * 获取实例 
  14.      * @return 
  15.      */  
  16.     public static HttpConfig custom(){  
  17.         return new HttpConfig();  
  18.     }  
  19.   
  20.     /** 
  21.      * HttpClient对象 
  22.      */  
  23.     private HttpClient client;  
  24.   
  25.     /** 
  26.      * CloseableHttpAsyncClient对象 
  27.      */  
  28.     private CloseableHttpAsyncClient asynclient;  
  29.       
  30.     /** 
  31.      * 资源url 
  32.      */  
  33.     private String url;  
  34.   
  35.     /** 
  36.      * Header头信息 
  37.      */  
  38.     private Header[] headers;  
  39.   
  40.     /** 
  41.      * 请求方法 
  42.      */  
  43.     private HttpMethods method=HttpMethods.GET;  
  44.       
  45.     /** 
  46.      * 请求方法名称 
  47.      */  
  48.     private String methodName;  
  49.   
  50.     /** 
  51.      * 用于cookie操作 
  52.      */  
  53.     private HttpContext context;  
  54.   
  55.     /** 
  56.      * 传递参数 
  57.      */  
  58.     private Map<String, Object> map;  
  59.   
  60.     /** 
  61.      * 输入输出编码 
  62.      */  
  63.     private String encoding=Charset.defaultCharset().displayName();  
  64.   
  65.     /** 
  66.      * 输入编码 
  67.      */  
  68.     private String inenc;  
  69.   
  70.     /** 
  71.      * 输出编码 
  72.      */  
  73.     private String outenc;  
  74.       
  75.     /** 
  76.      * 输出流对象 
  77.      */  
  78.     private OutputStream out;  
  79.       
  80.     /** 
  81.      * 异步操作回调执行器 
  82.      */  
  83.     private IHandler handler;  
  84.   
  85.     /** 
  86.      * HttpClient对象 
  87.      */  
  88.     public HttpConfig client(HttpClient client) {  
  89.         this.client = client;  
  90.         return this;  
  91.     }  
  92.       
  93.     /** 
  94.      * CloseableHttpAsyncClient对象 
  95.      */  
  96.     public HttpConfig asynclient(CloseableHttpAsyncClient asynclient) {  
  97.         this.asynclient = asynclient;  
  98.         return this;  
  99.     }  
  100.       
  101.     /** 
  102.      * 资源url 
  103.      */  
  104.     public HttpConfig url(String url) {  
  105.         this.url = url;  
  106.         return this;  
  107.     }  
  108.       
  109.     /** 
  110.      * Header头信息 
  111.      */  
  112.     public HttpConfig headers(Header[] headers) {  
  113.         this.headers = headers;  
  114.         return this;  
  115.     }  
  116.       
  117.     /** 
  118.      * 请求方法 
  119.      */  
  120.     public HttpConfig method(HttpMethods method) {  
  121.         this.method = method;  
  122.         return this;  
  123.     }  
  124.       
  125.     /** 
  126.      * 请求方法 
  127.      */  
  128.     public HttpConfig methodName(String methodName) {  
  129.         this.methodName = methodName;  
  130.         return this;  
  131.     }  
  132.       
  133.     /** 
  134.      * cookie操作相关 
  135.      */  
  136.     public HttpConfig context(HttpContext context) {  
  137.         this.context = context;  
  138.         return this;  
  139.     }  
  140.       
  141.     /** 
  142.      * 传递参数 
  143.      */  
  144.     public HttpConfig map(Map<String, Object> map) {  
  145.         this.map = map;  
  146.         return this;  
  147.     }  
  148.       
  149.     /** 
  150.      * 输入输出编码 
  151.      */  
  152.     public HttpConfig encoding(String encoding) {  
  153.         //设置输入输出  
  154.         inenc(encoding);  
  155.         outenc(encoding);  
  156.         this.encoding = encoding;  
  157.         return this;  
  158.     }  
  159.       
  160.     /** 
  161.      * 输入编码 
  162.      */  
  163.     public HttpConfig inenc(String inenc) {  
  164.         this.inenc = inenc;  
  165.         return this;  
  166.     }  
  167.       
  168.     /** 
  169.      * 输出编码 
  170.      */  
  171.     public HttpConfig outenc(String outenc) {  
  172.         this.outenc = outenc;  
  173.         return this;  
  174.     }  
  175.       
  176.     /** 
  177.      * 输出流对象 
  178.      */  
  179.     public HttpConfig out(OutputStream out) {  
  180.         this.out = out;  
  181.         return this;  
  182.     }  
  183.       
  184.     /** 
  185.      * 异步操作回调执行器 
  186.      */  
  187.     public HttpConfig handler(IHandler handler) {  
  188.         this.handler = handler;  
  189.         return this;  
  190.     }  
  191.   
  192.   
  193.     public HttpClient client() {  
  194.         return client;  
  195.     }  
  196.       
  197.     public CloseableHttpAsyncClient asynclient() {  
  198.         return asynclient;  
  199.     }  
  200.       
  201.     public Header[] headers() {  
  202.         return headers;  
  203.     }  
  204.       
  205.     public String url() {  
  206.         return url;  
  207.     }  
  208.   
  209.     public HttpMethods method() {  
  210.         return method;  
  211.     }  
  212.   
  213.     public String methodName() {  
  214.         return methodName;  
  215.     }  
  216.   
  217.     public HttpContext context() {  
  218.         return context;  
  219.     }  
  220.   
  221.     public Map<String, Object> map() {  
  222.         return map;  
  223.     }  
  224.   
  225.     public String encoding() {  
  226.         return encoding;  
  227.     }  
  228.   
  229.     public String inenc() {  
  230.         return inenc == null ? encoding : inenc;  
  231.     }  
  232.   
  233.     public String outenc() {  
  234.         return outenc == null ? encoding : outenc;  
  235.     }  
  236.       
  237.     public OutputStream out() {  
  238.         return out;  
  239.     }  
  240.       
  241.     public IHandler handler() {  
  242.         return handler;  
  243.     }  
  244. }  
       将构造方法设置为private,然后提供一个custom()方法来获取新的实例,所有的set方法,都是返回HttpConfig,这样就支持链式调用(创建者模式)了。

       工具类的核心方法如下:

[java]  view plain  copy
 print ?
  1. /** 
  2.  * 请求资源或服务 
  3.  *  
  4.  * @param config 
  5.  * @return 
  6.  * @throws HttpProcessException 
  7.  */  
  8. public static String send(HttpConfig config) throws HttpProcessException {  
  9.     return fmt2String(execute(config), config.outenc());  
  10. }  
  11.   
  12. /** 
  13.  * 请求资源或服务 
  14.  *  
  15.  * @param client                client对象 
  16.  * @param url                   资源地址 
  17.  * @param httpMethod    请求方法 
  18.  * @param parasMap      请求参数 
  19.  * @param headers           请求头信息 
  20.  * @param encoding      编码 
  21.  * @return                      返回处理结果 
  22.  * @throws HttpProcessException  
  23.  */  
  24. private static HttpResponse execute(HttpConfig config) throws HttpProcessException {  
  25.     if(config.client()==null){//检测是否设置了client  
  26.         config.client(create(config.url()));  
  27.     }  
  28.     HttpResponse resp = null;  
  29.     try {  
  30.         //创建请求对象  
  31.         HttpRequestBase request = getRequest(config.url(), config.method());  
  32.           
  33.         //设置header信息  
  34.         request.setHeaders(config.headers());  
  35.           
  36.         //判断是否支持设置entity(仅HttpPost、HttpPut、HttpPatch支持)  
  37.         if(HttpEntityEnclosingRequestBase.class.isAssignableFrom(request.getClass())){  
  38.             List<NameValuePair> nvps = new ArrayList<NameValuePair>();  
  39.               
  40.             //检测url中是否存在参数  
  41.             config.url(Utils.checkHasParas(config.url(), nvps, config.inenc()));  
  42.               
  43.             //装填参数  
  44.             HttpEntity entity = Utils.map2List(nvps, config.map(), config.inenc());  
  45.               
  46.             //设置参数到请求对象中  
  47.             ((HttpEntityEnclosingRequestBase)request).setEntity(entity);  
  48.               
  49.             logger.info("请求地址:"+config.url());  
  50.             if(nvps.size()>0){  
  51.                 logger.info("请求参数:"+nvps.toString());  
  52.             }  
  53.         }else{  
  54.             int idx = config.url().indexOf("?");  
  55.             logger.info("请求地址:"+config.url().substring(0, (idx>0 ? idx : config.url().length())));  
  56.             if(idx>0){  
  57.                 logger.info("请求参数:"+config.url().substring(idx+1));  
  58.             }  
  59.         }  
  60.         //执行请求操作,并拿到结果(同步阻塞)  
  61.         resp = (config.context()==null)?config.client().execute(request) : config.client().execute(request, config.context()) ;  
  62.           
  63.         //获取结果实体  
  64.         return resp;  
  65.           
  66.     } catch (IOException e) {  
  67.         throw new HttpProcessException(e);  
  68.     }  
  69. }  
  70.   
  71. //-----------华----丽----分----割----线--------------  
  72. //-----------华----丽----分----割----线--------------  
  73. //-----------华----丽----分----割----线--------------  
  74.   
  75. /** 
  76.  * 转化为字符串 
  77.  *  
  78.  * @param entity            实体 
  79.  * @param encoding  编码 
  80.  * @return 
  81.  * @throws HttpProcessException  
  82.  */  
  83. public static String fmt2String(HttpResponse resp, String encoding) throws HttpProcessException {  
  84.     String body = "";  
  85.     try {  
  86.         if (resp.getEntity() != null) {  
  87.             // 按指定编码转换结果实体为String类型  
  88.             body = EntityUtils.toString(resp.getEntity(), encoding);  
  89.             logger.debug(body);  
  90.         }  
  91.         EntityUtils.consume(resp.getEntity());  
  92.     } catch (ParseException | IOException e) {  
  93.         throw new HttpProcessException(e);  
  94.     }finally{  
  95.         close(resp);  
  96.     }  
  97.     return body;  
  98. }  
  99.   
  100. /** 
  101.  * 转化为流 
  102.  *  
  103.  * @param entity            实体 
  104.  * @param out               输出流 
  105.  * @return 
  106.  * @throws HttpProcessException  
  107.  */  
  108. public static OutputStream fmt2Stream(HttpResponse resp, OutputStream out) throws HttpProcessException {  
  109.     try {  
  110.         resp.getEntity().writeTo(out);  
  111.         EntityUtils.consume(resp.getEntity());  
  112.     } catch (ParseException | IOException e) {  
  113.         throw new HttpProcessException(e);  
  114.     }finally{  
  115.         close(resp);  
  116.     }  
  117.     return out;  
  118. }  

       再附上测试代码:

[java]  view plain  copy
 print ?
  1.     public static void testOne() throws HttpProcessException{  
  2.           
  3.         System.out.println("--------简单方式调用(默认post)--------");  
  4.         String url = "http://tool.oschina.net/";  
  5.         HttpConfig  config = HttpConfig.custom();  
  6.         //简单调用  
  7.         String resp = HttpClientUtil.get(config.url(url));  
  8.   
  9.         System.out.println("请求结果内容长度:"+ resp.length());  
  10.           
  11.         System.out.println("\n#################################\n");  
  12.           
  13.         System.out.println("--------加入header设置--------");  
  14.         url="http://blog.csdn.net/xiaoxian8023";  
  15.         //设置header信息  
  16.         Header[] headers=HttpHeader.custom().userAgent("Mozilla/5.0").build();  
  17.         //执行请求  
  18.         resp = HttpClientUtil.get(config.headers(headers));  
  19.         System.out.println("请求结果内容长度:"+ resp.length());  
  20.   
  21.         System.out.println("\n#################################\n");  
  22.           
  23.         System.out.println("--------代理设置(绕过证书验证)-------");  
  24.         url="https://www.facebook.com/";  
  25.         HttpClient client= HCB.custom().timeout(10000).proxy("127.0.0.1"8087).ssl().build();//采用默认方式(绕过证书验证)  
  26.         //执行请求  
  27.         resp = HttpClientUtil.get(config.client(client));  
  28.         System.out.println("请求结果内容长度:"+ resp.length());  
  29.   
  30.         System.out.println("\n#################################\n");  
  31.   
  32. //      System.out.println("--------代理设置(自签名证书验证)+header+get方式-------");  
  33. //      url = "https://sso.tgb.com:8443/cas/login";  
  34. //      client= HCB.custom().timeout(10000).ssl("D:\\keys\\wsriakey","tomcat").build();  
  35. //      headers=HttpHeader.custom().keepAlive("false").connection("close").contentType(Headers.APP_FORM_URLENCODED).build();  
  36. //      //执行请求  
  37. //      resp = CopyOfHttpClientUtil.get(config.method(HttpMethods.GET));  
  38. //      System.out.println("请求结果内容长度:"+ resp.length());  
  39.         try {  
  40.             System.out.println("--------下载测试-------");  
  41.             url="http://ss.bdimg.com/static/superman/img/logo/logo_white_fe6da1ec.png";  
  42.             FileOutputStream out = new FileOutputStream(new File("d://aaa//000.png"));  
  43.             HttpClientUtil.down(HttpConfig.custom().url(url).out(out));  
  44.             out.flush();  
  45.             out.close();  
  46.             System.out.println("--------下载测试+代理-------");  
  47.               
  48.             out = new FileOutputStream(new File("d://aaa//001.png"));  
  49.             HttpClientUtil.down(HttpConfig.custom().client(client).url(url).out(out));  
  50.             out.flush();  
  51.             out.close();  
  52.         } catch (IOException e) {  
  53.             e.printStackTrace();  
  54.         }  
  55.   
  56.         System.out.println("\n#################################\n");  
  57.     }  

       可以看到这样调用会更显得清晰明了。以后再添加功能时,改起来也会比较方便了。工具类也提供了输出流的功能,可以用于下载文件或者加载验证码图片,非常方便。


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值