Showing posts with label simple solutions. Show all posts
Showing posts with label simple solutions. Show all posts

Wednesday, July 29, 2009

Accessing protected URL in Java

Come through an elegant code yesterday. Somehow the content needs to be accessed from the database server which is password protected. A simple URL query would fetch the content. I've tried Apache commons. I could managed to access the content via plain java.net classes works for me pretty smoothly.

here is how

Authenticator.setDefault(new MyAuthenticator("user","password"));

URL url = new URL("http://localhost:5300/database?_query='for $a in collection('test')/types return $a'");
InputStream resultStream =url.openStream();

And the simple inner class
class MyAuthenticator extends Authenticator {
private String username, password;

public MyAuthenticator(String username, String password) {
this.username = username;
this.password = password;
}

// This method is called when a password-protected URL is accessed
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password.toCharArray());
}
}

Are there any better way?