httpclient4.3  java工具类。

。。

。因项目须要开发了一个工具类。正经常常使用的httpclient 请求操作应该都够用了

工具类下载地址:http://download.csdn.net/detail/ruishenh/7421641

  1. package com.ruishenh.utils;
  2.  
  3. import java.io.IOException;
  4. import java.io.UnsupportedEncodingException;
  5. import java.net.URISyntaxException;
  6. import java.nio.charset.Charset;
  7. import java.util.ArrayList;
  8. import java.util.HashMap;
  9. import java.util.List;
  10. import java.util.Map;
  11.  
  12. import org.apache.commons.httpclient.HttpStatus;
  13. import org.apache.http.HttpEntity;
  14. import org.apache.http.HttpException;
  15. import org.apache.http.HttpResponse;
  16. import org.apache.http.NameValuePair;
  17. import org.apache.http.client.ClientProtocolException;
  18. import org.apache.http.client.HttpClient;
  19. import org.apache.http.client.config.RequestConfig;
  20. import org.apache.http.client.entity.UrlEncodedFormEntity;
  21. import org.apache.http.client.methods.HttpGet;
  22. import org.apache.http.client.methods.HttpPost;
  23. import org.apache.http.client.methods.HttpRequestBase;
  24. import org.apache.http.client.utils.URLEncodedUtils;
  25. import org.apache.http.impl.client.CloseableHttpClient;
  26. import org.apache.http.impl.client.HttpClientBuilder;
  27. import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
  28. import org.apache.http.message.BasicNameValuePair;
  29. import org.apache.http.protocol.HTTP;
  30. import org.apache.http.util.EntityUtils;
  31.  
  32. public class HttpClientUtils {
  33. /**
  34. * 连接超时时间
  35. */
  36. public static final int CONNECTION_TIMEOUT_MS = 360000;
  37.  
  38. /**
  39. * 读取数据超时时间
  40. */
  41. public static final int SO_TIMEOUT_MS = 360000;
  42.  
  43. public static final String CONTENT_TYPE_JSON_CHARSET = "application/json;charset=gbk";
  44.  
  45. public static final String CONTENT_TYPE_XML_CHARSET = "application/xml;charset=gbk";
  46.  
  47. /**
  48. * httpclient读取内容时使用的字符集
  49. */
  50. public static final String CONTENT_CHARSET = "GBK";
  51.  
  52. public static final Charset UTF_8 = Charset.forName("UTF-8");
  53.  
  54. public static final Charset GBK = Charset.forName(CONTENT_CHARSET);
  55.  
  56. /**
  57. * 简单get调用
  58. *
  59. * @param url
  60. * @param params
  61. * @return
  62. * @throws ClientProtocolException
  63. * @throws IOException
  64. * @throws URISyntaxException
  65. */
  66. public static String simpleGetInvoke(String url, Map<String, String> params)
  67. throws ClientProtocolException, IOException, URISyntaxException {
  68. return simpleGetInvoke(url, params,CONTENT_CHARSET);
  69. }
  70. /**
  71. * 简单get调用
  72. *
  73. * @param url
  74. * @param params
  75. * @return
  76. * @throws ClientProtocolException
  77. * @throws IOException
  78. * @throws URISyntaxException
  79. */
  80. public static String simpleGetInvoke(String url, Map<String, String> params,String charset)
  81. throws ClientProtocolException, IOException, URISyntaxException {
  82.  
  83. HttpClient client = buildHttpClient(false);
  84.  
  85. HttpGet get = buildHttpGet(url, params);
  86.  
  87. HttpResponse response = client.execute(get);
  88.  
  89. assertStatus(response);
  90.  
  91. HttpEntity entity = response.getEntity();
  92. if (entity != null) {
  93. String returnStr = EntityUtils.toString(entity,charset);
  94. return returnStr;
  95. }
  96. return null;
  97. }
  98.  
  99. /**
  100. * 简单post调用
  101. *
  102. * @param url
  103. * @param params
  104. * @return
  105. * @throws URISyntaxException
  106. * @throws ClientProtocolException
  107. * @throws IOException
  108. */
  109. public static String simplePostInvoke(String url, Map<String, String> params)
  110. throws URISyntaxException, ClientProtocolException, IOException {
  111. return simplePostInvoke(url, params,CONTENT_CHARSET);
  112. }
  113. /**
  114. * 简单post调用
  115. *
  116. * @param url
  117. * @param params
  118. * @return
  119. * @throws URISyntaxException
  120. * @throws ClientProtocolException
  121. * @throws IOException
  122. */
  123. public static String simplePostInvoke(String url, Map<String, String> params,String charset)
  124. throws URISyntaxException, ClientProtocolException, IOException {
  125.  
  126. HttpClient client = buildHttpClient(false);
  127.  
  128. HttpPost postMethod = buildHttpPost(url, params);
  129.  
  130. HttpResponse response = client.execute(postMethod);
  131.  
  132. assertStatus(response);
  133.  
  134. HttpEntity entity = response.getEntity();
  135.  
  136. if (entity != null) {
  137. String returnStr = EntityUtils.toString(entity, charset);
  138. return returnStr;
  139. }
  140.  
  141. return null;
  142. }
  143.  
  144. /**
  145. * 创建HttpClient
  146. *
  147. * @param isMultiThread
  148. * @return
  149. */
  150. public static HttpClient buildHttpClient(boolean isMultiThread) {
  151.  
  152. CloseableHttpClient client;
  153.  
  154. if (isMultiThread)
  155. client = HttpClientBuilder
  156. .create()
  157. .setConnectionManager(
  158. new PoolingHttpClientConnectionManager()).build();
  159. else
  160. client = HttpClientBuilder.create().build();
  161. // 设置代理server地址和端口
  162. // client.getHostConfiguration().setProxy("proxy_host_addr",proxy_port);
  163. return client;
  164. }
  165.  
  166. /**
  167. * 构建httpPost对象
  168. *
  169. * @param url
  170. * @param headers
  171. * @return
  172. * @throws UnsupportedEncodingException
  173. * @throws URISyntaxException
  174. */
  175. public static HttpPost buildHttpPost(String url, Map<String, String> params)
  176. throws UnsupportedEncodingException, URISyntaxException {
  177. Assert.notNull(url, "构建HttpPost时,url不能为null");
  178. HttpPost post = new HttpPost(url);
  179. setCommonHttpMethod(post);
  180. HttpEntity he = null;
  181. if (params != null) {
  182. List<NameValuePair> formparams = new ArrayList<NameValuePair>();
  183. for (String key : params.keySet()) {
  184. formparams.add(new BasicNameValuePair(key, params.get(key)));
  185. }
  186. he = new UrlEncodedFormEntity(formparams, GBK);
  187. post.setEntity(he);
  188. }
  189. // 在RequestContent.process中会自己主动写入消息体的长度,自己不用写入。写入反而检測报错
  190. // setContentLength(post, he);
  191. return post;
  192.  
  193. }
  194.  
  195. /**
  196. * 构建httpGet对象
  197. *
  198. * @param url
  199. * @param headers
  200. * @return
  201. * @throws URISyntaxException
  202. */
  203. public static HttpGet buildHttpGet(String url, Map<String, String> params)
  204. throws URISyntaxException {
  205. Assert.notNull(url, "构建HttpGet时,url不能为null");
  206. HttpGet get = new HttpGet(buildGetUrl(url, params));
  207. return get;
  208. }
  209.  
  210. /**
  211. * build getUrl str
  212. *
  213. * @param url
  214. * @param params
  215. * @return
  216. */
  217. private static String buildGetUrl(String url, Map<String, String> params) {
  218. StringBuffer uriStr = new StringBuffer(url);
  219. if (params != null) {
  220. List<NameValuePair> ps = new ArrayList<NameValuePair>();
  221. for (String key : params.keySet()) {
  222. ps.add(new BasicNameValuePair(key, params.get(key)));
  223. }
  224. uriStr.append("?");
  225. uriStr.append(URLEncodedUtils.format(ps, UTF_8));
  226. }
  227. return uriStr.toString();
  228. }
  229.  
  230. /**
  231. * 设置HttpMethod通用配置
  232. *
  233. * @param httpMethod
  234. */
  235. public static void setCommonHttpMethod(HttpRequestBase httpMethod) {
  236. httpMethod.setHeader(HTTP.CONTENT_ENCODING, CONTENT_CHARSET);// setting
  237. // contextCoding
  238. // httpMethod.setHeader(HTTP.CHARSET_PARAM, CONTENT_CHARSET);
  239. // httpMethod.setHeader(HTTP.CONTENT_TYPE, CONTENT_TYPE_JSON_CHARSET);
  240. // httpMethod.setHeader(HTTP.CONTENT_TYPE, CONTENT_TYPE_XML_CHARSET);
  241. }
  242.  
  243. /**
  244. * 设置成消息体的长度 setting MessageBody length
  245. *
  246. * @param httpMethod
  247. * @param he
  248. */
  249. public static void setContentLength(HttpRequestBase httpMethod,
  250. HttpEntity he) {
  251. if (he == null) {
  252. return;
  253. }
  254. httpMethod.setHeader(HTTP.CONTENT_LEN, String.valueOf(he.getContentLength()));
  255. }
  256.  
  257. /**
  258. * 构建公用RequestConfig
  259. *
  260. * @return
  261. */
  262. public static RequestConfig buildRequestConfig() {
  263. // 设置请求和传输超时时间
  264. RequestConfig requestConfig = RequestConfig.custom()
  265. .setSocketTimeout(SO_TIMEOUT_MS)
  266. .setConnectTimeout(CONNECTION_TIMEOUT_MS).build();
  267. return requestConfig;
  268. }
  269.  
  270. /**
  271. * 强验证必须是200状态否则报异常
  272. * @param res
  273. * @throws HttpException
  274. */
  275. static void assertStatus(HttpResponse res) throws IOException{
  276. Assert.notNull(res, "http响应对象为null");
  277. Assert.notNull(res.getStatusLine(), "http响应对象的状态为null");
  278. switch (res.getStatusLine().getStatusCode()) {
  279. case HttpStatus.SC_OK:
  280. // case HttpStatus.SC_CREATED:
  281. // case HttpStatus.SC_ACCEPTED:
  282. // case HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION:
  283. // case HttpStatus.SC_NO_CONTENT:
  284. // case HttpStatus.SC_RESET_CONTENT:
  285. // case HttpStatus.SC_PARTIAL_CONTENT:
  286. // case HttpStatus.SC_MULTI_STATUS:
  287. break;
  288. default:
  289. throw new IOException("server响应状态异常,失败.");
  290. }
  291. }
  292. private HttpClientUtils() {
  293. }
  294. public static void main(String[] args) throws ClientProtocolException, IOException, URISyntaxException {
  295. System.out.println(simpleGetInvoke("http://www.baidu.com", new HashMap<String, String>()));
  296. }
  297. }

