Balazs Gunics
Balazs Gunics

Reputation: 2067

Opening an URL from java

we're writing an open-source jdbc driver for bigquery, and ran into the following problem:

We want to authorize our driver with Oauth 2 as an installed application. On windows xp, windows 7 x64, windows 7 x64 + RDP it works fine. But on the testbench which is a windows server 2008 R2 + RDP it fails.

Basically, we open a web browser, he logs in, we catch the reply, and authenticate the user.

Here's the code for the url opening:

    private static void browse(String url) {
    // first try the Java Desktop
    logger.debug("First try the Java Desktop");
    if (Desktop.isDesktopSupported()) {
        Desktop desktop = Desktop.getDesktop();
        if (desktop.isSupported(Action.BROWSE))
            try {
                desktop.browse(URI.create(url));
                return;
            } catch (IOException e) {
                // handled below
            }
    }
    // Next try rundll32 (only works on Windows)
    logger.debug("Try the rundll32");
    try {
        Runtime.getRuntime().exec(
                "rundll32 url.dll,FileProtocolHandler " + url);
        return;
    } catch (IOException e) {
        // handled below
    }
    // Next try browsers
    logger.debug("Try with browsers");
    BareBonesBrowserLaunch.openURL(url);
}

What i figured out is: BareBonesBrowserLaunch doesn't open the link, nor does the FileProtocolHandler.

The URL lenght is a little bit under 250character.

Any assistance would be appreciated!

Upvotes: 1

Views: 20817

Answers (3)

xproph
xproph

Reputation: 1231

Basically sounds good but here is another way if you want to open using specific browser (if more than one browser in the system)

String url = "http:/devmain.blogspot.com/";
String[] browsers = { "firefox", "opera", "mozilla", "netscape" }; // common browser names
String browser = null;
for (int count = 0; count < browsers.length && browser == null; count++)
  if (Runtime.getRuntime().exec(new String[] { "which", browsers[count] }).waitFor() == 0)
    browser = browsers[count]; // have found a browser
Runtime.getRuntime().exec(new String[] { browser, url }) // open using a browser

More details here: http://devmain.blogspot.com/2013/10/java-how-to-open-url-in-browser.html

Upvotes: 1

Santosh
Santosh

Reputation: 17893

Here is a suggestion from a different perspective. (Not sure if this is an option to you)

The problem that you are trying to solve is to use Oauth 2 and authentication mechanism. Instead of opening a browser capturing its response. There are already available libraries like Apache amber which do this purely in java.

Here is an official Amber Example that you can refer to.

Upvotes: 1

Andrea Turri
Andrea Turri

Reputation: 6500

Using java.net.HttpURLConnection

URL myURL = new URL("http://example.com/");
    URLConnection myURLConnection = myURL.openConnection();
    myURLConnection.connect();

Upvotes: 3

Related Questions