Last active
December 20, 2022 06:07
-
-
Save premnirmal/8526542 to your computer and use it in GitHub Desktop.
Parse GZip responses using volley
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.android.volley.NetworkResponse; | |
import com.android.volley.ParseError; | |
import com.android.volley.Response; | |
import com.android.volley.toolbox.HttpHeaderParser; | |
import com.android.volley.toolbox.StringRequest; | |
import java.io.BufferedReader; | |
import java.io.ByteArrayInputStream; | |
import java.io.IOException; | |
import java.io.InputStreamReader; | |
import java.util.zip.GZIPInputStream; | |
public class GZipRequest extends StringRequest { | |
public GZipRequest(int method, String url, Response.Listener<String> listener, Response.ErrorListener errorListener) { | |
super(method, url, listener, errorListener); | |
} | |
public GZipRequest(String url, Response.Listener<String> listener, Response.ErrorListener errorListener) { | |
super(url, listener, errorListener); | |
} | |
// parse the gzip response using a GZIPInputStream | |
@Override | |
protected Response<String> parseNetworkResponse(NetworkResponse response) { | |
String output = ""; // note: better to use StringBuilder | |
try { | |
final GZIPInputStream gStream = new GZIPInputStream(new ByteArrayInputStream(response.data)); | |
final InputStreamReader reader = new InputStreamReader(gStream); | |
final BufferedReader in = new BufferedReader(reader); | |
String read; | |
while ((read = in.readLine()) != null) { | |
output += read; | |
} | |
reader.close(); | |
in.close(); | |
gStream.close(); | |
} catch (IOException e) { | |
return Response.error(new ParseError()); | |
} | |
return Response.success(output, HttpHeaderParser.parseCacheHeaders(response)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Dear @scottagarman,
Just my two cents, you could write also
if("gzip".equals(response.headers.get("Content-Encoding"))) {
Saves you both the check on
null
and the additionalString
object.BTW: you can find my implementation for a
JsonArrayRequest
here: GZipJsonArrayRequest.java