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, ...
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));
It works for me.
Please check if you are using the right imports?
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
Following code should work,
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();
Are you sure using the java.net.URL
class? Check your import statements.
It may be more useful to use a http client library like such as this
There are more things like access denied , document moved etc to handle when dealing with http.
(though, it is unlikely in this case)
If you just want to open up the webpage, I think less is more in this case:
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"));
}
}
}
I found this question while Googling. Note that if you just want to make use of the URI's content via something like a string, consider using Apache's IOUtils.toString()
method.
For example, a sample line of code could be:
String pageContent = IOUtils.toString("http://maps.google.at/maps?saddr=4714&daddr=Marchtrenk&hl=de", Charset.UTF_8);