Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open URL in Java to get the content

I´m searching for a opportunity to open a url in 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();

I found that way.

I added it in my program and the following error occurred.

The method openConnection() is undefined for the type URL

(by url.openConnection())

What is my problem?

I use a tomcat-server with servlets, ...

like image 590
alexander-fire Avatar asked Apr 02 '12 13:04

alexander-fire


People also ask

How do I read text from a URL?

Parsing text from a URL implies that you should: Create a URL object from the String representation. Use openStream() API method to open a connection to this URL and and get the InputStream for reading from that connection. Create a new BufferedReader, using a new InputStreamReader with the URL input stream.


2 Answers

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

    }
}
like image 121
Vaibs Avatar answered Sep 28 '22 10:09

Vaibs


String url_open ="http://javadl.sun.com/webapps/download/AutoDL?BundleId=76860";
java.awt.Desktop.getDesktop().browse(java.net.URI.create(url_open));
like image 30
miguepiscy Avatar answered Sep 28 '22 11:09

miguepiscy