我正在尝试使用正文制作HTTP Post请求。我想知道如何将json对象放入请求体内,然后阅读正文。
HttpClient httpClient = HttpClientBuilder.create().build();
String responseString = null;
try {
HttpPost request = new HttpPost(link);
log.info("Executing request " + request.getRequestLine());
StringEntity params = new StringEntity(data);
request.addHeader("content-type", "application/json");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
HttpEntity entity = response.getEntity();
responseString = EntityUtils.toString(entity, "UTF-8");
} catch (Exception e) {
log.info("Exception thrown while executing HTTPPostRequest");
}
return responseString;
这是我目前用来提出请求的代码片段。如果使用'StringEntity'是将数据放入body中的正确选择。 我得到空身,它应该返回包含json数据的主体
答案 0 :(得分:0)
只要你的数据'是json它应该没问题。
HttpClient httpClient = HttpClientBuilder.create().build();
String responseString = null;
try {
HttpPost request = new HttpPost(link);
log.info("Executing request " + request.getRequestLine());
StringEntity content = new StringEntity(data);
content.setContentType("application/json");
//or request.setHeader("Content-type", "application/json");
request.setEntity(content);
HttpResponse response = httpClient.execute(request);
HttpEntity entity = response.getEntity();
responseString = EntityUtils.toString(entity, "UTF-8");
} catch (Exception e) {
log.info("Exception thrown while executing HTTPPostRequest");
}
return responseString;