Using Jakarta HttpClient to tunnel through NTLM Proxy
Following code in Java illustrates how Jakarta HttpClient package can be used to tunnel through NTLM proxy. This is handy if you want to download a page periodically and then serve it from your local web server. For this code to compile packages needed are httpclient 3.0, logging 1.0.5 and codec 1.3 (Later versions are also fine). All the jars for these packages must be in classpath while running the code below.
import java.io.*;
import java.net.Socket;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.GetMethod;
public class NTLMFetch
{
public static void main(String[] args) throws Exception
{
// Enable proxy to host logging
System.setProperty("org.apache.commons.logging.Log",
"org.apache.commons.logging.impl.SimpleLog");
System.setProperty("org.apache.commons.logging.simplelog.
showdatetime", "true");
System.setProperty("org.apache.commons.logging.simplelog.
log.httpclient.wire.header", "debug");
System.setProperty("org.apache.commons.logging.simplelog.
log.org.apache.commons.httpclient", "debug");
// Update this to the actual URL
String url = "http://mysite.com/index.html";
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod(url);
HostConfiguration hostConfig= client.getHostConfiguration();
// Update this to point to NTLM enabled proxy
hostConfig.setProxy("192.168.0.0", 80);
// Authenticate using NTLM
client.getState().setProxyCredentials(AuthScope.ANY,
new NTCredentials("userid","password","",""));
int statusCode = client.executeMethod(method);
System.out.println("Stat=" +HttpStatus.getStatusText(statusCode));
String strOutput = method.getResponseBodyAsString();
// Write the output to a local file
PrintWriter writer = new PrintWriter(new FileWriter("c:/down.html"));
writer.println(strOutput);
writer.close();
}
}
Presently with HttpClient only NTLMv1 is supported.
If you have a proxy server that is configured to accept NTLMv2 requests only, you are Out of Luck.
Hey Stephen, I didn’t knew that. Thanks!
Hi,
This is a great example, worked first time. However I’m trying to do something slightly different and I have to admit to being slightly out of my depth.
I have a java application that opens a ServerSocket listening on port 7777, this application sits behind a proxy server requiring NTLMv1 authorization. The above example can connect to this application and recieve a response. But the response is not HTTP its XML. My normal client connects to the application using Socket.
Is there a way to modify this example to work with Sockets, so that the Socket can authorize with the proxy and then connect as normal to the ServerSocket?
I can attach code if necessary, any help would be appreciated as I’ve extensively googled and not found what I’m looking for. Perhaps it is not possible, or most likely I dont really understand what I’m trying to do.
Cheers
Chris.