1. /**
  2. * 发送post请求
  3. * @param url 路径
  4. * @param jsonObject 参数(json类型)
  5. * @param encoding 编码格式
  6. * @return
  7. * @throws ParseException
  8. * @throws IOException
  9. */
  10. public static String send(String url, JSONObject jsonObject,String encoding) throws ParseException, IOException{
  11. String body = "";
  12.  
  13. //创建httpclient对象
  14. CloseableHttpClient client = HttpClients.createDefault();
  15. //创建post方式请求对象
  16. HttpPost httpPost = new HttpPost(url);
  17.  
  18. //装填参数
  19. StringEntity s = new StringEntity(jsonObject.toString(), "utf-8");
  20. s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
  21. "application/json"));
  22. //设置参数到请求对象中
  23. httpPost.setEntity(s);
  24. System.out.println("请求地址:"+url);
  25. // System.out.println("请求参数:"+nvps.toString());
  26.  
  27. //设置header信息
  28. //指定报文头【Content-type】、【User-Agent】
  29. // httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
  30. httpPost.setHeader("Content-type", "application/json");
  31. httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
  32.  
  33. //执行请求操作,并拿到结果(同步阻塞)
  34. CloseableHttpResponse response = client.execute(httpPost);
  35. //获取结果实体
  36. HttpEntity entity = response.getEntity();
  37. if (entity != null) {
  38. //按指定编码转换结果实体为String类型
  39. body = EntityUtils.toString(entity, encoding);
  40. }
  41. EntityUtils.consume(entity);
  42. //释放链接
  43. response.close();
  44. return body;
  45. }

  下面代码自己写。

