在與HttpsURLConnection建立連接後,我讀取輸入緩衝區。一切工作正常,但如果返回的數據是空的(只有200 0字節) reader.readLine()引發IOException。 (編輯:它實際上是一個超時)BufferedReader.readLine():如何避免空數據時的異常?
什麼IF語句我可以在reader.readLine()之前寫,所以我可以提前抓住這個?
注意:一個棘手的部分可能是我們仍然需要等待緩衝區已經收到了一切,因此IF需要是「我們收到了一切,但沒有任何東西。」
謝謝!
HttpsURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL("https://example.com/GiveMeSomTextPlain");
connection = (HttpsURLConnection) url.openConnection();
connection.setConnectTimeout(9000);
connection.setReadTimeout(11000);
connection.connect();
int resp = connection.getResponseCode();
if (resp == 200) {
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
// if(reader.ThereWillBeNoData()){ // THIS IS WHAT I NEED
// ...
// }
String line = "";
while((line = reader.readLine()) != null){ // EXCEPTION IF EMPTY DATA
// ...
}
}else{
reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
}
} catch (IOException e) {
e.printStackTrace();
// WE GET HERE AT EXCEPTION
} finally {
if (connection != null) connection.disconnect();
try {
if (reader != null) reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
編輯:啊,似乎它在超時結束(相當於我進入11S),但「空」是一個答案了,所以如何避免超時? (見我RESPONSE)
堆棧跟蹤:
09-13 18:39:40.134 20925-21658/com.theapp D/ZZZ: BEFORE WHILE
09-13 18:39:51.155 20925-21658/com.theapp W/System.err: java.net.SocketTimeoutException: Read timed out
09-13 18:39:51.155 20925-21658/com.theapp W/System.err: at com.android.org.conscrypt.NativeCrypto.SSL_read(Native Method)
09-13 18:39:51.155 20925-21658/com.theapp W/System.err: at com.android.org.conscrypt.OpenSSLSocketImpl$SSLInputStream.read(OpenSSLSocketImpl.java:690)
09-13 18:39:51.155 20925-21658/com.theapp W/System.err: at java.io.BufferedInputStream.read(BufferedInputStream.java:283)
09-13 18:39:51.165 20925-21658/com.theapp W/System.err: at com.android.okhttp.internal.http.UnknownLengthHttpInputStream.read(UnknownLengthHttpInputStream.java:39)
09-13 18:39:51.165 20925-21658/com.theapp W/System.err: at java.io.InputStreamReader.read(InputStreamReader.java:233)
09-13 18:39:51.165 20925-21658/com.theapp W/System.err: at java.io.BufferedReader.fillBuf(BufferedReader.java:145)
09-13 18:39:51.165 20925-21658/com.theapp W/System.err: at java.io.BufferedReader.readLine(BufferedReader.java:397)
09-13 18:39:51.165 20925-21658/com.theapp W/System.err: at com.theapp.Main.getMapData(Main.java:637)
09-13 18:39:51.165 20925-21658/com.theapp W/System.err: at com.theapp.Main$2$2.run(Main.java:231)
09-13 18:39:51.165 20925-21658/com.theapp W/System.err: at java.lang.Thread.run(Thread.java:841)
09-13 18:39:51.165 20925-21658/com.theapp D/ZZZ: EXCEPTION
'readLine()'如果沒有數據,則不會*拋出'IOException'。它返回null。你在說什麼? – EJP
你能發佈異常堆棧跟蹤嗎? –
它確實如果緩衝器從來沒有任何數據,因爲它正在等待。沒有必要對自己進行測試而無需負面評價。我之前和之後都放了一些Log.d(),毫無疑問,發送一些數據的200會很好,但只要我在沒有數據的情況下創建200,它就永遠不會到達第二個Lod.d()過了一會兒,直接進入IOException。 – FlorianB