如何以编程方式下载Java网页我希望能够获取网页的html并将其保存到String,这样我就可以对它做一些处理了。此外,我如何处理各种类型的压缩。我将如何使用Java来做这件事呢?
3 回答
临摹微笑
TA贡献1982条经验 获得超2个赞
URL url = new URL(urlStr);HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// Cast shouldn't failHttpURLConnection.setFollowRedirects(true);
// allow both GZip and Deflate (ZLib) encodingsconn.setRequestProperty("Accept-Encoding", "gzip, deflate");
String encoding = conn.getContentEncoding();InputStream inStr = null;
// create the appropriate stream wrapper based on// the encoding typeif (encoding != null && encoding.equalsIgnoreCase("gzip")) {
inStr = new GZIPInputStream(conn.getInputStream());} else if (encoding != null && encoding.equalsIgnoreCase("deflate")) {
inStr = new InflaterInputStream(conn.getInputStream(),
new Inflater(true));} else {
inStr = conn.getInputStream();}conn.setRequestProperty ( "User-agent", "my agent name");
添加回答
举报
0/150
提交
取消
