How to get the body of a 40x response?

我的未来我决定 提交于 2019-12-13 02:37:40

问题


My code is

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);

When I execute this code and that the response status is 400, an error is thrown on the last line and I cannot get what should be inside responseBody. If I do the same request via a browser (Chrome), I can see the response contents.

I would like to be able to see the response body in my java code. Response being a 200 or a 400.

In case, the error is

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:


Looks like BasicResponseHandler can't handle 400. Maybe try:

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


来源:https://stackoverflow.com/questions/15106324/how-to-get-the-body-of-a-40x-response

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!