通過httpclient的post方法發送json參數進行接口測試。借鑒知乎上“雲層”的提供的方法。
鏈接:https://www.zhihu.com/question/30878548/answer/121149629
public static String sendHttpPost(String url, String body) throws Exception { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url); httpPost.addHeader("Content-Type", "application/json"); httpPost.setEntity(new StringEntity(body)); CloseableHttpResponse response = httpClient.execute(httpPost); System.out.println(response.getStatusLine().getStatusCode() + "\n"); HttpEntity entity = response.getEntity(); String responseContent = EntityUtils.toString(entity, "UTF-8"); System.out.println(responseContent); response.close(); httpClient.close(); return responseContent; }
其中httpPost.setEntity(new StringEntity(body));body部分是JSON數據格式,可以不是定長數據,可以根據需求定義成數組形式,如下:
{ "splineList" : [ { "Points" : { "Pos" : [ { "Xasis" : 1.66156307383845, "Yasis" : 132.2036349238536 }, { "Xasis" : 2.598720236773715, "Yasis" : 186.8623164821516 }, { "Xasis" : 3.598720236773715, "Yasis" : 186.8623164821516 } ] } }, { "Points" : { "Pos" : [ { "Xasis" : 4.66156307383845, "Yasis" : 132.2036349238536 }, { "Xasis" : 5.598720236773715, "Yasis" : 186.8623164821516 } ] } }, { "Points" : { "Pos" : [ { "Xasis" : 6.66156307383845, "Yasis" : 132.2036349238536 }, { "Xasis" : 7.598720236773715, "Yasis" : 186.8623164821516 }, { "Xasis" : 17.598720236773715, "Yasis" : 186.8623164821516 }, { "Xasis" : 27.598720236773715, "Yasis" : 186.8623164821516 }, { "Xasis" : 37.598720236773715, "Yasis" : 186.8623164821516 } ] } } ] }
其中,splineList有多個Points組成,Points又由多個Xasis,Yasis坐標組成.
Json格式解釋和編解碼開源庫請參考:http://json.org/json-zh.html.