JAVA HttpUrlConnection 使用 GZIP 编码压缩

By default, when you make a request to URL, the response is not compressed.

默认情况下,当你在URL创建一个request 请求,response响应是不压缩的。

比如,代码:

import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpConnect {
    public static void main(String[] args) throws Exception {
      URL url = new URL("http://www.rgagnon.com/howto.html");
      HttpURLConnection con = (HttpURLConnection) url.openConnection();
      // con.setRequestProperty("Accept-Encoding", "gzip");
      System.out.println("Length : " + con.getContentLength());
      Reader reader = new InputStreamReader(con.getInputStream());
      while (true) {
        int ch = reader.read();
        if (ch==-1) {
          break;
        }
        System.out.print((char)ch);
      }
    }
}

From the response, we see that the length is 21740 bytes. 

从响应内容,我们看到长度是21740字节。

Length : 21740
<!DOCTYPE HTML>
<HTML>
    <head>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      <LINK REL="SHORTCUT ICON" HREF="http://www.rgagnon.com/favicon.ico">
      <META NAME="description"
            Content="Real's JAVA JAVASCRIPT WSH and PowerBuilder How-to pages with useful code snippets">
      <META NAME="keywords"
      Content="java,javascript,wsh,vbscript,how-to,powerbuilder">
...

By setting the Request Header "Accept" to "gzip", we are telling to the server that we want the response to be compressed if possible with the GZIP compression scheme. If it's not supported by the server then the response will be sent as plain text.

通过设置request header 的属性“Accept” 为“gzip”,我们告诉服务器在可能Gzip压缩的情况下我们想要服务器压缩响应。如果服务器不支持压缩应当以纯文本发送响应。

import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;


public class HttpConnect {
    public static void main(String[] args) throws Exception {
      URL url = new URL("http://www.rgagnon.com/howto.html");
      HttpURLConnection con = (HttpURLConnection) url.openConnection();
      con.setRequestProperty("Accept-Encoding", "gzip");
      System.out.println("Length : " + con.getContentLength());
      Reader reader = new InputStreamReader(con.getInputStream());
      while (true) {
        int ch = reader.read();
        if (ch==-1) {
          break;
        }
        System.out.print((char)ch);
      }
    }
}

Now the response length is 4865 but the content is not readable because we need to uncompress it!

现在响应长度是4865,但是内容不可读因为我们需要jie压缩!

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

安优小青和他的程序生活

我的文档对您有很大的帮助吗?

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值