通过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() + " "); 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.