2010-09-06 78 views
4

我使用下面显示的代码从我们的Gzip服务器打开数据。我的代码是否已经支持Gzip(也许这已经由android完成了,而不是由我的java程序完成),还是我必须添加/更改smth。?我如何检查它是否使用Gzip?对于我的观点,下载有点慢。Android:默认支持Gzip/Http?

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; 
     } 

回答

8

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

但是你可能需要发送标题:“接受编码:gzip”

您可以检查它是否真的工作在你的局域网使用嗅探器,或者在服务器上。您还可以检查响应标题,但这需要更改代码(最有可能的是,您必须在您的Web服务器上启用gzip)。

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

+0

对于LAN嗅探器+1。例如,您可以尝试Wireshark。 – 2010-09-06 13:04:43

0

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