Http协议的重要性相信不用我多说了,HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性(具体区别,日后我们再讨论),它不仅是客户端发送Http请求变得容易,而且也方便了开发人员测试接口(基于Http协议的),即提高了开发的效率,也方便提高代码的健壮性。因此熟练掌握HttpClient是很重要的必修内容,掌握HttpClient后,相信对于Http协议的了解会更加深入。

一、简介

HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议。HttpClient已经应用在很多的项目中,比如Apache Jakarta上很著名的另外两个开源项目Cactus和HTMLUnit都使用了HttpClient。

下载地址: http://hc.apache.org/downloads.cgi

二、特性

1. 基于标准、纯净的Java语言。实现了Http1.0和Http1.1

2. 以可扩展的面向对象的结构实现了Http全部的方法(GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE)。

3. 支持HTTPS协议。

4. 通过Http代理建立透明的连接。

5. 利用CONNECT方法通过Http代理建立隧道的https连接。

6. Basic, Digest, NTLMv1, NTLMv2, NTLM2 Session, SNPNEGO/Kerberos认证方案。

7. 插件式的自定义认证方案。

8. 便携可靠的套接字工厂使它更容易的使用第三方解决方案。

9. 连接管理器支持多线程应用。支持设置最大连接数,同时支持设置每个主机的最大连接数,发现并关闭过期的连接。

10. 自动处理Set-Cookie中的Cookie。

11. 插件式的自定义Cookie策略。

12. Request的输出流可以避免流中内容直接缓冲到socket服务器。

13. Response的输入流可以有效的从socket服务器直接读取相应内容。

14. 在http1.0和http1.1中利用KeepAlive保持持久连接。

15. 直接获取服务器发送的response code和 headers。

16. 设置连接超时的能力。

17. 实验性的支持http1.1 response caching。

18. 源代码基于Apache License 可免费获取。

三、使用方法

使用HttpClient发送请求、接收响应很简单,一般需要如下几步即可。

1. 创建HttpClient对象。

2. 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。

3. 如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HetpParams
params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity
entity)方法来设置请求参数。

4. 调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。

