HttpURLConnection - 未知格式(幻数376)

时间:2016-06-16 13:42:11

标签: java android http gzip httpurlconnection

我从我的Android应用程序调用HTTP GET请求:

String urlString = "http://my.service.com/foo";
HttpURLConnection conn = (HttpURLConnection) (new URL(urlString)).openConnection();
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setRequestProperty("X-MY-HEADER", "1");
conn.setDoOutput(false);

int code = conn.getResponseCode();

最后一行抛出异常:

java.io.IOException: unknown format (magic number 376)
at java.util.zip.GZIPInputStream.<init>(GZIPInputStream.java:101)
at java.util.zip.GZIPInputStream.<init>(GZIPInputStream.java:81)
at com.android.okhttp.internal.http.HttpEngine.initContentStream(HttpEngine.java:468)
at com.android.okhttp.internal.http.HttpEngine.readResponse(HttpEngine.java:666)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:347)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:296)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:503)

HTTP引擎似乎在内部使用gzip,这会导致异常。我没有要求任何压缩。为什么抛出这个异常?我可以以某种方式关闭它吗?这个神奇的数字376是什么意思?

1 个答案:

答案 0 :(得分:1)

我解决了!根据developer.android.com:

  

默认情况下, HttpURLConnection 的此实现请求   服务器使用gzip压缩,它会自动解压缩   getInputStream()调用者的数据。内容编码和   在这种情况下,Content-Length响应头被清除。 Gzip已   可以通过在中设置可接受的编码来禁用压缩   请求标题:

conn.setRequestProperty("Accept-Encoding", "identity");