我正在尝试让 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);
所以我问:使用 v4.2.2
库,如何从同一个 client.execute(...) 获取状态码和响应体
打电话? 提前致谢!
最佳答案
不要将处理程序提供给执行
。
获取HttpResponse
对象,使用handler获取body,直接从中获取状态码
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);
}
}
对于快速单次调用,fluent 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,代码可能看起来不同。
关于java - 如何让 HttpClient 返回状态码和响应正文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14024625/