我正在尝试让Apache HttpClient触发HTTP请求,然后显示HTTP响应代码(200,404,500等)以及HTTP响应正文(文本字符串)。重要的是要注意我使用 v4.2.2 因为大多数HttpClient示例来自 v.3.xx 并且API从版本3变为版本4.
I am trying to get Apache HttpClient to fire an HTTP request, and then display the HTTP response code (200, 404, 500, etc.) as well as the HTTP response body (text string). It is important to note that I am using v4.2.2 because most HttpClient examples out there are from v.3.x.x and the API changed greatly from version 3 to version 4.
不幸的是,我只能让HttpClient返回状态代码或回复正文(但不是两者)。
Unfortunately I've only been able to get HttpClient returning the status code or the response body (but not both).
这就是我所拥有的:
// Getting the status code. HttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet("whatever.blah"); HttpResponse resp = client.execute(httpGet); int statusCode = resp.getStatusLine().getStatusCode(); // Getting the response body. HttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet("whatever.blah"); ResponseHandler<String> handler = new BasicResponseHandler(); String body = client.execute(httpGet, handler);所以我问:使用 v4.2.2 库,如何从同一个 client.execute(...)调用中获取状态代码和响应正文?提前致谢!
So I ask: Using the v4.2.2 library, how can I obtain both status code and response body from the same client.execute(...) call? Thanks in advance!
推荐答案不要将处理程序提供给执行。
Don't provide the handler to execute.
获取 HttpResponse 对象,使用处理程序获取正文并直接从中获取状态代码
Get the HttpResponse object, use the handler to get the body and get the status code from it directly
HttpResponse response = client.execute(httpGet); String body = handler.handleResponse(response); int code = response.getStatusLine().getStatusCode();更多推荐
如何让HttpClient返回状态代码和响应体?
发布评论