SOAP with Apache HttpClient 4

June 18, 2013

Here's some example code for making a SOAP call with Apache's HttpClient 4.

HttpClient lHttpClient = new DefaultHttpClient();

// Setup proxy server to call through
HttpHost lProxy = new HttpHost("hostname", 1234);
lHttpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, lProxy);

 // Setup POST request
HttpPost lHttpPost = new HttpPost(pLenderUrl);

// Set SOAPAction header
lHttpPost.addHeader("SOAPAction", "http://tempuri.org/SubmitApplication");

 // Add XML to request, direct in the body - no parameter name
StringEntity lEntity = new StringEntity(pSoapCallXml, "text/xml", "utf-8");
lHttpPost.setEntity(lEntity);

// Execute POST   
HttpResponse lHttpResponse = lHttpClient.execute(lHttpPost);

 iif (lHttpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK)
{
  throw new RuntimeException("HTTP problems posting method " + lHttpResponse.getStatusLine().getReasonPhrase());
}

// Get hold of response XML 
lResponseXml = EntityUtils.toString(lHttpResponse.getEntity());

Tags: httpclient http proxy