2019/11/18,看到代码挺多人看的,再给大家提供一个Http工具类,数据提交包括 Raw,Json等

  1. package com.xiaojiang.checkin.utils;
  2.  
  3. import com.alibaba.fastjson.JSONObject;
  4. import com.xiaojiang.checkin.entity.HttpClientResult;
  5. import org.apache.http.HttpStatus;
  6. import org.apache.http.NameValuePair;
  7. import org.apache.http.client.config.RequestConfig;
  8. import org.apache.http.client.entity.UrlEncodedFormEntity;
  9. import org.apache.http.client.methods.*;
  10. import org.apache.http.client.utils.URIBuilder;
  11. import org.apache.http.entity.StringEntity;
  12. import org.apache.http.impl.client.CloseableHttpClient;
  13. import org.apache.http.impl.client.HttpClients;
  14. import org.apache.http.message.BasicNameValuePair;
  15. import org.apache.http.util.EntityUtils;
  16.  
  17. import java.io.IOException;
  18. import java.io.UnsupportedEncodingException;
  19. import java.nio.charset.Charset;
  20. import java.util.*;
  21.  
  22. /**
  23. * Description: httpClient工具类
  24. *
  25. * @author JourWon
  26. * @date Created on 2018年4月19日
  27. */
  28. public class HttpClientUtils {
  29.  
  30. // 编码格式。发送编码格式统一用UTF-8
  31. private static final String ENCODING = "UTF-8";
  32.  
  33. // 设置连接超时时间,单位毫秒。
  34. private static final int CONNECT_TIMEOUT = 6000;
  35.  
  36. // 请求获取数据的超时时间(即响应时间),单位毫秒。
  37. private static final int SOCKET_TIMEOUT = 6000;
  38.  
  39. /**
  40. * 发送get请求;不带请求头和请求参数
  41. *
  42. * @param url 请求地址
  43. * @return
  44. * @throws Exception
  45. */
  46. public static HttpClientResult doGet(String url) throws Exception {
  47. return doGet(url, null, null);
  48. }
  49.  
  50. /**
  51. * 发送get请求;带请求参数
  52. *
  53. * @param url 请求地址
  54. * @param params 请求参数集合
  55. * @return
  56. * @throws Exception
  57. */
  58. public static HttpClientResult doGet(String url, Map<String, String> params) throws Exception {
  59. return doGet(url, null, params);
  60. }
  61.  
  62. /**
  63. * 发送get请求;带请求头和请求参数
  64. *
  65. * @param url 请求地址
  66. * @param headers 请求头集合
  67. * @param params 请求参数集合
  68. * @return
  69. * @throws Exception
  70. */
  71. public static HttpClientResult doGet(String url, Map<String, String> headers, Map<String, String> params) throws Exception {
  72. // 创建httpClient对象
  73. CloseableHttpClient httpClient = HttpClients.createDefault();
  74.  
  75. // 创建访问的地址
  76. URIBuilder uriBuilder = new URIBuilder(url);
  77. if (params != null) {
  78. Set<Map.Entry<String, String>> entrySet = params.entrySet();
  79. for (Map.Entry<String, String> entry : entrySet) {
  80. uriBuilder.setParameter(entry.getKey(), entry.getValue());
  81. }
  82. }
  83.  
  84. // 创建http对象
  85. HttpGet httpGet = new HttpGet(uriBuilder.build());
  86. /**
  87. * setConnectTimeout:设置连接超时时间,单位毫秒。
  88. * setConnectionRequestTimeout:设置从connect Manager(连接池)获取Connection
  89. * 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。
  90. * setSocketTimeout:请求获取数据的超时时间(即响应时间),单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
  91. */
  92. RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
  93. httpGet.setConfig(requestConfig);
  94.  
  95. // 设置请求头
  96. packageHeader(headers, httpGet);
  97.  
  98. // 创建httpResponse对象
  99. CloseableHttpResponse httpResponse = null;
  100.  
  101. try {
  102. // 执行请求并获得响应结果
  103. return getHttpClientResult(httpResponse, httpClient, httpGet);
  104. } finally {
  105. // 释放资源
  106. release(httpResponse, httpClient);
  107. }
  108. }
  109.  
  110. /**
  111. * 发送post请求;不带请求头和请求参数
  112. *
  113. * @param url 请求地址
  114. * @return
  115. * @throws Exception
  116. */
  117. public static HttpClientResult doPost(String url) throws Exception {
  118. return doPost(url, null, null);
  119. }
  120.  
  121. /**
  122. * 发送post请求;带请求参数
  123. *
  124. * @param url 请求地址
  125. * @param params 参数集合
  126. * @return
  127. * @throws Exception
  128. */
  129. public static HttpClientResult doPost(String url, Map<String, String> params) throws Exception {
  130. return doPost(url, null, params);
  131. }
  132.  
  133. /**
  134. * 发送post请求;带请求头和请求参数
  135. *可发送Formdata数据,请把请求头设置一下,不然获取不到数据。
  136. * @param url 请求地址
  137. * @param headers 请求头集合
  138. * @param params 请求参数集合
  139. * @return
  140. * @throws Exception
  141. */
  142. public static HttpClientResult doPost(String url, Map<String, String> headers, Map<String, String> params) throws Exception {
  143. // 创建httpClient对象
  144. CloseableHttpClient httpClient = HttpClients.createDefault();
  145.  
  146. // 创建http对象
  147. HttpPost httpPost = new HttpPost(url);
  148. /**
  149. * setConnectTimeout:设置连接超时时间,单位毫秒。
  150. * setConnectionRequestTimeout:设置从connect Manager(连接池)获取Connection
  151. * 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。
  152. * setSocketTimeout:请求获取数据的超时时间(即响应时间),单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
  153. */
  154. RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
  155. httpPost.setConfig(requestConfig);
  156. // 设置请求头
  157. /*httpPost.setHeader("Cookie", "");
  158. httpPost.setHeader("Connection", "keep-alive");
  159. httpPost.setHeader("Accept", "application/json");
  160. httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.9");
  161. httpPost.setHeader("Accept-Encoding", "gzip, deflate, br");
  162. httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36");*/
  163. packageHeader(headers, httpPost);
  164.  
  165. // 封装请求参数
  166. packageParam(params, httpPost);
  167.  
  168. // 创建httpResponse对象
  169. CloseableHttpResponse httpResponse = null;
  170.  
  171. try {
  172. // 执行请求并获得响应结果
  173. return getHttpClientResult(httpResponse, httpClient, httpPost);
  174. } finally {
  175. // 释放资源
  176. release(httpResponse, httpClient);
  177. }
  178. }
  179.  
  180. /***
  181. * 发送post请求封装formdata
  182. *
  183. */
  184.  
  185. // public static HttpClientResult doPost(String url, Map<String, String> headers, Map<String, String> params){
  186. //
  187. // }
  188.  
  189. /**
  190. * 发送POST请求带Raw参数
  191. * */
  192. public static HttpClientResult doPost(String url, Map<String, String> headers, Map<String, String> params,String raw) throws Exception {
  193. // 创建httpClient对象
  194. CloseableHttpClient httpClient = HttpClients.createDefault();
  195.  
  196. // 创建http对象
  197. HttpPost httpPost = new HttpPost(url);
  198. //封装raw 参数
  199. packageRaw(raw,httpPost);
  200. /**
  201. * setConnectTimeout:设置连接超时时间,单位毫秒。
  202. * setConnectionRequestTimeout:设置从connect Manager(连接池)获取Connection
  203. * 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。
  204. * setSocketTimeout:请求获取数据的超时时间(即响应时间),单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
  205. */
  206. RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
  207. httpPost.setConfig(requestConfig);
  208. // 设置请求头
  209. /*httpPost.setHeader("Cookie", "");
  210. httpPost.setHeader("Connection", "keep-alive");
  211. httpPost.setHeader("Accept", "application/json");
  212. httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.9");
  213. httpPost.setHeader("Accept-Encoding", "gzip, deflate, br");
  214. httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36");*/
  215. packageHeader(headers, httpPost);
  216.  
  217. // 封装请求参数
  218. packageParam(params, httpPost);
  219.  
  220. // 创建httpResponse对象
  221. CloseableHttpResponse httpResponse = null;
  222.  
  223. try {
  224. // 执行请求并获得响应结果
  225. return getHttpClientResult(httpResponse, httpClient, httpPost);
  226. } finally {
  227. // 释放资源
  228. release(httpResponse, httpClient);
  229. }
  230. }
  231.  
  232. /***
  233. * 发送Post有些这封装代码
  234. * 封装formdata数据
  235. */
  236. public static void packageFormData(Map<String,String> params,HttpEntityEnclosingRequestBase HttpMethod){
  237. List<NameValuePair> paramList = new ArrayList <NameValuePair>();
  238. if(params != null && params.size() > 0){
  239. Set<String> keySet = params.keySet();
  240. for(String key : keySet) {
  241. paramList.add(new BasicNameValuePair(key, params.get(key)));
  242. }
  243. }
  244. HttpMethod.setEntity(new UrlEncodedFormEntity(paramList,Charset.forName("UTF-8")));
  245. System.out.println(paramList);
  246. }
  247.  
  248. /**
  249. * 封装Raw数据
  250. * */
  251. public static void packageRaw(String raw,HttpEntityEnclosingRequestBase HttpMethod){
  252. try {
  253. //传map进来需要自己封装key,val
  254. StringEntity postingString = new StringEntity(raw);// json传递
  255. HttpMethod.setEntity(postingString);
  256. } catch (UnsupportedEncodingException e) {
  257. e.printStackTrace();
  258. }
  259.  
  260. }
  261.  
  262. /**
  263. * 发送put请求;不带请求参数
  264. *
  265. * @param url 请求地址
  266. * @return
  267. * @throws Exception
  268. */
  269. public static HttpClientResult doPut(String url) throws Exception {
  270. return doPut(url);
  271. }
  272.  
  273. /**
  274. * 发送put请求;带请求参数
  275. *
  276. * @param url 请求地址
  277. * @param params 参数集合
  278. * @return
  279. * @throws Exception
  280. */
  281. public static HttpClientResult doPut(String url, Map<String, String> params) throws Exception {
  282. CloseableHttpClient httpClient = HttpClients.createDefault();
  283. HttpPut httpPut = new HttpPut(url);
  284. RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
  285. httpPut.setConfig(requestConfig);
  286.  
  287. packageParam(params, httpPut);
  288.  
  289. CloseableHttpResponse httpResponse = null;
  290.  
  291. try {
  292. return getHttpClientResult(httpResponse, httpClient, httpPut);
  293. } finally {
  294. release(httpResponse, httpClient);
  295. }
  296. }
  297.  
  298. /**
  299. * 发送delete请求;不带请求参数
  300. *
  301. * @param url 请求地址
  302. * @return
  303. * @throws Exception
  304. */
  305. public static HttpClientResult doDelete(String url) throws Exception {
  306. CloseableHttpClient httpClient = HttpClients.createDefault();
  307. HttpDelete httpDelete = new HttpDelete(url);
  308. RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
  309. httpDelete.setConfig(requestConfig);
  310.  
  311. CloseableHttpResponse httpResponse = null;
  312. try {
  313. return getHttpClientResult(httpResponse, httpClient, httpDelete);
  314. } finally {
  315. release(httpResponse, httpClient);
  316. }
  317. }
  318.  
  319. /**
  320. * 发送delete请求;带请求参数
  321. *
  322. * @param url 请求地址
  323. * @param params 参数集合
  324. * @return
  325. * @throws Exception
  326. */
  327. public static HttpClientResult doDelete(String url, Map<String, String> params) throws Exception {
  328. if (params == null) {
  329. params = new HashMap<String, String>();
  330. }
  331.  
  332. params.put("_method", "delete");
  333. return doPost(url, params);
  334. }
  335.  
  336. /**
  337. * Description: 封装请求头
  338. * @param params
  339. * @param httpMethod
  340. */
  341. public static void packageHeader(Map<String, String> params, HttpRequestBase httpMethod) {
  342. // 封装请求头
  343. if (params != null) {
  344. Set<Map.Entry<String, String>> entrySet = params.entrySet();
  345. for (Map.Entry<String, String> entry : entrySet) {
  346. // 设置到请求头到HttpRequestBase对象中
  347. httpMethod.setHeader(entry.getKey(), entry.getValue());
  348. }
  349. }
  350. }
  351.  
  352. /**
  353. * Description: 封装请求参数
  354. *
  355. * @param params
  356. * @param httpMethod
  357. * @throws UnsupportedEncodingException
  358. */
  359. public static void packageParam(Map<String, String> params, HttpEntityEnclosingRequestBase httpMethod)
  360. throws UnsupportedEncodingException {
  361. // 封装请求参数
  362. if (params != null) {
  363. List<NameValuePair> nvps = new ArrayList<NameValuePair>();
  364. Set<Map.Entry<String, String>> entrySet = params.entrySet();
  365. for (Map.Entry<String, String> entry : entrySet) {
  366. nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
  367. }
  368.  
  369. // 设置到请求的http对象中
  370. httpMethod.setEntity(new UrlEncodedFormEntity(nvps, ENCODING));
  371. }
  372. }
  373.  
  374. /**
  375. * Description: 获得响应结果
  376. *
  377. * @param httpResponse
  378. * @param httpClient
  379. * @param httpMethod
  380. * @return
  381. * @throws Exception
  382. */
  383. public static HttpClientResult getHttpClientResult(CloseableHttpResponse httpResponse,
  384. CloseableHttpClient httpClient, HttpRequestBase httpMethod) throws Exception {
  385. // 执行请求
  386. httpResponse = httpClient.execute(httpMethod);
  387. // 获取返回结果
  388. if (httpResponse != null && httpResponse.getStatusLine() != null) {
  389. String content = "";
  390. if (httpResponse.getEntity() != null) {
  391. content = EntityUtils.toString(httpResponse.getEntity(), ENCODING);
  392. }
  393. return new HttpClientResult(httpResponse.getStatusLine().getStatusCode(),content);
  394. }
  395. return new HttpClientResult(HttpStatus.SC_INTERNAL_SERVER_ERROR);
  396. }
  397.  
  398. /**
  399. * Description: 释放资源
  400. *
  401. * @param httpResponse
  402. * @param httpClient
  403. * @throws IOException
  404. */
  405. public static void release(CloseableHttpResponse httpResponse, CloseableHttpClient httpClient) throws IOException {
  406. // 释放资源
  407. if (httpResponse != null) {
  408. httpResponse.close();
  409. }
  410. if (httpClient != null) {
  411. httpClient.close();
  412. }
  413. }
  414.  
  415. }

    

