使用HttpClient发送post请求时传递json格式的参数

  1. java

  2. // 接口测试-处理json格式的post请求

  3. public static String doPostJson(String url,String json) {

  4. // 创建连接池

  5. CloseableHttpClient closeableHttpClient = HttpClients.createDefault();

  6. ResponseHandler<String> responseHandler = new BasicResponseHandler();

  7. // 声明呀一个字符串用来存储response

  8. String result;

  9. // 创建httppost对象

  10. HttpPost httpPost = new HttpPost(url);

  11. // 给httppost对象设置json格式的参数

  12. StringEntity httpEntity = new StringEntity(json,"utf-8");

  13. // 设置请求格式

  14. httpPost.setHeader("Content-type","application/json");

  15. // 传参

  16. httpPost.setEntity(httpEntity);

  17.  
  18. // 发送请求,并获取返回值

  19. try {

  20. CloseableHttpResponse response = closeableHttpClient.execute(httpPost);

  21.   //返回json数据

  22. HttpEntity entity = response.getEntity();

  23. String responseContent = EntityUtils.toString(entity, "UTF-8");

  24. System.out.println(responseContent);

  25. //返回响应码200

  26.  return response.getStatusLine().getStatusCode();

  27. response.close();

  28. } catch (IOException e) {

  29. // TODO Auto-generated catch block

  30. e.printStackTrace();

  31. }

  32. return "error";

  33. }

  34.  
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值