Apache HTTPClient Get and Post

January 8, 2010

Here's examples of calling GET and POST requests using the Apache HTTPClient library

Performing a GET

This code performs a GET call:

HttpClient lClient = new HttpClient();
HttpMethod lMethod = new GetMethod(lUrlToCall);
int lCode = lClient.executeMethod(lMethod);
String lResponse = lMethod.getResponseBodyAsString();

Performing a POST

Similarly, this code performs a POST, passing in a parameter:

HttpClient lClient = new HttpClient();
PostMethod lMethod = new PostMethod(lUrlToCall);
NameValuePair[] lParams = { new NameValuePair("username", lUsername)};
lMethod.setRequestBody(lParams);

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

If the parameters list needs building up dynamically, build it in a List<NameValuePair> and then convert to an array using:

List<NameValuePair> lServiceParameters = this.getServiceParameters();
NameValuePair[] lParams = lServiceParameters.toArray(new NameValuePair[lServiceParameters.size()]);

SOAP style POST

This code performs a SOAP style POST, with data straight in the body rather than as a name/value pair.

PostMethod lMethod = new PostMethod(lUrl);
RequestEntity lEntity = new StringRequestEntity(lXml, "text/xml", "UTF-8");
lMethod.setRequestEntity(lEntity);
HttpClient lHttpClient = new HttpClient();
try
{
    int lResult = lHttpClient.executeMethod(lMethod);

    System.out.println("Response status code: " + lResult);
    System.out.println("Response body: ");
    System.out.println(lMethod.getResponseBodyAsString());
} 
finally 
{
    lMethod.releaseConnection();
}

References