Sunday, February 28, 2010

Setting Proxy Authentication in Java (weblogic.net.http.HttpUnauthorizedException: Proxy or Server Authentication Required)

weblogic.net.http.HttpUnauthorizedException: Proxy or Server Authentication Required
 at weblogic.net.http.HttpURLConnection.getAuthInfo(HttpURLConnection.java:284)
 at weblogic.net.http.HttpURLConnection.getInputStream(HttpURLConnection.java:455)
 at weblogic.net.http.SOAPHttpURLConnection.getInputStream(SOAPHttpURLConnection.java:36)
 at com.google.api.GoogleAPI.retrieveJSON(GoogleAPI.java:112)
 ... 45 more
I encountered the above error while attempting to test my Oracle ADF sample application that integrates with the Google Translate behind a proxy. I believe this error applies when your application tries to access the internet while behind a firewall that requires proxy authentication.

Below are the steps that resolved the issue above:
  1. Extend java.net.Authenticator class and override the getPasswordAuthentication() method.
  2. Set System properties for the http:proxyHost, http:proxyPort
  3. Set your custom authenticator above as the default authenticator.
  4. Modify the instantiation of the URL
Below is my custom authenticator:
package soadev.blogspot.googletranslateapi.common;

import java.net.Authenticator;
import java.net.PasswordAuthentication;

public class MyAuthenticator extends Authenticator {
    private String username;
    private String password;
    public MyAuthenticator(String username, String password){
        this.username = username;
        this.password = password;
    }
    public PasswordAuthentication getPasswordAuthentication () {
        return new PasswordAuthentication (username, password.toCharArray());
    }

}
Below are the code snippets (as it applies to my case) that illustrates the steps above:
    System.setProperty("http.proxyHost", "myproxy");             
    System.setProperty("http.proxyPort", "8080");
    Authenticator.setDefault (new MyAuthenticator("XXXXXX\\username","password"));
Below is how I instantiate the external URL to be accessed:
...
final URL url = new URL(null, "http://your_external_URL", new sun.net.www.protocol.http.Handler());
notes for readers of my blogpost on leveraging the google translate api: To run your test behind proxy, you need to modify the execute() method of the Translate class to reflect the proper way of instantiating the URL.

Cheers!
pino

1 comment:

  1. Hi,
    do you have any clues, it doesnt work for me when using JaxWsProxyFactoryBean in my spring configuration. could you pls read the thread and share your thoughts pls.
    http://forum.springsource.org/showthread.php?140755-Using-JaxWsProxyFactoryBean-with-timeout-interent-proxy-and-host-details

    ReplyDelete