HttpPost请求将json作为请求体传入的简单处理方法

Posted 一骑轻尘

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HttpPost请求将json作为请求体传入的简单处理方法相关的知识,希望对你有一定的参考价值。

通过httpclient的post方法发送json参数进行接口测试。借鉴知乎上“云层”的提供的方法。

作者:云层
链接:https://www.zhihu.com/question/30878548/answer/121149629
来源:知乎
把要发送的json作为字符串传入body即可
 1 public static String sendHttpPost(String url, String body) throws Exception {
 2 CloseableHttpClient httpClient = HttpClients.createDefault();
 3 HttpPost httpPost = new HttpPost(url);
 4 httpPost.addHeader("Content-Type", "application/json");
 5 httpPost.setEntity(new StringEntity(body));
 6 
 7 CloseableHttpResponse response = httpClient.execute(httpPost);
 8 System.out.println(response.getStatusLine().getStatusCode() + "\n");
 9 HttpEntity entity = response.getEntity();
10 String responseContent = EntityUtils.toString(entity, "UTF-8"); 
11 System.out.println(responseContent);
12 
13 response.close();
14 httpClient.close();
15 return responseContent;
16 }

 

我的测试代码示例:

 1     public static void main(String[] args) {
 2         //测试公司的API接口,将json当做一个字符串传入httppost的请求体
 3         String result = null;
 4         HttpClient client = HttpClients.createDefault();
 5         URIBuilder builder = new URIBuilder();
 6         URI uri = null;
 7         try {
 8             uri = builder.setScheme("http")
 9                       .setHost("xxx.xxx.xxx.xxx:xxxx")
10                       .setPath("/api/authorize/login")
11                       .build();
12             
13             HttpPost post = new HttpPost(uri);
14             //设置请求头
15             post.setHeader("Content-Type", "application/json");
16             String body = "{\"Key\": \"\",\"Secret\": \"\"}";
17             //设置请求体
18             post.setEntity(new StringEntity(body));
19             //获取返回信息
20             HttpResponse response = client.execute(post);
21             result = response.toString();
22         } catch (Exception e) {
23             System.out.println("接口请求失败"+e.getStackTrace());
24         }
25         System.out.println(result);
26     }

 



以上是关于HttpPost请求将json作为请求体传入的简单处理方法的主要内容,如果未能解决你的问题,请参考以下文章

Swift 4 中的 Encoding 和 Decoding

在 Swift 中使用 JSON 正文发出 HTTP Post 请求

通过 iis 上的 python 脚本处理带有 json 的 http post 请求

WSO2 API Manager将JSON转换为XML(并且失败了请求)

HttpGet或HttpPost 请求报400错误

fastapi教程翻译(四):Request Body(请求体)