2013-02-27 85 views
1

我的代码是如何获得40x响应的正文?

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)
+0

坏请求服务器说它不喜欢你GET的东西。在GET请求中可能丢失了一些设置。 – araknoid 2013-02-27 07:29:41

回答

3

貌似BasicResponseHandler无法处理400也许尝试:

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

事实上,他不能:如果响应代码大于等于300,则响应正文被消耗,并抛出HttpResponseException。http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org /apache/http/impl/client/BasicResponseHandler.html – n1ckolas 2013-02-27 07:31:07

+0

非常感谢你们俩。 – oldergod 2013-02-27 07:37:17