httpclient4.3 工具类的更多相关文章

  1. 基于HttpClient4.5.1实现Http访问工具类

    本工具类基于httpclient4.5.1实现 <dependency> <groupId>org.apache.httpcomponents</groupId> ...

  2. HttpClient4.5 SSL访问工具类

    要从网上找一个HttpClient SSL访问工具类太难了,原因是HttpClient版本太多了,稍有差别就不能用,最后笔者干脆自己封装了一个访问HTTPS并绕过证书工具类. 主要是基于新版本Http ...

  3. 基于HttpClient4.5.2实现的HttpClient工具类

    1.maven依赖: <dependency> <groupId>org.apache.commons</groupId> <artifactId>co ...

  4. java http工具类和HttpUrlConnection上传文件分析

    利用java中的HttpUrlConnection上传文件,我们其实只要知道Http协议上传文件的标准格式.那么就可以用任何一门语言来模拟浏览器上传文件.下面有几篇文章从http协议入手介绍了java ...

  5. 验证工具类 - ValidateUtils.java

    验证工具类,提供验证email格式.是否ipv4.是否ipv6.是否中文.是否数字.正则表达式验证的方法. 源码如下:(点击下载 - ValidateUtils.java .commons-lang- ...

  6. Jsoup请求http或https返回json字符串工具类

    Jsoup请求http或https返回json字符串工具类 所需要的jar包如下: jsoup-1.8.1.jar 依赖jar包如下: httpclient-4.5.4.jar; httpclient ...

  7. 小D课堂-SpringBoot 2.x微信支付在线教育网站项目实战_5-5.HttpClient4.x工具获取使用

    笔记 5.HttpClient4.x工具获取使用     简介:讲解httpClient4.x相关依赖,并封装基本方法. 1.加入依赖         <dependency>       ...

  8. Java基础Map接口+Collections工具类

    1.Map中我们主要讲两个接口 HashMap  与   LinkedHashMap (1)其中LinkedHashMap是有序的  怎么存怎么取出来 我们讲一下Map的增删改查功能: /* * Ma ...

  9. Android—关于自定义对话框的工具类

    开发中有很多地方会用到自定义对话框,为了避免不必要的城府代码,在此总结出一个工具类. 弹出对话框的地方很多,但是都大同小异,不同无非就是提示内容或者图片不同,下面这个类是将提示内容和图片放到了自定义函 ...

随机推荐

  1. System.Drawing.Design.UITypeEditor自定义控件属性GetEditStyle(ITypeDescriptorContext context),EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.C ...

  2. poj2014 不带修改区间第k大树

    主席树 又称函数式线段树,又称可持久化线段树……缺点是内存有点儿大…… type node1=record l,r,sum:longint; end; node2=record x,idx:longi ...

  3. WinCE发展史

    Windows CE概述 WindowsCE是微软公司嵌入式.移动计算平台的基础,它是一个开放的.可升级的32位嵌入式操作系统,是基于掌上型电脑类的电子设备操作系统,它是精简的Windows 95,W ...

  4. 【spring-boot】快速构建spring-boot微框架

    spring-boot是一个快速构建环境的一套框架,其设计理念是尽可能的减少xml的配置,用来简化新Spring应用的初始搭建以及开发过程.该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义 ...

  5. OA,ERP等源码一部分演示

    更多源码http://www.pssdss.com QQ:11851298 功能强大的JAVA开发的ERP源码http://cx050027.pssdss.com:8080/   用户名pssdss  ...

  6. iOS开发中提交带有中文或特殊字符串的参数

    iOS开发中,与后台进行数据交换是一个很常见的场景. 在web开发中,对于我们提交的地址,浏览器会负责进行decode,但是在ios中,必须要自己手动来实现.否则我们拼接出的网址在包括中文.特殊字符串 ...

  7. java中的final关键字

    谈到final关键字,想必很多人都不陌生,在使用匿名内部类的时候可能会经常用到final关键字.另外,Java中的String类就是一个final类,那么今天我们就来了解final这个关键字的用法.下 ...

  8. order by优化--Order By实现原理分析和Filesort优化

    在MySQL中的ORDER BY有两种排序实现方式: 1.利用有序索引获取有序数据 2.文件排序 在使用explain分析查询的时候,利用有序索引获取有序数据显示Using index.而文件排序显示 ...

  9. Mac下安装Mysql出现 Can’t connect to local MySQL server through socket '/tmp/mysql.sock'

    在Mac下安装mysql出现 Can't connect to local MySQL server through socket '/tmp/mysql.sock' 错误,解决如下: $ unset ...

  10. 第二个App“今日美文”上架【原】

    App store 下载地址 开发这个App的本意 之前偶然找到一个叫<每日一文>的应用,正是我一直想找的,优点如下: 界面够简单 推荐的文章也很好,而且都不太长 每天都不一样 但是用起来 ...