如何获取返回状态代码和响应正文的 HttpClient?
2022-08-31 16:19:23
我试图让Apache HttpClient触发HTTP请求,然后显示HTTP响应代码(200,404,500等)以及HTTP响应正文(文本字符串)。重要的是要注意,我正在使用,因为大多数HttpClient示例都来自版本3,并且API从版本3更改为版本4。v4.2.2
v.3.x.x
不幸的是,我只能让HttpClient返回状态代码或响应正文(但不是两者)。
以下是我所拥有的:
// Getting the status code.
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://whatever.blah.com");
HttpResponse resp = client.execute(httpGet);
int statusCode = resp.getStatusLine().getStatusCode();
// Getting the response body.
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://whatever.blah.com");
ResponseHandler<String> handler = new BasicResponseHandler();
String body = client.execute(httpGet, handler);
所以我问:使用v4.2.2
库,我如何从同一个客户端获取状态代码和响应正文。execute(...)
调用?提前致谢!