5. 调用HttpResponse的getAllHeaders()、getHeaders(String

name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。

6. 释放连接。无论执行方法是否成功,都必须释放连接

四、实例

  1. package com.test;
  2.  
  3. import java.io.File;
  4. import java.io.FileInputStream;
  5. import java.io.IOException;
  6. import java.io.UnsupportedEncodingException;
  7. import java.security.KeyManagementException;
  8. import java.security.KeyStore;
  9. import java.security.KeyStoreException;
  10. import java.security.NoSuchAlgorithmException;
  11. import java.security.cert.CertificateException;
  12. import java.util.ArrayList;
  13. import java.util.List;
  14.  
  15. import javax.net.ssl.SSLContext;
  16.  
  17. import org.apache.http.HttpEntity;
  18. import org.apache.http.NameValuePair;
  19. import org.apache.http.ParseException;
  20. import org.apache.http.client.ClientProtocolException;
  21. import org.apache.http.client.entity.UrlEncodedFormEntity;
  22. import org.apache.http.client.methods.CloseableHttpResponse;
  23. import org.apache.http.client.methods.HttpGet;
  24. import org.apache.http.client.methods.HttpPost;
  25. import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
  26. import org.apache.http.conn.ssl.SSLContexts;
  27. import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
  28. import org.apache.http.entity.ContentType;
  29. import org.apache.http.entity.mime.MultipartEntityBuilder;
  30. import org.apache.http.entity.mime.content.FileBody;
  31. import org.apache.http.entity.mime.content.StringBody;
  32. import org.apache.http.impl.client.CloseableHttpClient;
  33. import org.apache.http.impl.client.HttpClients;
  34. import org.apache.http.message.BasicNameValuePair;
  35. import org.apache.http.util.EntityUtils;
  36. import org.junit.Test;
  37.  
  38. public class HttpClientTest {
  39.  
  40. @Test
  41. public void jUnitTest() {
  42. get();
  43. }
  44.  
  45. /**
  46. * HttpClient连接SSL
  47. */
  48. public void ssl() {
  49. CloseableHttpClient httpclient = null;
  50. try {
  51. KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
  52. FileInputStream instream = new FileInputStream(new File("d:\\tomcat.keystore"));
  53. try {
  54. // 加载keyStore d:\\tomcat.keystore
  55. trustStore.load(instream, "123456".toCharArray());
  56. } catch (CertificateException e) {
  57. e.printStackTrace();
  58. } finally {
  59. try {
  60. instream.close();
  61. } catch (Exception ignore) {
  62. }
  63. }
  64. // 相信自己的CA和所有自签名的证书
  65. SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
  66. // 只允许使用TLSv1协议
  67. SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null,
  68. SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
  69. httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
  70. // 创建http请求(get方式)
  71. HttpGet httpget = new HttpGet("https://localhost:8443/myDemo/Ajax/serivceJ.action");
  72. System.out.println("executing request" + httpget.getRequestLine());
  73. CloseableHttpResponse response = httpclient.execute(httpget);
  74. try {
  75. HttpEntity entity = response.getEntity();
  76. System.out.println("----------------------------------------");
  77. System.out.println(response.getStatusLine());
  78. if (entity != null) {
  79. System.out.println("Response content length: " + entity.getContentLength());
  80. System.out.println(EntityUtils.toString(entity));
  81. EntityUtils.consume(entity);
  82. }
  83. } finally {
  84. response.close();
  85. }
  86. } catch (ParseException e) {
  87. e.printStackTrace();
  88. } catch (IOException e) {
  89. e.printStackTrace();
  90. } catch (KeyManagementException e) {
  91. e.printStackTrace();
  92. } catch (NoSuchAlgorithmException e) {
  93. e.printStackTrace();
  94. } catch (KeyStoreException e) {
  95. e.printStackTrace();
  96. } finally {
  97. if (httpclient != null) {
  98. try {
  99. httpclient.close();
  100. } catch (IOException e) {
  101. e.printStackTrace();
  102. }
  103. }
  104. }
  105. }
  106.  
  107. /**
  108. * post方式提交表单(模拟用户登录请求)
  109. */
  110. public void postForm() {
  111. // 创建默认的httpClient实例.
  112. CloseableHttpClient httpclient = HttpClients.createDefault();
  113. // 创建httppost
  114. HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceJ.action");
  115. // 创建参数队列
  116. List<NameValuePair> formparams = new ArrayList<NameValuePair>();
  117. formparams.add(new BasicNameValuePair("username", "admin"));
  118. formparams.add(new BasicNameValuePair("password", "123456"));
  119. UrlEncodedFormEntity uefEntity;
  120. try {
  121. uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
  122. httppost.setEntity(uefEntity);
  123. System.out.println("executing request " + httppost.getURI());
  124. CloseableHttpResponse response = httpclient.execute(httppost);
  125. try {
  126. HttpEntity entity = response.getEntity();
  127. if (entity != null) {
  128. System.out.println("--------------------------------------");
  129. System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));
  130. System.out.println("--------------------------------------");
  131. }
  132. } finally {
  133. response.close();
  134. }
  135. } catch (ClientProtocolException e) {
  136. e.printStackTrace();
  137. } catch (UnsupportedEncodingException e1) {
  138. e1.printStackTrace();
  139. } catch (IOException e) {
  140. e.printStackTrace();
  141. } finally {
  142. // 关闭连接,释放资源
  143. try {
  144. httpclient.close();
  145. } catch (IOException e) {
  146. e.printStackTrace();
  147. }
  148. }
  149. }
  150.  
  151. /**
  152. * 发送 post请求访问本地应用并根据传递参数不同返回不同结果
  153. */
  154. public void post() {
  155. // 创建默认的httpClient实例.
  156. CloseableHttpClient httpclient = HttpClients.createDefault();
  157. // 创建httppost
  158. HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceJ.action");
  159. // 创建参数队列
  160. List<NameValuePair> formparams = new ArrayList<NameValuePair>();
  161. formparams.add(new BasicNameValuePair("type", "house"));
  162. UrlEncodedFormEntity uefEntity;
  163. try {
  164. uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
  165. httppost.setEntity(uefEntity);
  166. System.out.println("executing request " + httppost.getURI());
  167. CloseableHttpResponse response = httpclient.execute(httppost);
  168. try {
  169. HttpEntity entity = response.getEntity();
  170. if (entity != null) {
  171. System.out.println("--------------------------------------");
  172. System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));
  173. System.out.println("--------------------------------------");
  174. }
  175. } finally {
  176. response.close();
  177. }
  178. } catch (ClientProtocolException e) {
  179. e.printStackTrace();
  180. } catch (UnsupportedEncodingException e1) {
  181. e1.printStackTrace();
  182. } catch (IOException e) {
  183. e.printStackTrace();
  184. } finally {
  185. // 关闭连接,释放资源
  186. try {
  187. httpclient.close();
  188. } catch (IOException e) {
  189. e.printStackTrace();
  190. }
  191. }
  192. }
  193.  
  194. /**
  195. * 发送 get请求
  196. */
  197. public void get() {
  198. CloseableHttpClient httpclient = HttpClients.createDefault();
  199. try {
  200. // 创建httpget.
  201. HttpGet httpget = new HttpGet("http://www.baidu.com/");
  202. System.out.println("executing request " + httpget.getURI());
  203. // 执行get请求.
  204. CloseableHttpResponse response = httpclient.execute(httpget);
  205. try {
  206. // 获取响应实体
  207. HttpEntity entity = response.getEntity();
  208. System.out.println("--------------------------------------");
  209. // 打印响应状态
  210. System.out.println(response.getStatusLine());
  211. if (entity != null) {
  212. // 打印响应内容长度
  213. System.out.println("Response content length: " + entity.getContentLength());
  214. // 打印响应内容
  215. System.out.println("Response content: " + EntityUtils.toString(entity));
  216. }
  217. System.out.println("------------------------------------");
  218. } finally {
  219. response.close();
  220. }
  221. } catch (ClientProtocolException e) {
  222. e.printStackTrace();
  223. } catch (ParseException e) {
  224. e.printStackTrace();
  225. } catch (IOException e) {
  226. e.printStackTrace();
  227. } finally {
  228. // 关闭连接,释放资源
  229. try {
  230. httpclient.close();
  231. } catch (IOException e) {
  232. e.printStackTrace();
  233. }
  234. }
  235. }
  236.  
  237. /**
  238. * 上传文件
  239. */
  240. public void upload() {
  241. CloseableHttpClient httpclient = HttpClients.createDefault();
  242. try {
  243. HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceFile.action");
  244.  
  245. FileBody bin = new FileBody(new File("F:\\image\\sendpix0.jpg"));
  246. StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);
  247.  
  248. HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bin", bin).addPart("comment", comment).build();
  249.  
  250. httppost.setEntity(reqEntity);
  251.  
  252. System.out.println("executing request " + httppost.getRequestLine());
  253. CloseableHttpResponse response = httpclient.execute(httppost);
  254. try {
  255. System.out.println("----------------------------------------");
  256. System.out.println(response.getStatusLine());
  257. HttpEntity resEntity = response.getEntity();
  258. if (resEntity != null) {
  259. System.out.println("Response content length: " + resEntity.getContentLength());
  260. }
  261. EntityUtils.consume(resEntity);
  262. } finally {
  263. response.close();
  264. }
  265. } catch (ClientProtocolException e) {
  266. e.printStackTrace();
  267. } catch (IOException e) {
  268. e.printStackTrace();
  269. } finally {
  270. try {
  271. httpclient.close();
  272. } catch (IOException e) {
  273. e.printStackTrace();
  274. }
  275. }
  276. }
  277. }

