【发布时间】:2012-08-17 00:02:18
【问题描述】:
我正在运行带有 Ruby 1.9.3p194 的 Rails 3.2.7,以从 SQLite 数据库输出 JSON 数据。
render :json => result.to_json
Android 应用程序使用通过 HTTP-GET 加载的 JSON 文件:
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(urlPath);
HttpResponse response = httpclient.execute(httpGet);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity, HTTP.UTF_8);
JSONObject jsonObject = new JSONObject(result);
平台支持:
我在API中读到Rails offers gzip support如下:
ActiveSupport::Gzip.compress(result)
我也从HTTP/1.1, RFC2626, section 14.3 猜想我可以配置 HTTP 请求的标头:
httpPost.setHeader("Accept-Encoding", "gzip");
我还发现section 3.5 "Content Codings"中包含的信息很有趣:
- 所有内容编码值不区分大小写。
- HTTP/1.1 在 Accept-Encoding(第 14.3 节)和 Content-Encoding(第 14.11 节)标头字段中使用内容编码值。
- 互联网号码分配机构 (IANA) 充当内容编码值令牌的注册机构。最初,注册表包含 以下标记:
- gzip 由文件压缩程序“gzip”(GNU zip)产生的编码格式,如 RFC 1952 [25] 中所述。
这篇文章进一步解释了how to handle GZIP encoded content with Android。
服务器测试:
因此,我不知道如何找出数据是否已被服务器压缩。 为了测试 Rails 是否输出 gzip,我尝试按照建议使用 curl here:
$ curl --head -H "Accept-Encoding: gzip" http://localhost:3000/posts.json
但是,输出并没有告诉我是否支持 gzip:
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
X-Ua-Compatible: IE=Edge
Etag: "f6f6732c747466f75052f88b1eff393b"
Cache-Control: max-age=0, private, must-revalidate
X-Request-Id: 74ee0562c05adea679deb701f1b8fd88
X-Runtime: 0.004205
Content-Length: 0
Server: WEBrick/1.3.1 (Ruby/1.9.3/2012-04-20)
Date: Thu, 16 Aug 2012 23:33:25 GMT
Connection: Keep-Alive
我也试过curl的--compressed参数...
$ curl --compressed --head -H "Accept-Encoding: gzip" http://localhost:3000/posts.json
输出与前一个命令相同的标头信息。当我跑...
$ curl --compressed -H "Accept-Encoding: gzip" http://localhost:3000/posts.json
JSON 数据作为可读文本打印到控制台。我看不到压缩是否发生。也许,因为 curl 已经解压缩了响应?!
在线测试
我也试过在线测试HTTP Compression Test提到here。它确认 JSON 内容“未压缩”。第二个网站GIDZipTest 链接here 承认检测结果为阴性。
问题:
- 如何从 Rails 输出 gzip 压缩的 JSON?
- 如何配置 HTTP 客户端以请求 gzip 压缩数据?
- 当我在 Heroku (PostgreSQL) 上运行 Rails 服务器时,相同的配置是否仍然有效...?
经验教训
据我所知,我必须为 REST 服务器配置的只是 use Rack::Deflater。需要明确的是:我的代码中没有使用ActiveSupport::Gzip.compress()。如果有人感兴趣,这就是启用 GZIP 压缩时标头的样子。
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
X-Ua-Compatible: IE=Edge
Etag: "8170a04be41673bf25824256740a9460"
Cache-Control: max-age=0, private, must-revalidate
X-Request-Id: 700b9536f6a20164d31b8528bde423af
X-Runtime: 0.369337
Vary: Accept-Encoding
Content-Encoding: gzip
Server: WEBrick/1.3.1 (Ruby/1.9.3/2012-04-20)
Date: Tue, 21 Aug 2012 12:10:48 GMT
Content-Length: 20
Connection: Keep-Alive
现在我知道了神奇的关键字,很容易search and find articles on use Rack::Deflater。
【问题讨论】:
标签: android ruby-on-rails-3 json gzip httpclient