簡體   English   中英

從HttpURLConnection中的getErrorStream返回的InputStream中獲取從服務器發送的有用數據

[英]Get the useful data sent from server in InputStream returned by getErrorStream in HttpURLConnection

當我在HttpURLConnection中調用getInputStream()方法時,它將返回HTTP異常,並且我使用此策略來捕獲該異常。

try {
   con.getInputStream();
} catch (IOException e) {
   resStream = con.getErrorStream();
}

但是,正如JavaDoc所述,我需要獲取服務器發送到resStream的有用數據,如下所示。 “如果連接失敗但服務器仍發送有用的數據,則返回錯誤流。”

有什么方法可以從getErrorStream()返回的InputStream中獲取響應消息(如果返回的值不為null且返回的響應是有效的)?

您可以將此字節流包裝為字符流,然后讀取錯誤信息。

InputStreamReader isr = new InputStreamReader(resStream);
BufferedReader br = new BufferedReader(isr);
StringBuffer buf = new StringBuffer();
String line = null;
while((line = buf.readLine()) != null) {
    buf.append(line);
}
//assume you have a log object, you'd better not use System.out.println()
log.error(buf.toString());
//do not forget to close all the stream

然后,您可以從服務器端獲取堆棧跟蹤。 我希望這將有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM