Open a URL in the default browser in Java

Open a URL in the default browser in Java

When developing a Java desktop or command-line application, you may need to prompt the operating system to open a URL. For instance, to login or approve authentication (OAuth). One approach is to print out the URL and ask the user to copy/paste it. A better alternative is opening that in the user’s default browser automatically. In this tutorial, we cover how to open a URL in the default browser in Java programs.

Although it may sound like a trivial and straightforward task, it is not since each operating system has its mechanism for launching an application. For instance, in Windows, rundll32.exe url.dll is responsible for opening a URL in the default browser, while macOS leverages on open command.

Having said that, thanks to rich built-in Java APIs and available libraries, you don’t need to worry about the underlying mechanism (unless in extreme cases). We cover three ways of opening a URL in the default browser in this article: using AWT, JavaFX library, and custom code.

Open a URL with AWT

To work with AWT you don’t need to add any libraries to your project. All you need to do is to create a method as follows.

Open a URL with JavaFX

In the case of JavaFX, it’s even simpler and more abstract. Though under the hood, it still uses AWT.

Add the JavaFX dependency.

Then this code.

Open a URL without any libraries (custom code)

If you don’t want to use any libraries or AWT doesn’t work due to compatibility issues with your project, such as generating a native image with GraalVM, you can use this approach.

All we have to do is detect the operating system, then use the getRuntime().exec to execute a command responsible for opening a URL in the default browser.

A note on AWT compatibility (with GraalVM)

As you may know, AWT APIs are ancient. They have a history of causing some troubles in different scenarios and even with other libraries.

In our case, AWT doesn’t work when generating GraalVM Native Image. There are some GitHub issues around this topic that you can follow to see the progress, this, and this. Until then, the best alternative is to use the custom code as other Java libraries that support the functionality to open a URL in the default browser are also using AWT under the hood.

Conclusion

In this tutorial, we covered how to open a URL in the default browser in Java using three methods, AWT, JavaFX, and custom code namely. Under normal circumstances, one does not need to use the custom code approach unless one strives to build a native image using GraalVM.

For more related content, check our Java category.

Inline/featured images credits