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

发布于 2024-08-09 15:13:05 字数 923 浏览 2 评论 0原文

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

Hi I need to evaluate if a server supports gzip compression.

Therefore I want to set gzip as Accept-Encoding in my request and evaluate if the response of the server containts "Content-Encoding: gzip".

However I am not quite clear on how to do this with HTTPURLConnection. Especially when to query my Connection object about the response. I currently do:

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();

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

雪落纷纷 2024-08-16 15:13:05

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

Have a look at this OReilly article. It illustrates how to generate the request, and how to interrogate the response and then create the appropriate stream (normal or gzipped) dependent on what's being returned.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文