如何使用Java从网站检索URL?

我想使用HTTP GET和POST命令从网站检索URL并解析HTML。 我该怎么做呢?

您可以将HttpURLConnection与URL结合使用。

URL url = new URL("http://example.com"); HttpURLConnection connection = (HttpURLConnection)url.openConnection(); connection.setRequestMethod("GET"); connection.connect(); InputStream stream = connection.getInputStream(); // read the contents using an InputStreamReader 

执行GET最简单的方法是使用内置的java.net.URL。 但是,如上所述,httpclient是正确的方法,因为它将允许您和其他人处理重定向。

对于解析html,您可以使用html解析器 。

勾选/批准的答案来自robhruska – 谢谢。 这显示了最基本的方法,它很简单,了解了进行简单URL连接所需的内容。 但是,长期策略是使用HTTP客户端来获得更高级和function丰富的方法来完成此任务。

谢谢大家,这里是快速回答:

 URL url = new URL("http://example.com"); HttpURLConnection connection = (HttpURLConnection)url.openConnection(); connection.setRequestMethod("GET"); connection.connect(); InputStream stream = connection.getInputStream(); // read the contents using an InputStreamReader 

使用http://hc.apache.org/httpclient-3.x/

我在一个项目中使用了JTidy并且运行良好。 其他解析器的列表在这里 ,但除了JTidy,我不知道它们中的任何一个。