HttpClient获取状态码
使用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);
这应该做的伎俩!
这个怎么样?
HttpResponse response = client.execute(getRequest); // Status Code int statusCode = response.getStatusLine().getStatusCode(); ResponseHandler<String> responseHandler = new BasicResponseHandler(); // Response Body String responseBody = responseHandler.handleResponse(response);
我这样做:
HttpResponse response = client.execute(httppost); int status = response.getStatusLine().getStatusCode();
要获取respose主体作为一个string,虽然通过不使用responseHandler,我首先得到它作为InputStream:
InputStream is = response.getEntity().getContent();
然后将其转换为一个string(方法如何做到这一点 )