我有一个问题,当我尝试读取任何输入时,我的HttpsURLConnection会抛出EOFException异常。这段代码可以用于某些网络调用,但在其他情况下会失败。如果我尝试从该连接中读取任何内容,它将以前面提到的错误失败。
示例:
urlConnect.getResponseCode() // will throw error
urlConnect.getResponseMessage() // will throw error
BufferedInputStream in = new BufferedInputStream(urlConnect.getInputStream()); //will throw error
以下是每个的堆栈跟踪:
getResponse:
03-14 09:49:18.547: W/System.err(6270): java.io.EOFException
03-14 09:49:18.547: W/System.err(6270): at libcore.io.Streams.readAsciiLine(Streams.java:203)
03-14 09:49:18.547: W/System.err(6270): at libcore.net.http.HttpEngine.readResponseHeaders(HttpEngine.java:573)
03-14 09:49:18.547: W/System.err(6270): at libcore.net.http.HttpEngine.readResponse(HttpEngine.java:821)
03-14 09:49:18.547: W/System.err(6270): at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:283)
03-14 09:49:18.547: W/System.err(6270): at libcore.net.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:495)
03-14 09:49:18.547: W/System.err(6270): at libcore.net.http.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:134)
缓冲输入流:
03-14 09:39:14.077: W/System.err(5935): java.io.EOFException
03-14 09:39:14.077: W/System.err(5935): at libcore.io.Streams.readAsciiLine(Streams.java:203)
03-14 09:39:14.077: W/System.err(5935): at libcore.net.http.HttpEngine.readResponseHeaders(HttpEngine.java:573)
03-14 09:39:14.077: W/System.err(5935): at libcore.net.http.HttpEngine.readResponse(HttpEngine.java:821)
03-14 09:39:14.077: W/System.err(5935): at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:283)
03-14 09:50:46.547: W/System.err(6476): at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:177)
03-14 09:50:46.547: W/System.err(6476): at libcore.net.http.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:271)
感谢任何帮助,
Rick
编辑 我找到了答案:
这不是一个文档完善的答案。在一些新版本的安卓中,出现了已回收的 URL 连接存在问题的 bug。为了解决这个问题(尽管可能会有一些性能问题),我需要添加:
if (Build.VERSION.SDK != null
&& Build.VERSION.SDK_INT > 13) {
urlConnect.setRequestProperty("Connection", "close");
}
谢谢!
Rick