This question already has answers here:
How to get HttpClient returning status code and response body?

(5个答案)


在11个月前关闭。




使用Apache HttpClient 4.1.3并尝试从HttpGet获取状态代码:
HttpClient client = new DefaultHttpClient();
HttpGet response = new HttpGet("http://www.example.com");
ResponseHandler<String> handler = new BasicResponseHandler();
String body = client.execute(response, handler);

如何从body中提取状态代码(202、404等)? 或者,如果在4.1.3中还有另一种方法,那是什么?

另外,我假设一个完美/良好的HTTP响应是一个HttpStatus.SC_ACCEPTED,但也希望对此进行确认。提前致谢!

最佳答案

编辑:

尝试:

HttpResponse httpResp = client.execute(response);
int code = httpResp.getStatusLine().getStatusCode();

HttpStatus应该为200(HttpStatus.SC_OK)

(我读的问题太快了!)

尝试:
GetMethod getMethod = new GetMethod("http://www.example.com");
int res = client.executeMethod(getMethod);

这应该可以解决问题!

10-07 20:40