Http Request and Http Response

The JDK client, with no extra dependency, is Java HttpClient GET and POST. This page is Apache HttpClient. POST is in How to send POST HTTP request.

First of all we need to add a Maven dependency for Apache Http Client

Apache Http Client Maven dependency

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.1</version>
</dependency>

GET HTTP Request

This is how to create a simple GET HTTP request

HttpGet get = new HttpGet(url);

Here url is the url of the web service endpoint or the url of the web site page. For example https://www.google.com

You also can add headers to the request.

For example you want to pretend a browser

Header headers[] = { new BasicHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.3; Win64; x64) 
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36")};
get.setHeaders(headers);

or you want to call REST API an get a response in JSON fromat

Header headers[] = { new BasicHeader("Accept", "application/json")};
get.setHeaders(headers);

HTTP client with Apache Http Components

Now you have to create a HTTP client, send a request, get a response and close the HTTP client

response.getEntity().getContent()

We access the response content with response.getEntity().getContent().

CloseableHttpClient client = HttpClients.custom().build();
HttpResponse response = client.execute(get);
String result = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8);
response.getEntity().getContent().close();

If you expect the response body to be a JSON then you can convert that to Java object.

Gson gson = new Gson();
User user = gson.fromJson(result, User.class);

See more about How to convert JSON to Java Object.

Response Code

You also can verify the response code if you need.

int responseCode = response.getStatusLine().getStatusCode();
String statusPhrase = response.getStatusLine().getReasonPhrase();

All pieces together

String url = "https://www.some-web-service/api/endpoint";
HttpGet get = new HttpGet(url);

Header headers[] = { new BasicHeader("Accept", "application/json")};
get.setHeaders(headers);

CloseableHttpClient client = HttpClients.custom().build();
HttpResponse response = client.execute(get);
    
String result = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8);

Gson gson = new Gson();
User user = gson.fromJson(result, User.class);
        
int responseCode = response.getStatusLine().getStatusCode();
String statusPhrase = response.getStatusLine().getReasonPhrase();

response.getEntity().getContent().close();

You may also find these posts interesting: