Android Volley:gzip响应 [英] Android Volley: gzip response

查看:68
本文介绍了Android Volley:gzip响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们必须使用哪种类型的响应侦听器来通过Android Volley处理gzip响应?

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

如果使用String侦听器,则响应似乎会丢失其编码.

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

您如何使用Volley处理gzip响应?

How do you handle gzip responses using Volley?

主要 HttpUrlConnection自动将 gzip 标头添加到请求中,如果将响应压缩,则它将无缝解码并呈现给您.所有gzip东西都在幕后发生,您不需要做我在要点中发布的作为该问题的答案的事情.在此处查看文档 http://developer.android.com/reference/java/net/HttpURLConnection.html

MAJOR 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

事实上,我使用的是不应该发布的答案,因为gzip解码非常慢,应该由HttpUrlConnection处理.

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:

默认情况下,此HttpURLConnection实现请求 服务器使用gzip压缩.由于getContentLength()返回 传输的字节数,您不能使用该方法来预测 可以从getInputStream()中读取许多字节.相反,请阅读 流直到耗尽为止:当read()返回-1时. Gzip压缩 可以通过在请求中设置可接受的编码来禁用 标头:

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");

推荐答案

所以我想出了如何做到这一点.

So I figured out how to do this.

基本上,我扩展了StringRequest,以便它以不同的方式处理网络响应.

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

您只需使用GZipInputStream解析响应字节数组并返回结果字符串即可.

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

要点如下: https://gist.github.com/premnirmal/8526542

这篇关于Android Volley:gzip响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