Apache HTTP Client Example

<dependency>
 <groupId>org.apache.httpcomponents</groupId>
 <artifactId>httpclient</artifactId>
 <version>4.2.5</version>
 <scope>test</scope>
</dependency>
import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

/**
 * Reference: http://hc.apache.org/httpcomponents-client-ga/tutorial/html/fundamentals.html
 * 
 * @author Bhavani
 * @since 05/29/2013
 */
public class WSClient {

	public static String getData(String url, String content, String contentType) {

		StringEntity entity = new StringEntity(content, ContentType.create(
				contentType, "UTF-8"));

		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(url);
		httppost.setEntity(entity);

		try {

			ResponseHandler<byte[]> handler = new ResponseHandler<byte[]>() {
				public byte[] handleResponse(HttpResponse response)
						throws ClientProtocolException, IOException {
					HttpEntity entity = response.getEntity();
					if (entity != null) {
						return EntityUtils.toByteArray(entity);
					} else {
						return null;
					}
				}
			};

			byte[] response = httpclient.execute(httppost, handler);

			if (null == response)
				return null;
			else
				return new String(response);

		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return null;
	}
}

Check Apache documentation for latest features.
http://hc.apache.org/httpcomponents-client-ga/tutorial/html/index.html

Check repo for latest versions.
http://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s