HttpURLConnection - 未知格式(幻数 376)
HttpURLConnection - uknown format (magic number 376)
我从我的 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 是什么意思?
我解决了!根据developer.android.com:
By default, this implementation of HttpURLConnection requests that servers use gzip compression and it automatically decompresses the data for callers of getInputStream(). The Content-Encoding and Content-Length response headers are cleared in this case. Gzip compression can be disabled by setting the acceptable encodings in the request header:
conn.setRequestProperty("Accept-Encoding", "identity");