在 Java 中打开 URL 以获取内容

2022-09-03 08:40:45

我正在寻找一个用java打开网址的机会。

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

(by url.openConnection())

我的问题是什么?

我使用带有servlet的tomcat服务器,...


答案 1
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();
        }

    }
}

答案 2
String url_open ="http://javadl.sun.com/webapps/download/AutoDL?BundleId=76860";
java.awt.Desktop.getDesktop().browse(java.net.URI.create(url_open));