基于HttpClient的HttpUtils(后台访问URL)

      最近做在线支付时遇到需要以后台方式访问URL并获取其返回的数据的问题,在网络上g了一把,发现在常用的还是Apache的HttpClient。因为以经常要用到的原故,因此我对其进行了一些简单的封装,在此将代码贴一来,希望对有需要的朋友有所帮助,呵呵...

      HttpUtils.java中有两个公共的静态方法,一个是URLPost,另一个是URLGet,一目了然,前者是提供POST方式提交数据的,后者是提供GET方式提交数据的。其中所需要传送的数据以Map的方式传入,剩下的工作就交给我这个HttpUtils吧!当然如果Http服务器端对所提交的数据的编码有要求的话,也没问题,你可以传入UTF-8或者GBK,当然大家还可自行增加。

      下面是源代码,如果使用中有什么问题,欢迎大家提出。

Java代码  收藏代码
  1. import java.io.IOException;  
  2. import java.io.UnsupportedEncodingException;  
  3. import java.net.URLEncoder;  
  4. import java.util.Iterator;  
  5. import java.util.Map;  
  6. import java.util.Set;  
  7.   
  8. import org.apache.commons.httpclient.HttpClient;  
  9. import org.apache.commons.httpclient.HttpException;  
  10. import org.apache.commons.httpclient.HttpStatus;  
  11. import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;  
  12. import org.apache.commons.httpclient.methods.GetMethod;  
  13. import org.apache.commons.httpclient.methods.PostMethod;  
  14. import org.apache.commons.logging.Log;  
  15. import org.apache.commons.logging.LogFactory;  
  16.   
  17. /** 
  18.  * HTTP工具类 
  19.  *  
  20.  * @author lixiangyang 
  21.  *  
  22.  */  
  23. public class HttpUtils {  
  24.   
  25.     private static Log log = LogFactory.getLog(HttpUtils.class);  
  26.       
  27.     /** 
  28.      * 定义编码格式 UTF-8 
  29.      */  
  30.     public static final String URL_PARAM_DECODECHARSET_UTF8 = "UTF-8";  
  31.       
  32.     /** 
  33.      * 定义编码格式 GBK 
  34.      */  
  35.     public static final String URL_PARAM_DECODECHARSET_GBK = "GBK";  
  36.       
  37.     private static final String URL_PARAM_CONNECT_FLAG = "&";  
  38.       
  39.     private static final String EMPTY = "";  
  40.   
  41.     private static MultiThreadedHttpConnectionManager connectionManager = null;  
  42.   
  43.     private static int connectionTimeOut = 25000;  
  44.   
  45.     private static int socketTimeOut = 25000;  
  46.   
  47.     private static int maxConnectionPerHost = 20;  
  48.   
  49.     private static int maxTotalConnections = 20;  
  50.   
  51.     private static HttpClient client;  
  52.   
  53.     static{  
  54.         connectionManager = new MultiThreadedHttpConnectionManager();  
  55.         connectionManager.getParams().setConnectionTimeout(connectionTimeOut);  
  56.         connectionManager.getParams().setSoTimeout(socketTimeOut);  
  57.         connectionManager.getParams().setDefaultMaxConnectionsPerHost(maxConnectionPerHost);  
  58.         connectionManager.getParams().setMaxTotalConnections(maxTotalConnections);  
  59.         client = new HttpClient(connectionManager);  
  60.     }  
  61.       
  62.     /** 
  63.      * POST方式提交数据 
  64.      * @param url 
  65.      *          待请求的URL 
  66.      * @param params 
  67.      *          要提交的数据 
  68.      * @param enc 
  69.      *          编码 
  70.      * @return 
  71.      *          响应结果 
  72.      * @throws IOException 
  73.      *          IO异常 
  74.      */  
  75.     public static String URLPost(String url, Map<String, String> params, String enc){  
  76.   
  77.         String response = EMPTY;          
  78.         PostMethod postMethod = null;  
  79.         try {  
  80.             postMethod = new PostMethod(url);  
  81.             postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=" + enc);  
  82.             //将表单的值放入postMethod中  
  83.             Set<String> keySet = params.keySet();  
  84.             for(String key : keySet){  
  85.                 String value = params.get(key);  
  86.                 postMethod.addParameter(key, value);  
  87.             }             
  88.             //执行postMethod  
  89.             int statusCode = client.executeMethod(postMethod);  
  90.             if(statusCode == HttpStatus.SC_OK) {  
  91.                 response = postMethod.getResponseBodyAsString();  
  92.             }else{  
  93.                 log.error("响应状态码 = " + postMethod.getStatusCode());  
  94.             }  
  95.         }catch(HttpException e){  
  96.             log.error("发生致命的异常,可能是协议不对或者返回的内容有问题", e);  
  97.             e.printStackTrace();  
  98.         }catch(IOException e){  
  99.             log.error("发生网络异常", e);  
  100.             e.printStackTrace();  
  101.         }finally{  
  102.             if(postMethod != null){  
  103.                 postMethod.releaseConnection();  
  104.                 postMethod = null;  
  105.             }  
  106.         }  
  107.           
  108.         return response;  
  109.     }  
  110.       
  111.     /** 
  112.      * GET方式提交数据 
  113.      * @param url 
  114.      *          待请求的URL 
  115.      * @param params 
  116.      *          要提交的数据 
  117.      * @param enc 
  118.      *          编码 
  119.      * @return 
  120.      *          响应结果 
  121.      * @throws IOException 
  122.      *          IO异常 
  123.      */  
  124.     public static String URLGet(String url, Map<String, String> params, String enc){  
  125.   
  126.         String response = EMPTY;  
  127.         GetMethod getMethod = null;       
  128.         StringBuffer strtTotalURL = new StringBuffer(EMPTY);  
  129.           
  130.         if(strtTotalURL.indexOf("?") == -1) {  
  131.           strtTotalURL.append(url).append("?").append(getUrl(params, enc));  
  132.         } else {  
  133.             strtTotalURL.append(url).append("&").append(getUrl(params, enc));  
  134.         }  
  135.         log.debug("GET请求URL =  " + strtTotalURL.toString());  
  136.           
  137.         try {  
  138.             getMethod = new GetMethod(strtTotalURL.toString());  
  139.             getMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=" + enc);  
  140.             //执行getMethod  
  141.             int statusCode = client.executeMethod(getMethod);  
  142.             if(statusCode == HttpStatus.SC_OK) {  
  143.                 response = getMethod.getResponseBodyAsString();  
  144.             }else{  
  145.                 log.debug("响应状态码 = " + getMethod.getStatusCode());  
  146.             }  
  147.         }catch(HttpException e){  
  148.             log.error("发生致命的异常,可能是协议不对或者返回的内容有问题", e);  
  149.             e.printStackTrace();  
  150.         }catch(IOException e){  
  151.             log.error("发生网络异常", e);  
  152.             e.printStackTrace();  
  153.         }finally{  
  154.             if(getMethod != null){  
  155.                 getMethod.releaseConnection();  
  156.                 getMethod = null;  
  157.             }  
  158.         }  
  159.           
  160.         return response;  
  161.     }     
  162.   
  163.     /** 
  164.      * 据Map生成URL字符串 
  165.      * @param map 
  166.      *          Map 
  167.      * @param valueEnc 
  168.      *          URL编码 
  169.      * @return 
  170.      *          URL 
  171.      */  
  172.     private static String getUrl(Map<String, String> map, String valueEnc) {  
  173.           
  174.         if (null == map || map.keySet().size() == 0) {  
  175.             return (EMPTY);  
  176.         }  
  177.         StringBuffer url = new StringBuffer();  
  178.         Set<String> keys = map.keySet();  
  179.         for (Iterator<String> it = keys.iterator(); it.hasNext();) {  
  180.             String key = it.next();  
  181.             if (map.containsKey(key)) {  
  182.                 String val = map.get(key);  
  183.                 String str = val != null ? val : EMPTY;  
  184.                 try {  
  185.                     str = URLEncoder.encode(str, valueEnc);  
  186.                 } catch (UnsupportedEncodingException e) {  
  187.                     e.printStackTrace();  
  188.                 }  
  189.                 url.append(key).append("=").append(str).append(URL_PARAM_CONNECT_FLAG);  
  190.             }  
  191.         }  
  192.         String strURL = EMPTY;  
  193.         strURL = url.toString();  
  194.         if (URL_PARAM_CONNECT_FLAG.equals(EMPTY + strURL.charAt(strURL.length() - 1))) {  
  195.             strURL = strURL.substring(0, strURL.length() - 1);  
  196.         }  
  197.           
  198.         return (strURL);  
  199.     }  
  200. }  
原文地址:https://www.cnblogs.com/maohuidong/p/8044662.html