httpclient4.3.6

  1. package org.caeit.cloud.dev.util;
  2.  
  3. import java.io.File;
  4. import java.io.IOException;
  5. import java.io.UnsupportedEncodingException;
  6. import java.nio.charset.Charset;
  7. import java.util.ArrayList;
  8. import java.util.List;
  9. import java.util.Map;
  10. import java.util.Set;
  11.  
  12. import org.apache.http.HttpEntity;
  13. import org.apache.http.NameValuePair;
  14. import org.apache.http.client.entity.UrlEncodedFormEntity;
  15. import org.apache.http.client.methods.CloseableHttpResponse;
  16. import org.apache.http.client.methods.HttpDelete;
  17. import org.apache.http.client.methods.HttpGet;
  18. import org.apache.http.client.methods.HttpPost;
  19. import org.apache.http.client.methods.HttpPut;
  20. import org.apache.http.entity.ContentType;
  21. import org.apache.http.entity.StringEntity;
  22. import org.apache.http.entity.mime.HttpMultipartMode;
  23. import org.apache.http.entity.mime.MultipartEntityBuilder;
  24. import org.apache.http.impl.client.CloseableHttpClient;
  25. import org.apache.http.impl.client.HttpClientBuilder;
  26. import org.apache.http.impl.client.HttpClients;
  27. import org.apache.http.message.BasicNameValuePair;
  28. import org.apache.http.util.EntityUtils;
  29. import org.caeit.cloud.dev.entity.HttpResponse; // no use
  30.  
  31. public class HttpClientUtil {
  32.  
  33. /**
  34. * 发送http get请求
  35. */
  36. public static HttpResponse httpGet(String url,Map<String,String> headers,String encode){
  37. HttpResponse response = new HttpResponse();
  38. if(encode == null){
  39. encode = "utf-8";
  40. }
  41. String content = null;
  42. //since 4.3 不再使用 DefaultHttpClient
  43. CloseableHttpClient closeableHttpClient = HttpClientBuilder.create().build();
  44. HttpGet httpGet = new HttpGet(url);
  45. //设置header
  46. if (headers != null && headers.size() > 0) {
  47. for (Map.Entry<String, String> entry : headers.entrySet()) {
  48. httpGet.setHeader(entry.getKey(),entry.getValue());
  49. }
  50. }
  51. CloseableHttpResponse httpResponse = null;
  52. try {
  53. httpResponse = closeableHttpClient.execute(httpGet);
  54. HttpEntity entity = httpResponse.getEntity();
  55. content = EntityUtils.toString(entity, encode);
  56. response.setBody(content);
  57. response.setHeaders(httpResponse.getAllHeaders());
  58. response.setReasonPhrase(httpResponse.getStatusLine().getReasonPhrase());
  59. response.setStatusCode(httpResponse.getStatusLine().getStatusCode());
  60. } catch (Exception e) {
  61. e.printStackTrace();
  62. }finally{
  63. try {
  64. httpResponse.close();
  65. } catch (IOException e) {
  66. e.printStackTrace();
  67. }
  68. }
  69. try { //关闭连接、释放资源
  70. closeableHttpClient.close();
  71. } catch (IOException e) {
  72. e.printStackTrace();
  73. }
  74. return response;
  75. }
  76. /**
  77. * 发送 http post 请求,参数以form表单键值对的形式提交。
  78. */
  79. public static HttpResponse httpPostForm(String url,Map<String,String> params, Map<String,String> headers,String encode){
  80. HttpResponse response = new HttpResponse();
  81. if(encode == null){
  82. encode = "utf-8";
  83. }
  84. //HttpClients.createDefault()等价于 HttpClientBuilder.create().build();
  85. CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
  86. HttpPost httpost = new HttpPost(url);
  87.  
  88. //设置header
  89. if (headers != null && headers.size() > 0) {
  90. for (Map.Entry<String, String> entry : headers.entrySet()) {
  91. httpost.setHeader(entry.getKey(),entry.getValue());
  92. }
  93. }
  94. //组织请求参数
  95. List<NameValuePair> paramList = new ArrayList <NameValuePair>();
  96. if(params != null && params.size() > 0){
  97. Set<String> keySet = params.keySet();
  98. for(String key : keySet) {
  99. paramList.add(new BasicNameValuePair(key, params.get(key)));
  100. }
  101. }
  102. try {
  103. httpost.setEntity(new UrlEncodedFormEntity(paramList, encode));
  104. } catch (UnsupportedEncodingException e1) {
  105. e1.printStackTrace();
  106. }
  107. String content = null;
  108. CloseableHttpResponse httpResponse = null;
  109. try {
  110. httpResponse = closeableHttpClient.execute(httpost);
  111. HttpEntity entity = httpResponse.getEntity();
  112. content = EntityUtils.toString(entity, encode);
  113. response.setBody(content);
  114. response.setHeaders(httpResponse.getAllHeaders());
  115. response.setReasonPhrase(httpResponse.getStatusLine().getReasonPhrase());
  116. response.setStatusCode(httpResponse.getStatusLine().getStatusCode());
  117. } catch (Exception e) {
  118. e.printStackTrace();
  119. }finally{
  120. try {
  121. httpResponse.close();
  122. } catch (IOException e) {
  123. e.printStackTrace();
  124. }
  125. }
  126. try { //关闭连接、释放资源
  127. closeableHttpClient.close();
  128. } catch (IOException e) {
  129. e.printStackTrace();
  130. }
  131. return response;
  132. }
  133.  
  134. /**
  135. * 发送 http post 请求,参数以原生字符串进行提交
  136. * @param url
  137. * @param encode
  138. * @return
  139. */
  140. public static HttpResponse httpPostRaw(String url,String stringJson,Map<String,String> headers, String encode){
  141. HttpResponse response = new HttpResponse();
  142. if(encode == null){
  143. encode = "utf-8";
  144. }
  145. //HttpClients.createDefault()等价于 HttpClientBuilder.create().build();
  146. CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
  147. HttpPost httpost = new HttpPost(url);
  148.  
  149. //设置header
  150. httpost.setHeader("Content-type", "application/json");
  151. if (headers != null && headers.size() > 0) {
  152. for (Map.Entry<String, String> entry : headers.entrySet()) {
  153. httpost.setHeader(entry.getKey(),entry.getValue());
  154. }
  155. }
  156. //组织请求参数
  157. StringEntity stringEntity = new StringEntity(stringJson, encode);
  158. httpost.setEntity(stringEntity);
  159. String content = null;
  160. CloseableHttpResponse httpResponse = null;
  161. try {
  162. //响应信息
  163. httpResponse = closeableHttpClient.execute(httpost);
  164. HttpEntity entity = httpResponse.getEntity();
  165. content = EntityUtils.toString(entity, encode);
  166. response.setBody(content);
  167. response.setHeaders(httpResponse.getAllHeaders());
  168. response.setReasonPhrase(httpResponse.getStatusLine().getReasonPhrase());
  169. response.setStatusCode(httpResponse.getStatusLine().getStatusCode());
  170. } catch (Exception e) {
  171. e.printStackTrace();
  172. }finally{
  173. try {
  174. httpResponse.close();
  175. } catch (IOException e) {
  176. e.printStackTrace();
  177. }
  178. }
  179. try { //关闭连接、释放资源
  180. closeableHttpClient.close();
  181. } catch (IOException e) {
  182. e.printStackTrace();
  183. }
  184. return response;
  185. }
  186.  
  187. /**
  188. * 发送 http put 请求,参数以原生字符串进行提交
  189. * @param url
  190. * @param encode
  191. * @return
  192. */
  193. public static HttpResponse httpPutRaw(String url,String stringJson,Map<String,String> headers, String encode){
  194. HttpResponse response = new HttpResponse();
  195. if(encode == null){
  196. encode = "utf-8";
  197. }
  198. //HttpClients.createDefault()等价于 HttpClientBuilder.create().build();
  199. CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
  200. HttpPut httpput = new HttpPut(url);
  201.  
  202. //设置header
  203. httpput.setHeader("Content-type", "application/json");
  204. if (headers != null && headers.size() > 0) {
  205. for (Map.Entry<String, String> entry : headers.entrySet()) {
  206. httpput.setHeader(entry.getKey(),entry.getValue());
  207. }
  208. }
  209. //组织请求参数
  210. StringEntity stringEntity = new StringEntity(stringJson, encode);
  211. httpput.setEntity(stringEntity);
  212. String content = null;
  213. CloseableHttpResponse httpResponse = null;
  214. try {
  215. //响应信息
  216. httpResponse = closeableHttpClient.execute(httpput);
  217. HttpEntity entity = httpResponse.getEntity();
  218. content = EntityUtils.toString(entity, encode);
  219. response.setBody(content);
  220. response.setHeaders(httpResponse.getAllHeaders());
  221. response.setReasonPhrase(httpResponse.getStatusLine().getReasonPhrase());
  222. response.setStatusCode(httpResponse.getStatusLine().getStatusCode());
  223. } catch (Exception e) {
  224. e.printStackTrace();
  225. }finally{
  226. try {
  227. httpResponse.close();
  228. } catch (IOException e) {
  229. e.printStackTrace();
  230. }
  231. }
  232. try {
  233. closeableHttpClient.close(); //关闭连接、释放资源
  234. } catch (IOException e) {
  235. e.printStackTrace();
  236. }
  237. return response;
  238. }
  239. /**
  240. * 发送http delete请求
  241. */
  242. public static HttpResponse httpDelete(String url,Map<String,String> headers,String encode){
  243. HttpResponse response = new HttpResponse();
  244. if(encode == null){
  245. encode = "utf-8";
  246. }
  247. String content = null;
  248. //since 4.3 不再使用 DefaultHttpClient
  249. CloseableHttpClient closeableHttpClient = HttpClientBuilder.create().build();
  250. HttpDelete httpdelete = new HttpDelete(url);
  251. //设置header
  252. if (headers != null && headers.size() > 0) {
  253. for (Map.Entry<String, String> entry : headers.entrySet()) {
  254. httpdelete.setHeader(entry.getKey(),entry.getValue());
  255. }
  256. }
  257. CloseableHttpResponse httpResponse = null;
  258. try {
  259. httpResponse = closeableHttpClient.execute(httpdelete);
  260. HttpEntity entity = httpResponse.getEntity();
  261. content = EntityUtils.toString(entity, encode);
  262. response.setBody(content);
  263. response.setHeaders(httpResponse.getAllHeaders());
  264. response.setReasonPhrase(httpResponse.getStatusLine().getReasonPhrase());
  265. response.setStatusCode(httpResponse.getStatusLine().getStatusCode());
  266. } catch (Exception e) {
  267. e.printStackTrace();
  268. }finally{
  269. try {
  270. httpResponse.close();
  271. } catch (IOException e) {
  272. e.printStackTrace();
  273. }
  274. }
  275. try { //关闭连接、释放资源
  276. closeableHttpClient.close();
  277. } catch (IOException e) {
  278. e.printStackTrace();
  279. }
  280. return response;
  281. }
  282.  
  283. /**
  284. * 发送 http post 请求,支持文件上传
  285. */
  286. public static HttpResponse httpPostFormMultipart(String url,Map<String,String> params, List<File> files,Map<String,String> headers,String encode){
  287. HttpResponse response = new HttpResponse();
  288. if(encode == null){
  289. encode = "utf-8";
  290. }
  291. CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
  292. HttpPost httpost = new HttpPost(url);
  293.  
  294. //设置header
  295. if (headers != null && headers.size() > 0) {
  296. for (Map.Entry<String, String> entry : headers.entrySet()) {
  297. httpost.setHeader(entry.getKey(),entry.getValue());
  298. }
  299. }
  300. MultipartEntityBuilder mEntityBuilder = MultipartEntityBuilder.create();
  301. mEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
  302. mEntityBuilder.setCharset(Charset.forName(encode));
  303.  
  304. // 普通参数
  305. ContentType contentType = ContentType.create("text/plain",Charset.forName(encode));//解决中文乱码
  306. if (params != null && params.size() > 0) {
  307. Set<String> keySet = params.keySet();
  308. for (String key : keySet) {
  309. mEntityBuilder.addTextBody(key, params.get(key),contentType);
  310. }
  311. }
  312. //二进制参数
  313. if (files != null && files.size() > 0) {
  314. for (File file : files) {
  315. mEntityBuilder.addBinaryBody("file", file);
  316. }
  317. }
  318. httpost.setEntity(mEntityBuilder.build());
  319. String content = null;
  320. CloseableHttpResponse httpResponse = null;
  321. try {
  322. httpResponse = closeableHttpClient.execute(httpost);
  323. HttpEntity entity = httpResponse.getEntity();
  324. content = EntityUtils.toString(entity, encode);
  325. response.setBody(content);
  326. response.setHeaders(httpResponse.getAllHeaders());
  327. response.setReasonPhrase(httpResponse.getStatusLine().getReasonPhrase());
  328. response.setStatusCode(httpResponse.getStatusLine().getStatusCode());
  329. } catch (Exception e) {
  330. e.printStackTrace();
  331. }finally{
  332. try {
  333. httpResponse.close();
  334. } catch (IOException e) {
  335. e.printStackTrace();
  336. }
  337. }
  338. try { //关闭连接、释放资源
  339. closeableHttpClient.close();
  340. } catch (IOException e) {
  341. e.printStackTrace();
  342. }
  343. return response;
  344. }
  345.  
  346. }

