httpclient工具类java

Java代码   收藏代码
  1. package com.zb.com.tool.util;  
  2.   
  3. import java.io.File;  
  4. import java.io.IOException;  
  5. import java.net.URISyntaxException;  
  6. import java.nio.charset.Charset;  
  7. import java.security.cert.CertificateException;  
  8. import java.util.List;  
  9. import java.util.Map;  
  10.   
  11. import javax.net.ssl.SSLContext;  
  12. import javax.net.ssl.SSLHandshakeException;  
  13. import javax.net.ssl.TrustManager;  
  14. import javax.net.ssl.X509TrustManager;  
  15.   
  16. import org.apache.http.HttpEntity;  
  17. import org.apache.http.HttpEntityEnclosingRequest;  
  18. import org.apache.http.HttpHost;  
  19. import org.apache.http.HttpRequest;  
  20. import org.apache.http.HttpResponse;  
  21. import org.apache.http.NameValuePair;  
  22. import org.apache.http.NoHttpResponseException;  
  23. import org.apache.http.client.ClientProtocolException;  
  24. import org.apache.http.client.HttpRequestRetryHandler;  
  25. import org.apache.http.client.ResponseHandler;  
  26. import org.apache.http.client.methods.HttpGet;  
  27. import org.apache.http.client.methods.HttpPost;  
  28. import org.apache.http.client.params.ClientPNames;  
  29. import org.apache.http.client.params.CookiePolicy;  
  30. import org.apache.http.client.utils.URLEncodedUtils;  
  31. import org.apache.http.conn.params.ConnRoutePNames;  
  32. import org.apache.http.conn.scheme.Scheme;  
  33. import org.apache.http.conn.ssl.SSLSocketFactory;  
  34. import org.apache.http.entity.StringEntity;  
  35. import org.apache.http.entity.mime.MultipartEntity;  
  36. import org.apache.http.entity.mime.content.ByteArrayBody;  
  37. import org.apache.http.entity.mime.content.FileBody;  
  38. import org.apache.http.entity.mime.content.StringBody;  
  39. import org.apache.http.impl.client.DefaultHttpClient;  
  40. import org.apache.http.params.CoreProtocolPNames;  
  41. import org.apache.http.protocol.ExecutionContext;  
  42. import org.apache.http.protocol.HttpContext;  
  43. import org.apache.http.util.EntityUtils;  
  44.   
  45. /** 
  46.  * @className:HttpClientUtil.java 
  47.  * @classDescription:HttpClient工具类//待完善模拟登录,cookie,证书登录 
  48.  * @author:xiayingjie 
  49.  * @createTime:2011-8-31 
  50.  */  
  51.   
  52. public class HttpClientUtil {  
  53.   
  54.     public static String CHARSET_ENCODING = "UTF-8";  
  55.     // private static String  
  56.     // USER_AGENT="Mozilla/4.0 (compatible; MSIE 6.0; Win32)";//ie6  
  57.     public static String USER_AGENT = "Mozilla/4.0 (compatible; MSIE 7.0; Win32)";// ie7  
  58.   
  59.     // private static String  
  60.     // USER_AGENT="Mozilla/4.0 (compatible; MSIE 8.0; Win32)";//ie8  
  61.   
  62.     /** 
  63.      * 获取DefaultHttpClient对象 
  64.      *  
  65.      * @param charset 
  66.      *            字符编码 
  67.      * @return DefaultHttpClient对象 
  68.      */  
  69.     private static DefaultHttpClient getDefaultHttpClient(final String charset) {  
  70.         DefaultHttpClient httpclient = new DefaultHttpClient();  
  71.         // 模拟浏览器,解决一些服务器程序只允许浏览器访问的问题  
  72.         httpclient.getParams().setParameter(CoreProtocolPNames.USER_AGENT,  
  73.                 USER_AGENT);  
  74.         httpclient.getParams().setParameter(  
  75.                 CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE);  
  76.         httpclient.getParams().setParameter(  
  77.                 CoreProtocolPNames.HTTP_CONTENT_CHARSET,  
  78.                 charset == null ? CHARSET_ENCODING : charset);  
  79.           
  80.         // 浏览器兼容性  
  81.         httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY,  
  82.                 CookiePolicy.BROWSER_COMPATIBILITY);  
  83.         // 定义重试策略  
  84.         httpclient.setHttpRequestRetryHandler(requestRetryHandler);  
  85.           
  86.         return httpclient;  
  87.     }  
  88.     /** 
  89.      * 访问https的网站 
  90.      * @param httpclient 
  91.      */  
  92.     private static void enableSSL(DefaultHttpClient httpclient){  
  93.         //调用ssl  
  94.          try {  
  95.                 SSLContext sslcontext = SSLContext.getInstance("TLS");  
  96.                 sslcontext.init(nullnew TrustManager[] { truseAllManager }, null);  
  97.                 SSLSocketFactory sf = new SSLSocketFactory(sslcontext);  
  98.                 sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);  
  99.                 Scheme https = new Scheme("https", sf, 443);  
  100.                 httpclient.getConnectionManager().getSchemeRegistry()  
  101.                         .register(https);  
  102.             } catch (Exception e) {  
  103.                 e.printStackTrace();  
  104.             }  
  105.     }  
  106.     /** 
  107.      * 重写验证方法,取消检测ssl 
  108.      */  
  109.     private static TrustManager truseAllManager = new X509TrustManager(){  
  110.   
  111.         public void checkClientTrusted(  
  112.                 java.security.cert.X509Certificate[] arg0, String arg1)  
  113.                 throws CertificateException {  
  114.             // TODO Auto-generated method stub  
  115.               
  116.         }  
  117.   
  118.         public void checkServerTrusted(  
  119.                 java.security.cert.X509Certificate[] arg0, String arg1)  
  120.                 throws CertificateException {  
  121.             // TODO Auto-generated method stub  
  122.               
  123.         }  
  124.   
  125.         public java.security.cert.X509Certificate[] getAcceptedIssuers() {  
  126.             // TODO Auto-generated method stub  
  127.             return null;  
  128.         }  
  129.           
  130.     } ;  
  131.   
  132.     /** 
  133.      * 异常自动恢复处理, 使用HttpRequestRetryHandler接口实现请求的异常恢复 
  134.      */  
  135.     private static HttpRequestRetryHandler requestRetryHandler = new HttpRequestRetryHandler() {  
  136.         // 自定义的恢复策略  
  137.         public boolean retryRequest(IOException exception, int executionCount,  
  138.                 HttpContext context) {  
  139.             // 设置恢复策略,在发生异常时候将自动重试3次  
  140.             if (executionCount >= 3) {  
  141.                 // 如果连接次数超过了最大值则停止重试  
  142.                 return false;  
  143.             }  
  144.             if (exception instanceof NoHttpResponseException) {  
  145.                 // 如果服务器连接失败重试  
  146.                 return true;  
  147.             }  
  148.             if (exception instanceof SSLHandshakeException) {  
  149.                 // 不要重试ssl连接异常  
  150.                 return false;  
  151.             }  
  152.             HttpRequest request = (HttpRequest) context  
  153.                     .getAttribute(ExecutionContext.HTTP_REQUEST);  
  154.             boolean idempotent = (request instanceof HttpEntityEnclosingRequest);  
  155.             if (!idempotent) {  
  156.                 // 重试,如果请求是考虑幂等  
  157.                 return true;  
  158.             }  
  159.             return false;  
  160.         }  
  161.     };  
  162.   
  163.     /** 
  164.      * 使用ResponseHandler接口处理响应,HttpClient使用ResponseHandler会自动管理连接的释放,解决了对连接的释放管理 
  165.      */  
  166.     private static ResponseHandler<String> responseHandler = new ResponseHandler<String>() {  
  167.         // 自定义响应处理  
  168.         public String handleResponse(HttpResponse response)  
  169.                 throws ClientProtocolException, IOException {  
  170.             HttpEntity entity = response.getEntity();  
  171.             if (entity != null) {  
  172.                 String charset = EntityUtils.getContentCharSet(entity) == null ? CHARSET_ENCODING  
  173.                         : EntityUtils.getContentCharSet(entity);  
  174.                 return new String(EntityUtils.toByteArray(entity), charset);  
  175.             } else {  
  176.                 return null;  
  177.             }  
  178.         }  
  179.     };  
  180.   
  181.     /** 
  182.      * 使用post方法获取相关的数据 
  183.      *  
  184.      * @param url 
  185.      * @param paramsList 
  186.      * @return 
  187.      */  
  188.     public static String post(String url, List<NameValuePair> paramsList) {  
  189.         return httpRequest(url, paramsList, "POST"null);  
  190.     }  
  191.   
  192.     /** 
  193.      * 使用post方法并且通过代理获取相关的数据 
  194.      *  
  195.      * @param url 
  196.      * @param paramsList 
  197.      * @param proxy 
  198.      * @return 
  199.      */  
  200.     public static String post(String url, List<NameValuePair> paramsList,  
  201.             HttpHost proxy) {  
  202.         return httpRequest(url, paramsList, "POST", proxy);  
  203.     }  
  204.   
  205.     /** 
  206.      * 使用get方法获取相关的数据 
  207.      *  
  208.      * @param url 
  209.      * @param paramsList 
  210.      * @return 
  211.      */  
  212.     public static String get(String url, List<NameValuePair> paramsList) {  
  213.         return httpRequest(url, paramsList, "GET"null);  
  214.     }  
  215.   
  216.     /** 
  217.      * 使用get方法并且通过代理获取相关的数据 
  218.      *  
  219.      * @param url 
  220.      * @param paramsList 
  221.      * @param proxy 
  222.      * @return 
  223.      */  
  224.     public static String get(String url, List<NameValuePair> paramsList,  
  225.             HttpHost proxy) {  
  226.         return httpRequest(url, paramsList, "GET", proxy);  
  227.     }  
  228.   
  229.     /** 
  230.      * 提交数据到服务器 
  231.      *  
  232.      * @param url 
  233.      * @param params 
  234.      * @param authenticated 
  235.      * @throws IOException 
  236.      * @throws ClientProtocolException 
  237.      */  
  238.     public static String httpRequest(String url,  
  239.             List<NameValuePair> paramsList, String method, HttpHost proxy) {  
  240.         String responseStr = null;  
  241.         // 判断输入的值是是否为空  
  242.         if (null == url || "".equals(url)) {  
  243.             return null;  
  244.         }  
  245.           
  246.         // 创建HttpClient实例  
  247.         DefaultHttpClient httpclient = getDefaultHttpClient(CHARSET_ENCODING);  
  248.           
  249.         //判断是否是https请求  
  250.         if(url.startsWith("https")){  
  251.             enableSSL(httpclient);  
  252.         }  
  253.         String formatParams = null;  
  254.         // 将参数进行utf-8编码  
  255.         if (null != paramsList && paramsList.size() > 0) {  
  256.             formatParams = URLEncodedUtils.format(paramsList, CHARSET_ENCODING);  
  257.         }  
  258.         // 如果代理对象不为空则设置代理  
  259.         if (null != proxy) {  
  260.             httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,  
  261.                     proxy);  
  262.         }  
  263.         try {  
  264.             // 如果方法为Get  
  265.             if ("GET".equalsIgnoreCase(method)) {  
  266.                 if (formatParams != null) {  
  267.                     url = (url.indexOf("?")) < 0 ? (url + "?" + formatParams)  
  268.                             : (url.substring(0, url.indexOf("?") + 1) + formatParams);  
  269.                 }  
  270.                 HttpGet hg = new HttpGet(url);  
  271.                 responseStr = httpclient.execute(hg, responseHandler);  
  272.   
  273.                 // 如果方法为Post  
  274.             } else if ("POST".equalsIgnoreCase(method)) {  
  275.                 HttpPost hp = new HttpPost(url);  
  276.                 if (formatParams != null) {  
  277.                     StringEntity entity = new StringEntity(formatParams);  
  278.                     entity.setContentType("application/x-www-form-urlencoded");  
  279.                     hp.setEntity(entity);  
  280.                 }  
  281.                 responseStr = httpclient.execute(hp, responseHandler);  
  282.                   
  283.             }  
  284.   
  285.         } catch (ClientProtocolException e) {  
  286.             // TODO Auto-generated catch block  
  287.             e.printStackTrace();  
  288.         } catch (IOException e) {  
  289.             // TODO Auto-generated catch block  
  290.             e.printStackTrace();  
  291.         }  
  292.         return responseStr;  
  293.     }  
  294.   
  295.   
  296.     /** 
  297.      * 提交数据到服务器 
  298.      *  
  299.      * @param url 
  300.      * @param params 
  301.      * @param authenticated 
  302.      * @throws IOException 
  303.      * @throws ClientProtocolException 
  304.      */  
  305.     public static String httpFileRequest(String url,  
  306.              Map<String, String> fileMap,Map<String, String> stringMap,int type, HttpHost proxy) {  
  307.         String responseStr = null;  
  308.         // 判断输入的值是是否为空  
  309.         if (null == url || "".equals(url)) {  
  310.             return null;  
  311.         }  
  312.         // 创建HttpClient实例  
  313.         DefaultHttpClient httpclient = getDefaultHttpClient(CHARSET_ENCODING);  
  314.           
  315.         //判断是否是https请求  
  316.         if(url.startsWith("https")){  
  317.             enableSSL(httpclient);  
  318.         }  
  319.           
  320.         // 如果代理对象不为空则设置代理  
  321.         if (null != proxy) {  
  322.             httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,  
  323.                     proxy);  
  324.         }  
  325.         //发送文件  
  326.         HttpPost hp = new HttpPost(url);  
  327.         MultipartEntity multiEntity = new MultipartEntity();  
  328.         try {  
  329.             //type=0是本地路径,否则是网络路径  
  330.             if(type==0){  
  331.                 for (String key : fileMap.keySet()) {  
  332.                     multiEntity.addPart(key, new FileBody(new File(fileMap.get(key))));  
  333.                 }  
  334.             }else{  
  335.                 for (String key : fileMap.keySet()) {                 
  336.                     multiEntity.addPart(key,new ByteArrayBody(getUrlFileBytes(fileMap.get(key)),key));  
  337.                 }  
  338.             }  
  339.             // 加入相关参数 默认编码为utf-8  
  340.             for (String key : stringMap.keySet()) {  
  341.                 multiEntity.addPart(key, new StringBody(stringMap.get(key),Charset.forName(CHARSET_ENCODING)));  
  342.             }  
  343.             hp.setEntity(multiEntity);  
  344.             responseStr = httpclient.execute(hp, responseHandler);  
  345.         } catch (Exception e) {  
  346.             // TODO Auto-generated catch block  
  347.             e.printStackTrace();  
  348.         }  
  349.         return responseStr;  
  350.     }  
  351.       
  352.     /** 
  353.      * 将相关文件和参数提交到相关服务器 
  354.      * @param url 
  355.      * @param fileMap 
  356.      * @param StringMap 
  357.      * @return 
  358.      */  
  359.     public static String postFile(String url, Map<String, String> fileMap,  
  360.             Map<String, String> stringMap) {  
  361.         return httpFileRequest( url,fileMap,stringMap,0null);   
  362.     }  
  363.     /** 
  364.      * 将相关文件和参数提交到相关服务器 
  365.      * @param url 
  366.      * @param fileMap 
  367.      * @param StringMap 
  368.      * @return 
  369.      */  
  370.     public static String postUrlFile(String url, Map<String, String> urlMap,  
  371.             Map<String, String> stringMap) {  
  372.         return httpFileRequest( url,urlMap,stringMap,1null);  
  373.     }  
  374.   
  375.     /** 
  376.      * 获取网络文件的字节数组 
  377.      *  
  378.      * @param url 
  379.      * @return 
  380.      * @throws IOException 
  381.      * @throws ClientProtocolException 
  382.      * @throws ClientProtocolException 
  383.      * @throws IOException 
  384.      */  
  385.     public static byte[] getUrlFileBytes(String url) throws ClientProtocolException,  
  386.             IOException {  
  387.           
  388.         byte[] bytes = null;  
  389.         // 创建HttpClient实例  
  390.         DefaultHttpClient httpclient = getDefaultHttpClient(CHARSET_ENCODING);  
  391.         // 获取url里面的信息  
  392.         HttpGet hg = new HttpGet(url);  
  393.         HttpResponse hr = httpclient.execute(hg);  
  394.         bytes = EntityUtils.toByteArray(hr.getEntity());  
  395.         // 转换内容为字节  
  396.         return bytes;  
  397.     }  
  398.   
  399.     /** 
  400.      * 获取图片的字节数组 
  401.      *  
  402.      * @createTime 2011-11-24 
  403.      * @param url 
  404.      * @return 
  405.      * @throws IOException 
  406.      * @throws ClientProtocolException 
  407.      * @throws ClientProtocolException 
  408.      * @throws IOException 
  409.      */  
  410.     public static byte[] getImg(String url) throws ClientProtocolException,  
  411.             IOException {  
  412.         byte[] bytes = null;  
  413.         // 创建HttpClient实例  
  414.         DefaultHttpClient httpclient = getDefaultHttpClient(CHARSET_ENCODING);  
  415.         // 获取url里面的信息  
  416.         HttpGet hg = new HttpGet(url);  
  417.         HttpResponse hr = httpclient.execute(hg);  
  418.         bytes = EntityUtils.toByteArray(hr.getEntity());  
  419.         // 转换内容为字节  
  420.         return bytes;  
  421.     }  
  422.   
  423.     public static void main(String[] args) throws URISyntaxException, ClientProtocolException, IOException {  
  424.   
  425.         String url="http://www.baidu.com/";  
  426.         String str=HttpClientUtil.get(url, null);  
  427.         System.out.println(str);  
  428.   
  429.     }  
  430.   
  431. }  

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值