Android HttpsUrlConnection java.io.EOFException

时间:2016-07-18 16:00:28

标签: android inputstream httpsurlconnection

我遇到一个问题,当我尝试打开此网址时,我的HttpsURLConnection会抛出EOFException:http://www.weather.com.cn/data/cityinfo/101210101.html

代码:

URL url = new URL("http://www.weather.com.cn/data/cityinfo/101210101.html");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
InputStream in = new BufferedInputStream(connection.getInputStream());
StringBuffer out = new StringBuffer();
byte[] b = new byte[1024];
for(int n;(n = in.read(b)) != -1;){
    out.append(new String(b, 0, n));
}

以下是StackTrace:

java.io.EOFException
    at com.android.okio.RealBufferedSource.require(RealBufferedSource.java:64)
    at com.android.okio.RealBufferedSource.readIntLe(RealBufferedSource.java:115)
    at com.android.okio.GzipSource.consumeTrailer(GzipSource.java:168)
    at com.android.okio.GzipSource.read(GzipSource.java:87)
    at com.android.okio.RealBufferedSource$1.read(RealBufferedSource.java:168)
    at java.io.InputStream.read(InputStream.java:162)
    at java.io.BufferedInputStream.fillbuf(BufferedInputStream.java:149)
    at java.io.BufferedInputStream.read(BufferedInputStream.java:295)
    at java.io.InputStream.read(InputStream.java:162)
    at com.coolweather.app.coolweather.util.HttpUtil$1.run(HttpUtil.java:47)
    at java.lang.Thread.run(Thread.java:818)

2 个答案:

答案 0 :(得分:1)

我也有同样的问题。我已经修改了它:

connection.setRequestProperty("Accept-Encoding", "musixmatch");

connection.setRequestProperty("Accept-Encoding", "");

connection.setRequestMethod("GET");

之后

设置connection.setRequestProperty(“Accept-Encoding”,“”);有效地解决了这个问题,因为它不再等待gzip压缩输出,因此不会触发超时。

更多细节:https://code.google.com/p/android/issues/detail?id=24672

答案 1 :(得分:0)

您可以在connection.setRequestProperty( "Accept-Encoding", "" );之后添加connection.setRequestMethod("GET");,因为网址的http响应标头为"Content-Encoding:gzip"。你可以看到解释here 另一个here