Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

http 407 proxy authentication required : how to handle in java code

System.setProperty("http.proxySet", "true");
System.setProperty("java.net.useSystemProxies", "true");
System.setProperty("http.proxyHost", "192.168.1.103");
System.setProperty("http.proxyPort", "3128");
System.setProperty("http.proxyUser", "user123");
System.setProperty("http.proxyPassword", "passwD123");

url = new URL("http://www.google.co.in");

every time when I am using this code IOException throws which say HTTP response code 407. HTTP 407 means proxy authentication required. why this problem is coming while I set proxyUser and proxyPassword. enter image description here
http 401 will occur if I put wrong password but it always give me 407, means my code does not take username and password. In above code user123 is username and passwD123 is password for proxy authentication.

like image 991
dayitv89 Avatar asked Jan 01 '13 19:01

dayitv89


1 Answers

http://blog.vinodsingh.com/2008/05/proxy-authentication-in-java.html

I found the solution thanks Mr. Vinod Singh.

Proxy authentication in Java

The usual corporate networks provide internet access via proxy servers and at times they require authentication as well. May applications do open the connections to servers which are external to the corporate intranet. So one has to do proxy authentication programmatically. Fortunately Java provides a transparent mechanism to do proxy authentications.

Create a simple class like below-

import java.net.Authenticator;

class ProxyAuthenticator extends Authenticator {

    private String user, password;

    public ProxyAuthenticator(String user, String password) {
        this.user = user;
        this.password = password;
    }

    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(user, password.toCharArray());
    }
}

and put these lines of code before your code opens an URLConnection-

Authenticator.setDefault(new ProxyAuthenticator("user", "password"));
System.setProperty("http.proxyHost", "proxy host");
System.setProperty("http.proxyPort", "port");

Now all calls will successfully pass through the proxy authentication.

like image 111
dayitv89 Avatar answered Sep 21 '22 13:09

dayitv89