https://www.cnblogs.com/mambahyw/p/7875142.html
********************************************************
通過httpclient的post方法發送json參數進行接口測試。借鑒知乎上“雲層”的提供的方法。
作者:雲層
鏈接:https://www.zhihu.com/question/30878548/answer/121149629
來源:知乎
鏈接:https://www.zhihu.com/question/30878548/answer/121149629
來源:知乎
把要發送的json作為字符串傳入body即可
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; }
我的測試代碼示例:
public static void main(String[] args) { //測試公司的API接口,將json當做一個字符串傳入httppost的請求體 String result = null; HttpClient client = HttpClients.createDefault(); URIBuilder builder = new URIBuilder(); URI uri = null; try { uri = builder.setScheme("http") .setHost("xxx.xxx.xxx.xxx:xxxx") .setPath("/api/authorize/login") .build(); HttpPost post = new HttpPost(uri); //設置請求頭 post.setHeader("Content-Type", "application/json"); String body = "{\"Key\": \"\",\"Secret\": \"\"}"; //設置請求體 post.setEntity(new StringEntity(body)); //獲取返回信息 HttpResponse response = client.execute(post); result = response.toString(); } catch (Exception e) { System.out.println("接口請求失敗"+e.getStackTrace()); } System.out.println(result); }