HttpClient v3 HTTP Authentication

July 25, 2012

I needed to use HttpClient 3 to POST to a web service that was protected with HTTP security. This means I need to pass in the credentials as part of the call.

The following code was used for this:

String lServiceHost = lUrl.substring("https://".length());
lServiceHost = lServiceHost.substring(0, lServiceHost.indexOf("/"));

HttpClient lClient = new HttpClient();
Credentials lCredentials = new UsernamePasswordCredentials(lUsername, lPassword);
lClient.getState().setCredentials(new AuthScope(lServiceHost, 80, AuthScope.ANY_REALM), lCredentials);
PostMethod lMethod = new PostMethod(lUrl);
RequestEntity lEntity = null;

try
{
  lEntity = new StringRequestEntity(lCallXml, "text/xml", "UTF-8");
}
catch (UnsupportedEncodingException lException)
{
  throw new RuntimeException("Unsupported Encoding UTF-8", lException);
}

lMethod.setRequestEntity(lEntity);

String lReturn = null;

try
{
  int lCode = lClient.executeMethod(lMethod);
  lReturn = lMethod.getResponseBodyAsString();
  System.out.println(lReturn);

  if (lCode != 200)
  {
    throw new RuntimeException("Problems calling HTTP POST [" + lCode + "]");
  }

  lReturn = lMethod.getResponseBodyAsString();
}
catch (HttpException lEx)
{
  throw new RuntimeException("Problems calling service, underlying problem is " + lEx.getMessage(), lEx);
}
catch (IOException lEx)
{
  throw new RuntimeException("Problems calling service, underlying problem is " + lEx.getMessage(), lEx);
}