发送Get请求:

HttpResponse httpGet(String url,Map<String,String> headers,String encode)

发送Post请求,同表单Post提交

HttpResponse httpPostForm(String url,Map<String,String> params, Map<String,String> headers,String encode)

发送Post Raw请求

HttpResponse httpPostRaw(String url,String stringJson,Map<String,String> headers, String encode)

发送Put Raw请求

HttpResponse httpPutRaw(String url,String stringJson,Map<String,String> headers, String encode)

发送Delete请求

HttpResponse httpDelete(String url,Map<String,String> headers,String encode)

说明:

1、since 4.3 不再使用 DefaultHttpClient

2、UrlEncodedFormEntity 与 StringEntity 区别

2.1、UrlEncodedFormEntity()的形式比较单一,只能是普通的键值对,局限性相对较大。

2.2、而StringEntity()的形式比较自由,只要是字符串放进去,不论格式都可以。

3、以raw方式发送请求时,需指定 Content type:httpost.setHeader("Content-type", "application/json");  否则默认使用 Content type 'text/plain;charset=UTF-8'。

原文地址:http://huangqiqing123.iteye.com/blog/2344680

使用HttpClient 发送 GET、POST(FormData、Raw)、PUT、Delete请求及文件上传的更多相关文章

  1. 使用HttpClient 发送 GET、POST、PUT、Delete请求及文件上传

    package org.caeit.cloud.dev.util; import java.io.File; import java.io.IOException; import java.io.Un ...

  2. 【H5】-- FormData用法介绍以及实现图片/文件上传--【XUEBIG】

      一.概述 FormData 对象的使用: 1.用一些键值对来模拟一系列表单控件:即把form中所有表单元素的name与value组装成一个queryString 2. 异步上传二进制文件. 二.使 ...

  3. SpringCloud 之 Fegin —— 发送GET、POST请求以及文件上传

    由于项目需要调用其他微服务的数据,首先想到的就是写一个http网络请求的工具类,但是想到在之前看springCloud的时候里面有这个Fegin可以实现,就顺便实践一下,虽然过程有点坎坷,好在都顺利解 ...

  4. multipart/form-data请求与文件上传

    要上传文件,需要用post方法,并且设置enctype为multipart/form-data. <form action="/upload" method="po ...

  5. multipart/form-data请求与文件上传的细节

    <!DOCTYPE html><html><head lang="en">  <meta charset="UTF-8" ...

  6. python 全栈开发,Day75(Django与Ajax,文件上传,ajax发送json数据,基于Ajax的文件上传,SweetAlert插件)

    昨日内容回顾 基于对象的跨表查询 正向查询:关联属性在A表中,所以A对象找关联B表数据,正向查询 反向查询:关联属性在A表中,所以B对象找A对象,反向查询 一对多: 按字段:xx book ----- ...

  7. Django与Ajax,文件上传,ajax发送json数据,基于Ajax的文件上传,SweetAlert插件

    一.Django与Ajax AJAX准备知识:JSON 什么是 JSON ? JSON 指的是 JavaScript 对象表示法(JavaScript Object Notation) JSON 是轻 ...

  8. Multipart/form-data POST文件上传详解

    Multipart/form-data POST文件上传详解 理论 简单的HTTP POST 大家通过HTTP向服务器发送POST请求提交数据,都是通过form表单提交的,代码如下: <form ...

  9. Multipart/form-data POST文件上传详解(转)

    Multipart/form-data POST文件上传详解 理论 简单的HTTP POST 大家通过HTTP向服务器发送POST请求提交数据,都是通过form表单提交的,代码如下: <form ...

