我正在使用 HttpClient 4.1 下载网页。我想要一个压缩版本:
HttpGet request = new HttpGet(url);
request.addHeader("Accept-Encoding", "gzip,deflate");
HttpResponse response = httpClient.execute(request,localContext);
HttpEntity entity = response.getEntity();
response.getFirstHeader("Content-Encoding")
显示"Content-Encoding: gzip"
但是,entity.getContentEncoding()
为 null
。
如果我输入:
entity = new GzipDecompressingEntity(entity);
我得到:
java.io.IOException: Not in GZIP format
看起来结果页面是纯文本且未压缩,即使“Content-Encoding” header 显示它已被 gzip 压缩。
我已在多个网址(来自不同网站)上尝试过此操作,但得到了相同的结果。
如何获得网页的压缩版本?
最佳答案
如果您不希望 API 处理诸如解压缩之类的日常事务,请不要使用 HttpClient。
您可以使用基本的 URLConnection 类来获取压缩流,如以下代码所示:
public static void main(String[] args) {
try {
URL url = new URL("http://code.jquery.com/jquery-latest.js");
URLConnection con = url.openConnection();
// comment next line if you want to have something readable in your console
con.addRequestProperty("Accept-Encoding", "gzip,deflate");
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String l;
while ((l=in.readLine())!=null) {
System.out.println(l);
}
} catch (Exception e) {
e.printStackTrace();
}
}
关于java - 获取网页的压缩版本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10792811/