REST Template Using Apache HttpClient

Calling REST web services using Spring’s RestTemplate has been already covered in the other post. Here is a template which can be used out side of Spring. A generalize REST template using Apache’s HttpClient API.

package com.your.package.name;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URISyntaxException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;

public class RestClient {
	public static final int HTTP_OK = 200;
	public static final String SERVER_URL = "BASE URL OF THE REST SERVER";

	public static String doGet(final String url) throws HttpException,
			IOException, URISyntaxException {

		final HttpClient httpClient = new DefaultHttpClient();
		HttpConnectionParams
				.setConnectionTimeout(httpClient.getParams(), 10000);
		HttpGet httpget = new HttpGet(SERVER_URL + url);
		HttpResponse response = httpClient.execute(httpget);
		HttpEntity entity = response.getEntity();
		InputStream instream = entity.getContent();
		return read(instream);
	}

	public static String doPost(final String url, final String POSTText)
			throws URISyntaxException, HttpException, IOException {

		final HttpClient httpClient = new DefaultHttpClient();
		HttpConnectionParams
				.setConnectionTimeout(httpClient.getParams(), 10000);

		HttpPost httpPost = new HttpPost(SERVER_URL + url);
		StringEntity entity = new StringEntity(POSTText, "UTF-8");
		BasicHeader basicHeader = new BasicHeader(HTTP.CONTENT_TYPE,
				"application/json");
		httpPost.getParams().setBooleanParameter(
				"http.protocol.expect-continue", false);
		entity.setContentType(basicHeader);
		httpPost.setEntity(entity);
		HttpResponse response = httpClient.execute(httpPost);
		InputStream instream = response.getEntity().getContent();
		return read(instream);
	}

	public static boolean doPut(final String url, final String PUTText)
			throws URISyntaxException, HttpException, IOException {
		final HttpClient httpClient = new DefaultHttpClient();
		HttpConnectionParams
				.setConnectionTimeout(httpClient.getParams(), 10000);

		HttpPut httpPut = new HttpPut(SERVER_URL + url);
		httpPut.addHeader("Accept", "application/json");
		httpPut.addHeader("Content-Type", "application/json");
		StringEntity entity = new StringEntity(PUTText, "UTF-8");
		entity.setContentType("application/json");
		httpPut.setEntity(entity);
		HttpResponse response = httpClient.execute(httpPut);
		int statusCode = response.getStatusLine().getStatusCode();
		return statusCode == HTTP_OK ? true : false;
	}

	public static boolean doDelete(final String url) throws HttpException,
			IOException, URISyntaxException {
		final HttpClient httpClient = new DefaultHttpClient();
		HttpConnectionParams
				.setConnectionTimeout(httpClient.getParams(), 10000);

		HttpDelete httpDelete = new HttpDelete(SERVER_URL + url);
		httpDelete.addHeader("Accept",
				"text/html, image/jpeg, *; q=.2, */*; q=.2");
		HttpResponse response = httpClient.execute(httpDelete);
		int statusCode = response.getStatusLine().getStatusCode();
		return statusCode == HTTP_OK ? true : false;
	}

	private static String read(InputStream in) throws IOException {
		StringBuilder sb = new StringBuilder();
		BufferedReader r = new BufferedReader(new InputStreamReader(in), 1000);
		for (String line = r.readLine(); line != null; line = r.readLine()) {
			sb.append(line);
		}
		in.close();
		return sb.toString();
	}
}

And it can be used like

RestClient.doDelete("/registration/" + userToken);
RestClient.doGet("/me/profile?ct=" + userToken);

5 Responses to REST Template Using Apache HttpClient

  1. deromka says:

    Please note that in a multithreaded environment it you should use only one single instance of final static HttpClient httpClient = new DefaultHttpClient(); in RestClient class and use org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager

    // Create an HttpClient with the ThreadSafeClientConnManager.
    // This connection manager must be used if more than one thread will
    // be using the HttpClient.
    ThreadSafeClientConnManager threadSafeClientConnectionManager = new ThreadSafeClientConnManager();
    threadSafeClientConnectionManager.setMaxTotal(MAX_CONNECTIONS);
    this.httpClient = new DefaultHttpClient(threadSafeClientConnectionManager, params);

  2. Ali Aga says:

    Thank you for sharing. Your post helped me in my project.

  3. This is the appropriate weblog for anybody who wants to seek out out about this topic. You understand a lot its virtually onerous to argue with you (not that I truly would want…HaHa). You undoubtedly put a brand new spin on a subject thats been written about for years. Great stuff, just nice!

  4. WONDERFUL Post.thanks for share..more wait .. …

  5. uniwersytety says:

    Thanks for all your efforts on this blog. My mum enjoys going through internet research and it is easy to see why. We all hear all concerning the compelling ways you convey helpful guidance by means of your blog and as well as increase contribution from visitors on the theme then our favorite daughter has been becoming educated a great deal. Have fun with the rest of the new year. Your doing a pretty cool job.

Leave a comment