+1  A: 

Hi opensas. According to this page, you can use the built-in JRE classes, with the caveat that earlier versions of Java can only do this on a Windows machine.

However, if you are willing to live with a 3rd-party dependency, IMO Apache Commons HttpClient 3.x is the way to go. Here is the documentation for using authentication, including NTLM. In general, HttpClient is a much more functional library.

The latest version of HttpClient is 4.0, but apparently this version does not support NTLM this version requires a tiny bit of extra work.

Here is what I think the code would look like, although I haven't tried it:

HttpClient httpClient = new HttpClient();
httpClient.getState().setCredentials(AuthScope.ANY, new NTCredentials(user, password, hostPortionOfURL, domain));
GetMethod request = new GetMethod(url);
BufferedReader reader = new InputStreamReader(request.getResponseBodyAsStream());

Good luck.

Matt Solnit
Hey Matt, thanks a lot for your answer, but I wonder if it's possible to do this, with the buil-in JRE classes, using kerberos instead of ntlm... I mean, kerberos is not ptopietary stuff like NTLM...
opensas
Last I heard, the Apache client does NOT support NTLMv2. And they are reluctant to tap JCIFS because a) they claim it's LGPLv2 is not compatible with their license and b) they are generally are weary of MS stuff. But it does not matter because if you want to interop with Microsoft, NTLM is the common denominator of authentication mechanisms. Kerberos does not work if the client does not have access to a domain controller or if time sync is off or if DNS isn't quite right or ... etc.
Hi ioplex. I'm not sure where you heard this, but it is incorrect. Please check out the docs I linked to. I have successfully used NTLM with both HttpClient 3.x and with 4.0.
Matt Solnit
+1  A: 

Take a look at the SpnegoHttpURLConnection class in the SPNEGO HTTP Servlet Filter project. This project has some examples as well.

This project has a client library that pretty much does what you are doing in your example.

Take a look this example from the javadoc...

 public static void main(final String[] args) throws Exception {
     final String creds = "dfelix:myp@s5";

     final String token = Base64.encode(creds.getBytes());

     URL url = new URL("http://medusa:8080/index.jsp");

     HttpURLConnection conn = (HttpURLConnection) url.openConnection();

     conn.setRequestProperty(Constants.AUTHZ_HEADER
             , Constants.BASIC_HEADER + " " + token);

     conn.connect();

     System.out.println("Response Code:" + conn.getResponseCode());
 }
Pat Gonzalez