Java发送Post请求,参数JSON,接收JSON的更多相关文章

  1. ExtJS发送POST请求 参数格式为JSON

    背景 这要从我比较懒说起.技术框架ExtJS + resteasy,默认请求方式是ajax get,这后台方法就要写很多@QueryParam来获取参数.我比较喜欢前台用ajax post请求,后台方 ...

  2. java 发送post请求参数中含有+会转化为空格的问题

    如题 原因分析:参数在传递过程中经历的几次编码和解码标准不同,导致加号.空格等字符的错误. 解决方案:将post请求的参数中 ,含有+号的,统统采用%2B 去替换,这是URL的协议问题.

  3. 我的Android进阶之旅------>android如何将List请求参数列表转换为json格式

    本文同步发表在简书,链接:http://www.jianshu.com/p/395a4c8b05b9 前言 由于接收原来的老项目并进行维护,之前的http请求是使用Apache Jakarta Com ...

  4. andlua,andlua发送http请求,并解析json数据

    andlua发送http请求,并解析json实例 import'cjson'import 'http'--导入cjson库url = 'https://www.baidu,com'--设置urlHtt ...

  5. Java发送Http请求并获取状态码

    通过Java发送url请求,查看该url是否有效,这时我们可以通过获取状态码来判断. try { URL u = new URL("http://10.1.2.8:8080/fqz/page ...

  6. Java发送HTTPS请求

    前言 上篇文章介绍了 java 发送 http 请求,大家都知道发送http是不安全的 .我也是由于对接了其他企业后总结了一套发送 https的工具.大家网上找方法很多的,但是可不是你粘过来就能用啊, ...

  7. Jquery Datatables 请求参数及接收参数处理

    Jquery Datatables 请求参数及接收参数处理 /** * Created by wb-wuyifu on 2016/8/9. */ /** * Created by wb-wuyifu ...

  8. 通过java发送http请求

    通常的http请求都是由用户点击某个连接或者按钮来发起的,但是在一些后台的Java程序中需要发送一些get或这post请求,因为不涉及前台页面,该怎么办呢? 下面为大家提供一个Java发送http请求 ...

  9. 使用Java发送Http请求的内容

    公司要将自己的产品封装一个WebService平台,所以最近开始学习使用Java发送Http请求的内容.这一块之前用PHP的时候写的也比较多,从用最基本的Socket和使用第三方插件都用过. 学习了J ...

随机推荐

  1. 细说opcache

    ; opcache的开关,关闭时代码不再优化. opcache.enable=1 ; Determines if Zend OPCache is enabled for the CLI version ...

  2. 吴裕雄--天生自然Linux操作系统:linux yum 命令

    yum( Yellow dog Updater, Modified)是一个在Fedora和RedHat以及SUSE中的Shell前端软件包管理器. 基於RPM包管理,能够从指定的服务器自动下载RPM包 ...

  3. 第二季第十一天 html5语义化标签 css透明度

    span不能设置宽高背景 HTML5语义化标签 <section>标签所包裹的是有一组相似的主题的内容,可以用这个标签来实现文章的章节.标签式对话框中的各种标签页等类似的功能. <s ...

  4. keras字符编码

    https://www.jianshu.com/p/258a21ae0390https://blog.csdn.net/apengpengpeng/article/details/80866034#- ...

  5. 用FFmpeg+nginx+rtmp搭建环境实现推流

    Windows: 1.下载文件: 链接:https://pan.baidu.com/s/1c2LmIHHw-dwLOlRN6iTIMg 提取码:g7sj 2.解压文件: 解压到nginx-1.7.11 ...

  6. Python笔记_第四篇_高阶编程_GUI编程之Tkinter_3.数据显示

    1. 表格数据显示: 图示: 实例: import tkinter from tkinter import ttk # 创建主窗口__编程头部 win = tkinter.Tk() # 设置标题 wi ...

  7. iOS播放器、Flutter高仿书旗小说、卡片动画、二维码扫码、菜单弹窗效果等源码

    iOS精选源码 全网最详细购物车强势来袭 一款优雅易用的微型菜单弹窗(类似QQ和微信右上角弹窗) swift, UITableView的动态拖动重排CCPCellDragger 高仿书旗小说 Flut ...

  8. linux c 调用 so 库

    /***********编译时要链接 -l dl 库************/ #include<stdlib.h> #include<stdio.h> #include< ...

  9. 【转】Fst指数

    [转]Fst指数 转载自 http://blog.csdn.net/zhu_si_tao/article/details/71513099 与 http://blog.sina.com.cn/s/bl ...

  10. pyCharm专业版最新2018激活码激活

    说明:本人亲测有用,对Window.Linux.Mac都稳定有效. 缺点:需要修改hosts文件 步骤: 由于管理权限问题,大部分电脑都不能直接修改hosts文件,所以我们可以先将hosts文件复制到 ...