如何让HttpClient返回状态码和响应体?

时间:2012-12-24 18:31:02

标签: java http apache-httpclient-4.x

我正在尝试让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(...)电话中获取状态代码和响应正文?提前致谢!

5 个答案:

答案 0 :(得分:43)

不要将处理程序提供给execute

获取HttpResponse对象,使用处理程序获取正文并直接从中获取状态代码

HttpResponse response = client.execute(httpGet);
String body = handler.handleResponse(response);
int code = response.getStatusLine().getStatusCode();

答案 1 :(得分:22)

您可以避免使用BasicResponseHandler,但使用HttpResponse本身将状态和响应都作为String获取。

HttpResponse response = httpClient.execute(get);

// Getting the status code.
int statusCode = response.getStatusLine().getStatusCode();

// Getting the response body.
String responseBody = EntityUtils.toString(response.getEntity());

答案 2 :(得分:11)

如果状态不是2xx,则抛出BasicResponseHandler。见其javadoc

我将如何做到这一点:

HttpResponse response = client.execute( get );
int code = response.getStatusLine().getStatusCode();
InputStream body = response.getEntity().getContent();
// Read the body stream

或者你也可以从BasicResponseHandler源代码开始编写一个ResponseHandler,当状态不是2xx时,它不会抛出。

答案 3 :(得分:3)

Fluent facade API:

Response response = Request.Get(uri)
        .connectTimeout(MILLIS_ONE_SECOND)
        .socketTimeout(MILLIS_ONE_SECOND)
        .execute();
HttpResponse httpResponse = response.returnResponse();
StatusLine statusLine = httpResponse.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
    // 响应内容编码自适应?(好像没那么智能)
    String responseContent = EntityUtils.toString(
            httpResponse.getEntity(), StandardCharsets.UTF_8.name());
}

答案 4 :(得分:0)

如果您使用的是Spring

        return  new ResponseEntity<String>("your response", HttpStatus.ACCEPTED);