五、实例(开发用到工具类实例)

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

HttpClient使用详解 (一)的更多相关文章

  1. HttpClient使用详解(转)

     HttpClient使用详解 Http协议的重要性相信不用我多说了,HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性(具体区别,日后我们再讨论),它不仅是客户 ...

  2. HttpClient使用详解

    http://itindex.net/detail/52566-httpclient HttpClient使用详解 标签: httpclient | 发表时间:2015-01-22 12:07 | 作 ...

  3. Java进阶(三十二) HttpClient使用详解

    Java进阶(三十二) HttpClient使用详解 Http协议的重要性相信不用我多说了,HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性(具体区别,日后我们 ...

  4. gvoory脚本中关于HttpClient使用详解实例

    一.gvoory脚本中关于HttpClient使用详解实例 HttpClient:是一个接口 首先需要先创建一个DefaultHttpClient的实例 HttpClient httpClient=n ...

  5. HttpClient请求详解

    HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的.最新的.功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建 ...

  6. HttpClient类详解

    文章链接:https://blog.csdn.net/justry_deng/article/details/81042379 HTTP 协议可能是现在 Internet 上使用得最多.最重要的协议了 ...

  7. 转载:HttpClient使用详解

    原文地址:http://blog.csdn.net/wangpeng047/article/details/19624529 Http协议的重要性相信不用我多说了,HttpClient相比传统JDK自 ...

  8. [转]HttpClient使用详解

    Http协议的重要性相信不用我多说了,HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性(具体区别,日后我们再讨论),它不仅是客户端发送Http请求变得容易,而且 ...

  9. Asp.Net MVC WebAPI的创建与前台Jquery ajax后台HttpClient调用详解

    1.什么是WebApi,它有什么用途? Web API是一个比较宽泛的概念.这里我们提到Web API特指ASP.NET MVC Web API.在新出的MVC中,增加了WebAPI,用于提供REST ...

随机推荐

  1. UVA - 1160(简单建模+并查集)

    A secret service developed a new kind of explosive that attain its volatile property only when a spe ...

  2. SwaggerUI用户手册

    SwaggerUI是一个非常好用的API文档工具,最关键的是他还能在工具内调试API,简直爽的不要不要的~网上针对开发者的文档非常多,但是给用户的手册却非常少.所以我来简单写个用户手册,供没有使用过s ...

  3. 我的QT5学习之路(四)——信号槽

    一.前言 前面说了Qt最基本的实例创建.控件以及工具集的介绍,相当于对于Qt有了一个初次的认识,这次我们开始认识Qt信号通信的重点之一——信号槽. 二.信号槽 信号槽是 Qt 框架引以为豪的机制之一. ...

  4. jquery checkbox点选反选

    <script type="text/javascript"> $(function(){ //点选反选 $("#check_all").click ...

  5. 记一次jvm异常排查及优化

    为方便自己查看,根据工作遇到的问题,转载并整理以下jvm优化内容 有次接到客服反馈,生产系统异常,无法访问.接到通知紧急上后台跟踪,查看了数据库死锁情况--正常,接着查看tomcat 内存溢出--正常 ...

  6. Java Activiti 工作流引擎 springmvc SSM 流程审批 后台框架源码

    1.模型管理 :web在线流程设计器.预览流程xml.导出xml.部署流程 2.流程管理 :导入导出流程资源文件.查看流程图.根据流程实例反射出流程模型.激活挂起 3.运行中流程:查看流程信息.当前任 ...

  7. MySQL初体验--安装MySQL

    操作系统版本:redhat 6.7 64位 [root@mysql ~]# cat /etc/redhat-release Red Hat Enterprise Linux Server releas ...

  8. js(jQuery)tips

    一:页面加上$(function(){***内容***})与不加的区别 1.这个是DOM加载完之后再加载JS代码,你的JS如果放在文档后面可能一样,但是如果你要是把JS放在head里面就有差别了(放在 ...

  9. django 登录注册注销

    一.设计数据模型 1.数据库模型设计 作为一个用户登录和注册项目,需要保存的都是各种用户的相关信息.很显然,我们至少需要一张用户表User,在用户表里需要保存下面的信息: 用户名 密码 邮箱地址 性别 ...

  10. firefox burp ssl证书配置

    打开浏览器 设置->证书->证书频发机构->添加证书 添加成功->找到位置->编辑信任->信任->查看证书 导出-> win下可直接安装证书->受 ...