如何区分 HTTPURLConnection 中的请求和响应?
您好,我需要评估服务器是否支持 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
请查看这篇 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.