简体   繁体   中英

How to open website using Java URL and URL connection class

I am trying to create a GUI-based program in Java that has a 'Submit' button and when clicked, it takes you to a website.

I have read about the URL and URLConnection classes online and the connection to the website is established but the program does not open the link... This is what I have so far:

if(command.equals("Submit data"))
    {
        try {
            URL myURL = new URL("http://google.com/");
            URLConnection myURLConnection = myURL.openConnection();
            myURLConnection.connect();
        } 
        catch (IOException t) {   
            // openConnection() failed
            // ...
        }
}

The connection seems to be established but I want the program to open up the browser and take to the website.. I've tried everything and no luck.. Thank you

You could either used a swing component like you can see in this thread --> Best Java/Swing browser component?

Otherwise use this snippet found at http://andy.ekiwi.de/?p=1026

public void openUrl(String url) throws IOException, URISyntaxException {
  if(java.awt.Desktop.isDesktopSupported() ) {
        java.awt.Desktop desktop = java.awt.Desktop.getDesktop();

        if(desktop.isSupported(java.awt.Desktop.Action.BROWSE) ) {
          java.net.URI uri = new java.net.URI(url);
              desktop.browse(uri);
        }
      }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM