Http Client is an API in Java that can be used to send HTTP requests like GET, POST, DELETE, and PUT and receive HTTP responses. HTTP Client API provides us with the functionality of both synchronous and asynchronous requests. To create a simple GET request, follow the following steps:
If we have a maven project, then we need to add the httpclient
dependency in pom.xml
:
<dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.10</version></dependency>
HttpClient
objectFor request, we will need an HttpClient
object. The createDefault()
creates a ClosableHTTPClient
object with the default configuration.
HttpClient httpClient = HttpClients.createDefault();
For multiple requests, it is recommended to use the same instance of HTTPClient
GET
requestThe GET
request is used to request data from a server. It shouldn’t change the state of any resource on the server. We can create a GET
request using HTTPGet
like this:
HttpGet httpget = new HttpGet("https://dummy.restapiexample.com/api/v1/employees");
Or we can also build a request using the HttpRequest.newBuilder()
like this:
HttpRequest request = HttpRequest.newBuilder().uri(new URI("https://dummy.restapiexample.com/api/v1/employees")).version(HttpClient.Version.HTTP_2).headers("key1", "value1", "key2", "value2").GET().build();
We can specify five parameters while creating a new HTTPRequest:
URI of the server
HTTP headers
HTTP protocol version
HTTP request type
Timeout for HTTP request
We can also add a request body in HTTP POST
, PUT
, or DELETE
request.
Next, we’ll send our HTTP request and read a response from it:
HttpResponse httpresponse = httpclient.execute(httpget);Scanner sc = new Scanner(httpresponse.getEntity().getContent());//Printing the status lineSystem.out.println(httpresponse.getStatusLine());while(sc.hasNext()) {System.out.println(sc.nextLine());}
Here is a complete project with a sample GET
request using HTTP client API:
package com.educative; import java.io.IOException; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; public class App { public static void main( String[] args ) { try { sendGetRequest(); } catch (Exception e) { System.out.println(e.toString()); } } private static int sendGetRequest() throws IOException, ClientProtocolException { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet httpget = new HttpGet("https://dummy.restapiexample.com/api/v1/employees"); CloseableHttpResponse httpResponse = httpClient.execute(httpget); int statusCode = httpResponse.getStatusLine().getStatusCode(); System.out.println("Status Code: "+ statusCode); System.out.println("Response of GET request:"+ EntityUtils.toString(httpResponse.getEntity())); return statusCode; } }
Line 26: Creates a ClosableHttpClient
instance with createDefault()
method.
Line 28: Creates a HTTPGet
request with the get request URL.
Line 30: Executes the get request.
Line 34: Prints the response code received from the server.
Line 36: Prints the response of get request using EntityUtils
.
Free Resources