如何获得HttpClient返回状态码和响应正文?
我正在尝试让Apache
HttpClient触发HTTP请求,然后显示HTTP响应代码(200、404、500等)以及HTTP响应正文(文本字符串)。重要的是要注意我正在使用,v4.2.2
因为那里有大多数HttpClient示例,v.3.x.x
并且API从版本3到版本4有了很大的变化。
不幸的是,我只能使HttpClient返回状态代码 响应正文(但不能同时返回两者)。
这是我所拥有的:
// Getting the status code.HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://whatever.blah.com");
HttpResponse resp = client.execute(httpGet);
int statusCode = resp.getStatusLine().getStatusCode();
// Getting the response body.
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://whatever.blah.com");
ResponseHandler<String> handler = new BasicResponseHandler();
String body = client.execute(httpGet, handler);
所以我问: 提前致谢!
回答:
不要向提供处理程序execute
。
获取HttpResponse
对象,使用处理程序获取主体并直接从中获取状态代码
try (CloseableHttpClient httpClient = HttpClients.createDefault()) { final HttpGet httpGet = new HttpGet(GET_URL);
try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
StatusLine statusLine = response.getStatusLine();
System.out.println(statusLine.getStatusCode() + " " + statusLine.getReasonPhrase());
String responseBody = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
System.out.println("Response body: " + responseBody);
}
}
对于快速的单次调用,流利的API很有用:
Response response = Request.Get(uri) .connectTimeout(MILLIS_ONE_SECOND)
.socketTimeout(MILLIS_ONE_SECOND)
.execute();
HttpResponse httpResponse = response.returnResponse();
StatusLine statusLine = httpResponse.getStatusLine();
对于Java或httpcomponents的旧版本,代码可能看起来有所不同。
以上是 如何获得HttpClient返回状态码和响应正文? 的全部内容, 来源链接: utcz.com/qa/432873.html