4

我正在使用下面显示的代码从我们打开 Gzip 的服务器获取数据。我的代码是否已经支持 Gzip(也许这已经由 android 而不是由我的 java 程序完成)还是我必须添加/更改 smth。?如何检查它是否使用 Gzip?在我看来,下载速度有点慢。

private static InputStream OpenHttpConnection(String urlString) throws IOException {
        InputStream in = null;
        int response = -1;

        URL url = new URL(urlString);
        URLConnection conn = url.openConnection();

        if (!(conn instanceof HttpURLConnection))
          throw new IOException("Not an HTTP connection");

        try {
          HttpURLConnection httpConn = (HttpURLConnection) conn;
          httpConn.setAllowUserInteraction(false);
          httpConn.setInstanceFollowRedirects(true);
          httpConn.setRequestMethod("GET");
          httpConn.connect();

          response = httpConn.getResponseCode();
          if (response == HttpURLConnection.HTTP_OK) {
            in = httpConn.getInputStream();
            if(in == null)
              throw new IOException("No data");
          }
        } catch (Exception ex) {
          throw new IOException("Error connecting");
        }
        return in;
      }
4

2 回答 2

8

任何现代 http lib 都支持 Gzip 压缩,它是多年来标准的一部分。

但您可能需要发送标头:“Accept-Encoding: gzip”

您可以在 LAN 或服务器上使用嗅探器检查它是否真的有效。您还可以检查响应标头,但这需要更改代码(很可能,您必须在网络服务器上打开 gzip)。

此外,您可以下载 10Mb 的空间文件。使用 gzip 会更快 :-)

于 2010-09-06T12:57:48.870 回答
0

当您使用 HttpURLConnection 类与 HTTP 协议一起工作时,“Accept-Encoding:gzip”字段会自动添加到传出请求中,并会处理相应的响应。(见文档

于 2012-11-01T10:59:05.050 回答