Skip to main content

HttpClient - another great Jakarta Commons component

Posted by simongbrown on October 6, 2003 at 12:58 PM PDT

I was putting TrackBack support into Pebble the other day and the found that the technical details of a TrackBack involve sending a HTTP POST request to the remote server. I've implemented HTTP POSTs before using the classes in the package, but rather than write all this code again, I thought that I'd take a look at Jakarta Commons HttpClient. What can I say ... this is another top notch component from the Commons project.

The following code shows how easy it is to make a HTTP POST with some name=value pairs and get the results back as a string.

      HttpClient httpClient = new HttpClient();
      PostMethod postMethod = new PostMethod(url);
      NameValuePair[] data = {
        new NameValuePair("name1", value1),
        new NameValuePair("namen", valuen)
      int responseCode = httpClient.executeMethod(postMethod);
      String responseBody = postMethod.getResponseBodyAsString();

As you can see, there's not much code here at all, and HTTP GETs are easier still! From start to finish, making use of this component took about five, maybe ten, minutes. If you find you need to access HTTP-based resources, take a look at HttpClient.

Related Topics >>