在Java中打开URL以获取内容

我正在寻找机会在java中打开一个url。

URL url = new URL("http://maps.google.at/maps?saddr=4714&daddr=Marchtrenk&hl=de"); InputStream is = url.openConnection().getInputStream(); BufferedReader reader = new BufferedReader( new InputStreamReader( is ) ); String line = null; while( ( line = reader.readLine() ) != null ) { System.out.println(line); } reader.close(); 

我找到了那种方式。

我在程序中添加了它,发生了以下错误。

 The method openConnection() is undefined for the type URL 

(通过url.openConnection())

我的问题是什么?

我使用带有servlet的tomcat-server,…

 public class UrlContent{ public static void main(String[] args) { URL url; try { // get URL content String a="http://localhost:8080/TestWeb/index.jsp"; url = new URL(a); URLConnection conn = url.openConnection(); // open the stream and put it into BufferedReader BufferedReader br = new BufferedReader( new InputStreamReader(conn.getInputStream())); String inputLine; while ((inputLine = br.readLine()) != null) { System.out.println(inputLine); } br.close(); System.out.println("Done"); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } 
 String url_open ="http://javadl.sun.com/webapps/download/AutoDL?BundleId=76860"; java.awt.Desktop.getDesktop().browse(java.net.URI.create(url_open)); 

这个对我有用。 请检查您是否使用了正确的import产品?

 import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; 

以下代码应该工作,

 URL url = new URL("http://maps.google.at/maps?saddr=4714&daddr=Marchtrenk&hl=de"); InputStream is = url.openConnection().getInputStream(); BufferedReader reader = new BufferedReader( new InputStreamReader( is ) ); String line = null; while( ( line = reader.readLine() ) != null ) { System.out.println(line); } reader.close(); 

你确定使用java.net.URL类吗? 检查您的import语句。

使用像这样的http客户端库可能更有用

在处理http时,还有更多的东西,如访问被拒绝,文档移动等。

(但是,在这种情况下不太可能)

如果你只想打开网页,我认为在这种情况下更少:

 import java.awt.Desktop; import java.net.URI; //Note this is URI, not URL class BrowseURL{ public static void main(String args[]) throws Exception{ // Create Desktop object Desktop d=Desktop.getDesktop(); // Browse a URL, say google.com d.browse(new URI("http://google.com")); } } }