如何获得HttpClient的返回状态码和响应主体?(How to get HttpClient r

2019-07-17 13:05发布

我试图让Apache的HttpClient的火一个HTTP请求,然后显示HTTP响应代码(200,404,500等)以及HTTP响应主体(文本字符串)。 需要注意的是我使用的是非常重要的v4.2.2 ,因为大多数的HttpClient的例子在那里来自v.3.xx和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(...)打电话? 提前致谢!

Answer 1:

不提供处理程序来execute

获取HttpResponse对象,使用处理程序来获取身体,并从它直接将状态代码

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


Answer 2:

你可以避开BasicResponseHandler,但使用的HttpResponse本身同时获得状态和响应为一个字符串。

HttpResponse response = httpClient.execute(get);

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

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


Answer 3:

BasicResponseHandler抛出,如果状态不2XX。 看到它的javadoc 。

这里是我会怎么做:

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

或者你也可以写信时状态不2XX不扔BasicResponseHandler源开始对ResponseHandler。



Answer 4:

流利的门面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());
}


Answer 5:

如果您使用的春天

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


文章来源: How to get HttpClient returning status code and response body?