HttpClient 获取状态代码

2022-09-01 01:54:49

使用 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);

如何从正文中提取状态代码(202、404 等)?或者,如果在4.1.3中还有另一种方法可以做到这一点,那它是什么?

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


答案 1

编辑:

尝试使用:

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);

这应该可以解决问题!


答案 2

怎么样?

HttpResponse response = client.execute(getRequest);

// Status Code
int statusCode = response.getStatusLine().getStatusCode();

ResponseHandler<String> responseHandler = new BasicResponseHandler();
// Response Body
String responseBody = responseHandler.handleResponse(response);

推荐