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     }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM