为了账号安全,请及时绑定邮箱和手机立即绑定

如何以编程方式下载Java网页

如何以编程方式下载Java网页

qq_笑_17 2019-07-06 15:27:53
如何以编程方式下载Java网页我希望能够获取网页的html并将其保存到String,这样我就可以对它做一些处理了。此外,我如何处理各种类型的压缩。我将如何使用Java来做这件事呢?
查看完整描述

3 回答

?
临摹微笑

TA贡献1982条经验 获得超2个赞

Bill的回答是非常好的,但是您可能想对请求做一些事情,比如压缩或用户代理。下面的代码演示如何对请求进行各种类型的压缩。

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


查看完整回答
反对 回复 2019-07-06
  • 3 回答
  • 0 关注
  • 343 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号