我正在尝试将以下JSON字符串发送到Java中的url:
标签名称为data
且正文为
{"process": "mobileS","phone": "9999999999"}
到目前为止我的代码如下:
HttpClient httpClient = HttpClientBuilder.create().build(); //Use this instead
try {
HttpPost request = new HttpPost("url goes here");
StringEntity params = new StringEntity("details={\"process\":\"mobileS\",\"phone\":\"9999999999\"}");
request.addHeader("content-type", "application/x-www-form-urlencoded");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
System.out.println(response);
// handle response here...
} catch (Exception ex) {
// handle exception here
} finally {
httpClient.getConnectionManager().shutdown(); //Deprecated
}
我应该在将JSON数据发送到服务器后从上面获取JSON字符串,但在发送上述请求后我不知道该去哪里。
好处是响应会返回200响应并显示通常来自HttpResponse结果的所有其他信息,但我得到的结果类似于:
{"test": {"this is":"what I am supposed to get"}}
所以基本上它应该返回一个JSON字符串,我得到的东西与我需要的东西完全不同
HttpResponseProxy{HTTP/1.1 200 OK [Cache-Control: no-store, no-cache, must-revalidate, max-age=0,post-check=0, pre-check=0 etc etc etc
我似乎无法理解我做错了什么。
答案 0 :(得分:1)
HttpResponse
类公开了getEntity
方法,该方法返回HttpEntity
个实例。这提供了一种访问响应内容的机制。
您可以使用EntityUtils
来检索和使用实体的内容流:
private void getData(){
CloseableHttpClient httpClient = HttpClientBuilder.create().build(); //Use this instead
CloseableHttpResponse response = null;
HttpEntity entity = null;
try {
HttpPost request = new HttpPost("url goes here");
StringEntity params = new StringEntity("details={\"process\":\"mobileS\",\"phone\":\"9999999999\"}");
request.addHeader("content-type", "application/x-www-form-urlencoded");
request.setEntity(params);
response = httpClient.execute(request);
System.out.println(response);
// handle response here...
if (successful(response)) {
entity = response.getEntity();
String content = EntityUtils.toString(entity);
System.out.println(content);
}
} catch (Exception ex) {
// handle exception here
} finally {
EntityUtils.consumeQuietly(entity);
if (response != null) response.close();
if (httpClient != null) httpClient.close();
}
}
// TODO Customize for your server/interaction
private boolean successful(HttpResponse response) {
return response != null
&& response.getStatusLine() != null
&& response.getStatusLine().getStatusCode() == 200;
}