This post originated from an RSS feed registered with Java Buzz
by Simon Brown.
Original Post: HttpClient - another great Jakarta Commons component
Feed Title: Simon Brown's weblog
Feed URL: http://www.simongbrown.com/blog/feed.xml?flavor=rss20&category=java
Feed Description: My thoughts on Java, software development and technology.
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 java.net 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)
};
postMethod.setRequestBody(data);
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.