2013-02-27 84 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