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     }

 

转载于:https://www.cnblogs.com/mambahyw/p/7875142.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值