Below is an example using HttpClient library to retrieve the response of HTTP GET request. We start by creating an instance of CloseableHttpClient
class. We then define an HTTP GET request by create an instance of HttpGet
class and specify the Url of a website we are going to retrieve.
To execute the request we call the HttpClient.execute()
method and pass the HttpGet
as the arguments. This execution return an HttpResponse
object. From this response object we can read the content of response by accessing the getEntity().getContent()
which will give us an InputStream
to the content.
For more detail let’s see the code snippet below:
package org.kodejava.apache.http;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class HttpGetExample {
public static void main(String[] args) {
try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
HttpGet request = new HttpGet("https://httpbin.org/get?id=1");
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null) {
try (InputStream stream = entity.getContent()) {
BufferedReader reader =
new BufferedReader(new InputStreamReader(stream));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Maven Dependencies
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.14</version>
</dependency>
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024