【问题标题】:How do I differentiate between request and response in an HTTPURLConnection?如何区分 HTTPURLConnection 中的请求和响应?
【发布时间】:2009-11-05 14:58:40
【问题描述】:

您好,我需要评估服务器是否支持 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();

【问题讨论】:

    标签: java httpurlconnection content-encoding


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2013-07-26
      • 2011-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多