其他分享
首页 > 其他分享> > 使用HttpClient发送post请求时传递json格式的参数

使用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. //返回结果 响应码200

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

  23. response.close();

  24. } catch (IOException e) {

  25. // TODO Auto-generated catch block

  26. e.printStackTrace();

  27. }

  28. return "error";

  29. }

  30.  

标签:String,json,httpPost,格式,new,post,response,HttpClient
来源: https://blog.csdn.net/qq_38480786/article/details/112465470