2013-06-27 57 views
0

我用URLConnection發送POST請求到服務器,並且我使用下面的代碼來讀取響應:如果服務器返回502錯誤,我該如何讀取HTTP響應?

String line; 
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
while ((line = reader.readLine()) != null) { 
    response += line; 
} 
reader.close(); 

但是,服務器有時會返回一個502錯誤會在響應一個有意義的錯誤消息,我想獲得。我的問題是,試圖在這種情況下創建BufferedReader將導致java.io.IOException

Server returned HTTP response code: 502 for URL: <url> 

我怎樣才能繞過這個?

回答

3

修改沿着這些線路代碼,這樣就可以得到errorstream而不是拋出IOException異常

HttpURLConnection httpConn = (HttpURLConnection)connection; 
InputStream is; 
if (httpConn.getResponseCode() >= 400) { 
    is = httpConn.getErrorStream(); 
} else { 
    is = httpConn.getInputStream(); 
} 

BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 
while ((line = reader.readLine()) != null) { 
    response += line; 
} 
reader.close(); 
+0

這做的伎倆。謝謝。 – NoToast

相關問題