Apache HttpClient是Apache提供的一个开源组件,使用HttpClient可以很方便地进行Http请求的调用。自4.1版本开始,HttpClient的API发生了较大的改变,很多方法的调用方式已经和3.x版本不同。本文使用的是当前最新的4.5.3版本。

首先在pom文件中引入httpcomponents依赖包:

  1. <dependency>
  2. <groupId>org.apache.httpcomponents</groupId>
  3. <artifactId>httpclient</artifactId>
  4. <version>4.5.3</version>
  5. </dependency>

本文展示的是POST请求。

  1. import java.io.IOException;
  2.  
  3. import org.apache.commons.lang3.ObjectUtils;
  4. import org.apache.commons.lang3.StringUtils;
  5. import org.apache.http.Consts;
  6. import org.apache.http.HttpStatus;
  7. import org.apache.http.ParseException;
  8. import org.apache.http.client.config.RequestConfig;
  9. import org.apache.http.client.methods.CloseableHttpResponse;
  10. import org.apache.http.client.methods.HttpPost;
  11. import org.apache.http.entity.ContentType;
  12. import org.apache.http.entity.StringEntity;
  13. import org.apache.http.impl.client.CloseableHttpClient;
  14. import org.apache.http.impl.client.HttpClients;
  15. import org.apache.http.util.EntityUtils;
  16.  
  17. /**
  18. * @author
  19. *
  20. * @date 2017年5月18日 上午9:17:30
  21. *
  22. * @Description
  23. */
  24. public class HttpPostUtils {
  25. /**
  26. *
  27. * @param uri
  28. * the request address
  29. * @param json
  30. * the request data that must be a JSON string
  31. * @param connectTimeout
  32. * the timeout in milliseconds until a connection is established
  33. * @param connectionRequestTimeout
  34. * the timeout in milliseconds used when requesting a connection
  35. * from the connection manager
  36. * @param socketTimeout
  37. * the socket timeout in milliseconds, which is the timeout for
  38. * waiting for data or, put differently, a maximum period
  39. * inactivity between two consecutive data packets
  40. * @return null when method parameter is null, "", " "
  41. * @throws IOException
  42. * if HTTP connection can not opened or closed successfully
  43. * @throws ParseException
  44. * if response data can not be parsed successfully
  45. */
  46. public String postJson(String uri, String json, int connectTimeout, int connectionRequestTimeout, int socketTimeout)
  47. throws IOException, ParseException {
  48. if (StringUtils.isAnyBlank(uri, json)) {
  49. return null;
  50. }
  51.  
  52. CloseableHttpClient client = HttpClients.createDefault();
  53. HttpPost post = new HttpPost(uri);
  54. // Create request data
  55. StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
  56. // Set request body
  57. post.setEntity(entity);
  58.  
  59. RequestConfig config = RequestConfig.custom().setConnectTimeout(connectTimeout)
  60. .setConnectionRequestTimeout(connectionRequestTimeout).setSocketTimeout(socketTimeout).build();
  61. post.setConfig(config);
  62. // Response content
  63. String responseContent = null;
  64. CloseableHttpResponse response = null;
  65. try {
  66. response = client.execute(post);
  67. if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
  68. responseContent = EntityUtils.toString(response.getEntity(), Consts.UTF_8.name());
  69. }
  70. } finally {
  71. if (ObjectUtils.anyNotNull(response)) {
  72. response.close();
  73. }
  74. if (ObjectUtils.anyNotNull(client)) {
  75. client.close();
  76. }
  77. }
  78. return responseContent;
  79. }
  80. }

