HttpPost请求将json作为请求体传入的简单处理方法
通过httpclient的post方法发送json参数进行接口测试。借鉴知乎上“云层”的提供的方法。
作者:云层
链接:https://www.zhihu.com/question/30878548/answer/121149629
来源:知乎
链接: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 }