【问题标题】:Java: Opening a URL with an IP inJava:打开带有 IP 的 URL
【发布时间】:2013-04-04 10:38:23
【问题描述】:

我正在构建一个网络爬虫。 Having read this我知道DNS解析很慢,所以我们应该分离出DNS Resolver。

所以说你有 字符串 urlString http://google.com 然后,您可以通过执行将其转换为 ip

URL url = new URL(urlString)
InetAddress ip = InetAddress.getByName(url.getHost());

但是你如何下载实际的网站本身呢?

使用 url,我们可以像这样:

String htmlDocumentString = new Scanner(new url.openStream(), "UTF-8").useDelimiter("\\A").next();

但是如果我们想使用解析后的IP,我们是否必须手动重构带有ip的URL?没有url.setHost()方法,看起来有点乱?

【问题讨论】:

  • "分离出 DNS 解析器?"我不明白重点。是的,DNS 解析会增加开销,但我看不出“将其分离”如何让您的网络爬虫更快。
  • 最简单的方法是拥有一个本地 DNS 缓存,因为当您进行 URL 内容加载时,许多服务器依赖于带有域的 VirtualHost。如果您直接请求 IP,您将无法获得正确的内容。

标签: java url ip


【解决方案1】:

从 URL 读取很简单:

public class URLReader {
public static void main(String[] args) throws Exception {

    URL oracle = new URL("http://www.oracle.com/");
    BufferedReader in = new BufferedReader(
    new InputStreamReader(oracle.openStream()));

    String inputLine;
    while ((inputLine = in.readLine()) != null)
        System.out.println(inputLine);
    in.close();
}

取自:http://docs.oracle.com/javase/tutorial/networking/urls/readingURL.html

【讨论】:

    【解决方案2】:

    试试这个:

      URL oracle = new URL("http://www.oracle.com/");
      URLConnection urlc = oracle.openConnection();
      urlc.setDoInput(true);
      urlc.setRequestProperty("Accept", "text/text");
      InputStream inputStream = urlc.getInputStream();
      String myString = IOUtils.toString(inputStream, "UTF-8");
    

    ...使用上面 Apache Commons 的 IOUtils:

    http://commons.apache.org/io/api-1.4/org/apache/commons/io/IOUtils.html#toString(java.io.InputStream,%20java.lang.String)

    【讨论】:

      猜你喜欢
      • 2015-10-27
      • 1970-01-01
      • 2023-03-25
      • 2014-08-20
      • 1970-01-01
      • 1970-01-01
      • 2015-10-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多