Java Network LAN Manager Authentication
Java Network LAN Manager Authentication (NTLM Authentication)
Java URL connections works fine from home/public networks. But these won't work from corporate networks due to proxy issues.To overcome this we set proxy properties in the system properties as below.
Proxy system properties
System.setProperty("http.proxySet", "true");
System.setProperty("java.net.useSystemProxies", "true");
System.setProperty("http.proxyHost", "host");
System.setProperty("http.proxyPort", "port");
System.setProperty("http.proxyUser", "user");
System.setProperty("http.proxyPassword", "password");
System.setProperty("java.net.useSystemProxies", "true");
System.setProperty("http.proxyHost", "host");
System.setProperty("http.proxyPort", "port");
System.setProperty("http.proxyUser", "user");
System.setProperty("http.proxyPassword", "password");
When you end up with the IOException : Bad response: (407Proxy Authentication required) it means a proxy authentication is required.
Java provides a solution to this using java.net.Autneticator
Write your own Authenticator to serve username and password of you closed network.
Custom Proxy Aunthenticator
ProxyAuthenticator.java
public class ProxyAuthenticator extends java.net.Authenticator{ private String user, password; public ProxyAuthenticator(String user, String password) { this.user = user; this.password = password; } protected java.net.PasswordAuthentication getPasswordAuthentication() { System.out.println("Authentication required."); return new PasswordAuthentication(user, password.toCharArray()); } }Before you open a URL connection add the below code
//set Authenticator Authenticator.setDefault(new ProxyAuthenticator("user", "password")); //Then set the usual stuff System.setProperty("http.proxyHost", "proxy.host"); System.setProperty("http.proxyPort", "port"); //Here goes URL processing URLConnection conn = url.openConnection();
This will pass through proxy authentication and connection will work fine.
In case you have an error in username/password - you can see the sop "Authentication required" will keep printed and you will end up with 403 Forbidden (bad password).
Make sure to include your domain in the username (domain\user). On a string it should be "domain\\user"
domain\\user - useful info
ReplyDelete