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