【问题标题】:Android: Gzip/Http supported by default?Android:默认支持 Gzip/Http?
【发布时间】:2010-09-06 12:54:31
【问题描述】:

我正在使用下面显示的代码从我们打开 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;
      }

【问题讨论】:

    标签: android gzipstream


    【解决方案1】:

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

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

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

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-10-30
        • 1970-01-01
        • 2011-03-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-07
        相关资源
        最近更新 更多