Android Volley: gzip response

2019-04-24 21:34发布

问题:

What type of response listener must we use to handle gzip responses with Android Volley?

If a String listener is used, the response seems to lose its encoding.

How do you handle gzip responses using Volley?

MAJOR EDIT: HttpUrlConnection automatically adds the gzip header to requests, and if the response is gzipped, it will seamlessly decode it and present to you the response. All the gzip stuff happens behind the scenes and you don't need to do what I posted in a gist as an answer to this question. See the documentation here http://developer.android.com/reference/java/net/HttpURLConnection.html

As a matter of fact, the answer I posted SHOULD NOT be used, because the gzip decoding is extremely slow, and should be left to be handled by HttpUrlConnection.

Here is the exact piece from the documentation:

By default, this implementation of HttpURLConnection requests that servers use gzip compression. Since getContentLength() returns the number of bytes transmitted, you cannot use that method to predict how many bytes can be read from getInputStream(). Instead, read that stream until it is exhausted: when read() returns -1. Gzip compression can be disabled by setting the acceptable encodings in the request header:

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

回答1:

So I figured out how to do this.

Basically, I extended StringRequest so that it handles the network response a different way.

You can just parse the response bytearray using GZipInputStream and return the resultant string.

Here's the gist: https://gist.github.com/premnirmal/8526542



回答2:

You should use ion ,, it's comes pre-set with

Transparent usage of HTTP features and optimizations:
SPDY and HTTP/2
Caching
Gzip/Deflate Compression
Connection pooling/reuse via HTTP Connection: keep-alive
Uses the best/stablest connection from a server if it has multiple IP addresses
Cookies