如何获得40倍响应的身体?

时间:2013-02-27 07:23:10

标签: java apache-httpclient-4.x

我的代码是

HttpClient client = new DefaultHttpClient();
URI uri = URIUtils.createURI(SCHEME, HOST, PORT, path, formatedParams, null);
HttpGet get = new HttpGet(uri);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = client.execute(get, responseHandler);

当我执行此代码并且响应状态为400时,最后一行会抛出错误,我无法获得responseBody内的内容。如果我通过浏览器( Chrome )执行相同的请求,我可以看到响应内容。

我希望能够在我的java代码中看到响应正文。响应是200或400。

如果错误是

org.apache.http.client.HttpResponseException: Bad Request
    at org.apache.http.impl.client.BasicResponseHandler.handleResponse(BasicResponseHandler.java:68)
    at org.apache.http.impl.client.BasicResponseHandler.handleResponse(BasicResponseHandler.java:54)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:1070)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:1044)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:1035)

1 个答案:

答案 0 :(得分:3)

看起来BasicResponseHandler无法处理400.也许试试:

  HttpResponse response = client.execute(get);
  InputStream inputStream = response.getEntity().getContent();
  // TODO Stream to String