使用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
,但也希望确认。提前谢谢!
答案 0 :(得分:73)
修改强>
尝试:
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);
这应该可以解决问题!
答案 1 :(得分:5)
这个怎么样?
HttpResponse response = client.execute(getRequest);
// Status Code
int statusCode = response.getStatusLine().getStatusCode();
ResponseHandler<String> responseHandler = new BasicResponseHandler();
// Response Body
String responseBody = responseHandler.handleResponse(response);
答案 2 :(得分:4)
我这样做:
HttpResponse response = client.execute(httppost);
int status = response.getStatusLine().getStatusCode();
要通过不使用responseHandler将respose主体作为String获取,我首先将其作为InputStream获取:
InputStream is = response.getEntity().getContent();
然后将其转换为String(如何执行here)