How To Use HttpClient

JavaIO

This java based tutorial is designed to provide a basic overview of how to use HttpClient.

Downloaded HttpClient and dependencies listed below that are required to put them on your classpath.

The general process for using HttpClient consists of a number of steps:

  • Create an instance of HttpClient.
  • Create an instance of one of the methods (GetMethod in this case). The URL to connect to is passed in to the the method constructor.
  • Tell HttpClient to execute the method.
  • Read the response.
  • Release the connection.
  • Deal with the response.
package com.jkoder.http;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
 
public class HttpClientExample {
 
	public static void main(String[] args) throws Exception {
 
		HttpClient client = new HttpClient();
		GetMethod method = new GetMethod("jkoder.com");
		
		// Provide custom retry handler is necessary
		method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));

		try {
			// Execute the method.
			int statusCode = client.executeMethod(method);
			//If status code is not 200.
			if (statusCode != HttpStatus.SC_OK) {
				System.err.println("Method failed: " + method.getStatusLine());
			}

			// Read the response body.
			byte[] responseBody = method.getResponseBody();
			System.out.println(new String(responseBody));

		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			method.releaseConnection();
		}
	}
}