java - 如何区分 HTTPURLConnection 中的请求和响应?

标签 java httpurlconnection content-encoding

您好,我需要评估服务器是否支持 gzip 压缩。

因此,我想在请求中将 gzip 设置为 Accept-Encoding,并评估服务器的响应是否包含“Content-Encoding: gzip”。

但是我不太清楚如何使用 HTTPURLConnection 执行此操作。特别是当查询我的 Connection 对象的响应时。我目前正在做:

HttpURLConnection con = (HttpURLConnection) feedurl.openConnection();
    con.setRequestProperty("Accept-Encoding", "gzip");
    System.out.println("Current Accept-Encoding: "+con.getRequestProperty("Accept-Encoding"));
    //check the response for the content-size
    float feedsize = con.getContentLength()/1024f;
    //the server uses transfer-encoding=chunked and does not specify
    //a content length
    if(con.getContentLength()==-1)
    {
        //count the content size manually
                    CountingInputStream counter = new CountingInputStream(con.getInputStream());
        while(counter.read()!=-1)
        {}
        feedsize=counter.getCount()/1024f;
    }
    con.disconnect();

最佳答案

看看this OReilly article 。它说明了如何生成请求,以及如何询问响应,然后根据返回的内容创建适当的流(正常或压缩)。

关于java - 如何区分 HTTPURLConnection 中的请求和响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1681081/

相关文章:

java - Android:将 httpURLConnection 连接到服务器

android - 自签名证书异常 Hostname Verification failed

java - 如何获取正确的外部 SDCard 位置

Java:父类(super class)中的 ArrayList

java - Mockito when().thenReturn 不必要地调用该方法

asp.net - 压缩 CSS 的 IIS 内容类型错误

php - 当 fastcgi 后端偶尔提供带有内容编码的 gzip 时,如何禁用 Nginx 双 gzip 编码?

java - 使用 StringBuffer 值将列添加到 CSV 文件 (Java)

java - 在正文中使用 application/x-www-form-urlencoded 的 400 错误白色 Java Post

http:客户端的最低内容编码支持?