使用Apache HttpClient 4.x发送Json数据的更多相关文章

  1. HttpClient发送Json数据到指定接口

    项目中遇到将Json数据发送到指定接口,于是结合网上利用HttpClient进行发送. /** * post发送json数据 * @param url * @param param * @return ...

  2. SpringMVC客户端发送json数据时报400错误

    当测试客户端发送json数据给服务器时,找不到响应路径? 原来是参数类型不符,即使是json也要考虑参数的个数和类型 解决:将age请求参数由"udf"改为"3" ...

  3. iOS开发网络篇—发送json数据给服务器以及多值参数

    iOS开发网络篇—发送json数据给服务器以及多值参数 一.发送JSON数据给服务器 发送JSON数据给服务器的步骤: (1)一定要使用POST请求 (2)设置请求头 (3)设置JSON数据为请求体 ...

  4. 【转】iOS开发网络篇—发送json数据给服务器以及多值参数

    原文: http://www.cnblogs.com/wendingding/p/3950132.html 一.发送JSON数据给服务器 发送JSON数据给服务器的步骤: (1)一定要使用POST请求 ...

  5. perl post发送json数据

    sub  wx_init {                #$login_url ="https://wx.qq.com/cgi-bin/mmwebwx-bin/webwxinit?r=- ...

  6. JSON的简单使用_向前台发送JSON数据

    转自:http://www.cnblogs.com/digdeep/p/5574366.html 1.前台页面 <%@ page language="java" conten ...

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

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

  8. IOS-网络(发送JSON数据给服务器和多值参数)

    三步走: 1.使用POST请求 2.设置请求头 [request setValue:@"application/json" forHTTPHeaderField:@"Co ...

  9. ajax使用向Spring MVC发送JSON数据出现 org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported错误

    ajax使用向Spring MVC发送JSON数据时,后端Controller在接受JSON数据时报org.springframework.web.HttpMediaTypeNotSupportedE ...

随机推荐

  1. [翻译]Review——How JavaScript works:The building blocks of Web Workers

    原文地址:https://blog.sessionstack.com/how-javascript-works-the-building-blocks-of-web-workers-5-cases-w ...

  2. 浅谈ul布局以及table布局

    我个人对于某些言论说要注重html语义化在布局中的应用,我反而不怎么感冒,试试兼容IE7&&项目期相对较赶的情况下,我还是推荐快速开发为主,兼容性强为主. 如果布局中需要用户边框,推荐 ...

  3. bootstrap框架怎么在html页面加载使用

    今天敲代码的时候,正好碰到这个问题. 与大家分享这个解决方法:     1/7 到bootstrap官方网站下载,对于我们开发者来说,直接下载编译和压缩后的CSS.JavaScript文件,另外还包含 ...

  4. CSS3字体火焰燃烧效果

    动画的CSS: // fire @keyframes fireDiv { 0% { text-shadow: 0 0 4px white, 0 -5px 4px #ff3, 2px -10px 6px ...

  5. drupal7 自定义登录&找回密码页面,注意事项

    1.登录页面的 $form['form_id'] 和 $form['form_build_id'],是这样输出的: <?php print drupal_render($form['form_i ...

  6. WDCP服务器升级之后伪静态缓存文件.htaccess读取失效

    当购买或者升级服务器之后,thinkphp3框架的默认缓存文件.htaccess读取失效,解决方法如下: 1.我的网站是thinkphp3 服务器环境是N+A模式 2.将网站根目录的.htaccess ...

  7. Linux / mysql: is it safe to copy mysql db files with cp command from one db to another?

    Copying is very simple for MyISAM and completely 100% risky (near suicidal) with InnoDB. From your q ...

  8. SQL Server ->> 性能调优案例之 -- 包含递归查询的视图导致整个查询语句性能下降

    有个语句最近性能下降很厉害,原本1秒就可以查询完毕的事情现在居然需要3-4分钟. 首先我的做法是先快速找出导致整个语句下降的元凶.在这个例子里面查询语句有3个JOIN字句,我通过删除某一个JOIN节点 ...

  9. 使用JSONP彻底解决Ajax跨域访问Cookie Session的方案

    最近做开发时要把图片文件放到另外一台服务器上(另外一个域名),因为这样分布式存放,网站打开速度会快很多.而我采用AJAX获取图片服务器上某用户的图片时遇到了问题,按照通常的方式无法获取信息,得到的Co ...

  10. .net 的page的OnInit方法

    /// <summary> /// 重写父类的方法,父类要执行的方法已经被覆盖 /// </summary> /// <param name="e"& ...