简体   繁体   English

如何使用Java URL和URL连接类打开网站

[英]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. 我正在尝试用Java创建一个基于GUI的程序,它有一个“提交”按钮,当点击它时,它会带你到一个网站。

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: 我已经在线阅读了URL和URLConnection类,并建立了与网站的连接,但程序没有打开链接...这是我到目前为止所做的:

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? 你可以使用像你在这个线程中看到的swing组件 - > Best Java / Swing浏览器组件?

Otherwise use this snippet found at http://andy.ekiwi.de/?p=1026 否则,请使用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);
        }
      }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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