How to Create a HTTP Client

In this tutorial I am going to tell you how to access HTTP resources from a java class. I am using apache HTTP Client 4.2 libraries. I have developed a simple demo web app using HTTP GET method. In that application when you pass a sentence as parameter it gives how many words are in that sentence. You can check that web app following URL.

First you need to download the required library files from click on this link. Download the HttpClient 4.1.2(GA) binary file according to your operating system. If you are using linux machine download 4.1.2.tar.gz or if you are using windows machine download file.  Then extract the zip file and go to lib folder. In there add httpclient and httpcore jar files to your libry path.

If you are using netbeans in your project folder right click on libries folder and add those jar files. If you are using eclipse right click on your project folder and add jar files to build path. I am not going to explain detail about it. You can find many online tutorials regarding this matter.

Okay now the interesting part. Now you can coding. By using this java class you can take the content of  web page. In my demo app it returns the number of words in the sentence. So you can easily assign it to string value and use it in your project .

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

public class HttpClientDemo {

public static void main(String args[]) {

HttpClient client = new DefaultHttpClient();
BufferedReader in = null;

try {

HttpGet httpget = new HttpGet(URL);
HttpResponse response = client.execute(httpget);
HttpEntity entity = response.getEntity();
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
String page = sb.toString();
String mean[]=page.substring(6, page.length()).split(", ");
} catch (IOException ie) {
} finally {
try {
} catch (IOException ex) {

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s