使用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.  
上一篇:网易云信课题实践-注册请求处理


下一篇:HttpUtil 发送请求