随机推荐

  1. bzoj3622已经没有什么好害怕的了

    bzoj3622已经没有什么好害怕的了 题意: 给n个数Ai,n个数Bi,将Ai中的数与Bi中的数配对,求配对Ai比Bi大的比Bi比Ai大的恰好有k组的方案数.n,k≤2000 题解: 蒟蒻太弱了只能 ...

  2. 证明:ThreadLocal的get,set方法无法防止内存泄漏

    先给出结论:get,set两个方法都不能完全防止内存泄漏,还是每次用完ThreadLocal都勤奋的remove一下靠谱. 前言:   看到有的博客说在把ThreadLocal的所有强引用置空前,调用 ...

  3. ant-design-vue中实现modal模态框的复用(添加,编辑展示同一个模态框)

    用两个button(添加,编辑)按钮展示同一个模态框,并不是什么大问题,问题在于解决这两个模态框得有自己的确定和取消方法 父页面完全接管子页面(利于子页面复用) 父页面代码: <template ...

  4. 软件测试工程师入门——Linux【使用说明书】

    先来说一下linux是什么? linux 是一个开源.免费的操作系统,其稳定性.安全性.处理多并发已经得到业界的认可,目前很多中性,大型甚至是巨型项目都在使用linux. linux 内核:redha ...

  5. try-catch- finally块中, finally块唯一不执行的情况是什么?

    除非在try块或者catch块中调用了退出虚拟机的方法(即System.exit(1);),否则不管在try块.catch块中执行怎样的代码,出现怎样的情况,异常处理的finally块总是会被执行的 ...

  6. Java顺序查找、二分查找

    Java顺序查找.二分查找   查找算法中顺序查找算是最简单的了,无论是有序的还是无序的都可以,只需要一个个对比即可,但其实效率很低. 顺序查找 动图演示 详细代码 // 顺序查找 public st ...

  7. Zabbix4.x如何安全传输数据

    由于设备都在混合云,所以不少数据传输是通过公网,这样极大的增加了危险性,所以在Zabbix数据传输这块则进行PSK安全认证,由proxy主动收集agent数据后统一发送给server,这样只需要对pr ...

  8. wpf文字模糊

    wpf如果使用了DropShadowEffect,会导致文字模糊,可以在window上设置 this.UseLayoutRounding = true;解决此问题

  9. Spring bean初始化

  10. web自动化 -- HTMLreport(三)测试报告输出log日志

    一.需求痛点 1.HTMLreport没法看到log日志,经过封装的框架不可能走一步就print() 2. 希望可以在HTMLreport中输出log日志 3.痛点截图 二.解决办法 1.既然是HTM ...