首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在Java中以编程方式下载网页

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

Stack Overflow用户
提问于 2008-10-26 20:16:18
回答 7查看 205K关注 0票数 120

我希望能够获取网页的html并将其保存到String,这样我就可以对其进行一些处理。另外,我如何处理各种类型的压缩。

我该如何使用Java来做这件事呢?

EN

回答 7

Stack Overflow用户

回答已采纳

发布于 2008-10-26 21:09:39

下面是一些使用Java的URL类测试过的代码。不过,我建议在处理异常或将它们向上传递到调用堆栈方面做得比我在这里做得更好。

代码语言:javascript
复制
public static void main(String[] args) {
    URL url;
    InputStream is = null;
    BufferedReader br;
    String line;

    try {
        url = new URL("http://stackoverflow.com/");
        is = url.openStream();  // throws an IOException
        br = new BufferedReader(new InputStreamReader(is));

        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
    } catch (MalformedURLException mue) {
         mue.printStackTrace();
    } catch (IOException ioe) {
         ioe.printStackTrace();
    } finally {
        try {
            if (is != null) is.close();
        } catch (IOException ioe) {
            // nothing to see here
        }
    }
}
票数 113
EN

Stack Overflow用户

发布于 2010-04-06 13:17:00

Bill的回答非常好,但您可能希望对请求执行一些操作,如压缩或用户代理。下面的代码展示了如何对请求进行各种类型的压缩。

代码语言:javascript
复制
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // Cast shouldn't fail
HttpURLConnection.setFollowRedirects(true);
// allow both GZip and Deflate (ZLib) encodings
conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
String encoding = conn.getContentEncoding();
InputStream inStr = null;

// create the appropriate stream wrapper based on
// the encoding type
if (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();
}

要同时设置用户代理,请添加以下代码:

代码语言:javascript
复制
conn.setRequestProperty ( "User-agent", "my agent name");
票数 27
EN

Stack Overflow用户

发布于 2014-05-30 18:30:16

上面提到的所有方法都不会下载在浏览器中出现的网页文本。现在很多数据都是通过html页面中的脚本加载到浏览器中的。上面提到的技术都不支持脚本,它们只下载html文本。HTMLUNIT支持javascripts。因此,如果你想下载在浏览器中显示的网页文本,那么你应该使用HTMLUNIT

票数 9
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/238547

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档