Wednesday, January 14, 2015

Invoking NTLM authentication enabled service through Java

Invoking NTLM authentication enabled service through Java

Java API

The below program help us to invoke NTLM authentication enabled services.

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NTCredentials;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.HttpStatus;

public class NTLMAuthentication {

public String invokeService(String url, String soapMessage) {
String responseString = null;
try {

HttpClient client = new HttpClient();
PostMethod postMethod = new PostMethod(url);
postMethod.setRequestEntity(new StringRequestEntity(soapMessage,"text/xml","utf-8"));
postMethod.setRequestHeader("SOAPAction", "http://www.service.com/GetEmployeeData");
postMethod.setRequestHeader("Content-Type", "text/xml; charset=UTF-8");
NTCredentials credentials = new NTCredentials("username","password", "hostName", "domain");
client.getState().setCredentials(new AuthScope(null, -1, null), credentials);
int status = client.executeMethod(postMethod);
if (status == HttpStatus.SC_OK)
{
responseString = postMethod.getResponseBodyAsString();
}
} catch (Exception e) {

}
return responseString;

}

}



4 comments:

  1. Hi, I'm getting the following error:
    No credentials available for NTLM @www.com
    null

    Any help here?

    ReplyDelete
  2. Hi can you explain me more about the setCredentials method, it either shows no credentials available or failure to authenticate with www.com. Can u help me out here

    ReplyDelete
  3. Can you please share the jar file for this import org.apache.commons.httpclient.methods.PostMethod;

    ReplyDelete
  4. You can download the jar from here https://repo1.maven.org/maven2/commons-httpclient/commons-httpclient/3.1/commons-httpclient-3.1.jar, this was the earlier version of HTTPClient(3.1) try to use the latest versions

    ReplyDelete