Contents

Make HTTP requests in Java

Writen by: David Vlijmincx

Introduction

In this tutorial, I will show you how to make an HTTP request in Java. I am going to use the HttpClient which was added in Java 11.

Get request

To create a request in Java we need to do the following three things:

  • Create a HttpClient
  • Build a request
  • Send the request

In the following example, I first create a HttpClient with HTTP version 1.1, which follows redirects and a timeout in case the server does not respond in time.

After creating the HttpClient I build the Get request I want to send. Using the HttpClient I then send the server and print the body of the response to the console.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
void get() throws IOException, InterruptedException {
    String url = "https://reqbin.com/echo/get/json";

    HttpClient client = HttpClient.newBuilder()
            .version(HttpClient.Version.HTTP_1_1)
            .followRedirects(HttpClient.Redirect.NORMAL)
            .connectTimeout(Duration.ofSeconds(20))
            .build();

    HttpRequest request = HttpRequest.newBuilder().GET().uri(URI.create(url)).build();
    HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

    System.out.println(response.body());
}

Post request

With a Post request, we send data to an endpoint. To send a Post request using the HttpClient we need to do the following steps:

  • Create a HttpClient
  • Create a body for the request
  • Build a request
  • Send the request with the body

In the following example, I create a Post request that sends a JSON payload to an endpoint. Line 4 shows the body that is going to be sent. The HttpClient is created at line 10 and is the same one as from the Get example.

At line 16 I create a BodyPublisher that is going to hold the body that I am going to send with the Post request. The client sends the request at line 25 and the response is printed to the console.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
void post() throws IOException, InterruptedException {
    String url = "https://httpbin.org/post";

    String body = """
            {
                "valueName": "value"
            }
            """;

    HttpClient client = HttpClient.newBuilder()
            .version(HttpClient.Version.HTTP_1_1)
            .followRedirects(HttpClient.Redirect.NORMAL)
            .connectTimeout(Duration.ofSeconds(20))
            .build();

    HttpRequest.BodyPublisher bodyPublisher = HttpRequest.BodyPublishers.ofString(body);

    HttpRequest request = HttpRequest
            .newBuilder()
            .POST(bodyPublisher)
            .header("Content-Type", "application/json")
            .uri(URI.create(url))
            .build();

    HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

    System.out.println(response.body());
}

Put request

The Put request looks very much like the Post example, except that the request builds a Put request on line 20.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
void put() throws IOException, InterruptedException {
    String url = "https://httpbin.org/put";

    String body = """
            {
                "valueName": "value"
            }
            """;

    HttpClient client = HttpClient.newBuilder()
            .version(HttpClient.Version.HTTP_1_1)
            .followRedirects(HttpClient.Redirect.NORMAL)
            .connectTimeout(Duration.ofSeconds(20))
            .build();

    HttpRequest.BodyPublisher bodyPublisher = HttpRequest.BodyPublishers.ofString(body);

    HttpRequest request = HttpRequest
            .newBuilder()
            .PUT(bodyPublisher)
            .header("Content-Type", "application/json")
            .uri(URI.create(url))
            .build();

    HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

    System.out.println(response.body());
}

Delete request

The Delete request looks very similar to a Get request. You still need to create a HttpClient, request, and send it. The only difference is that at line 12 which makes it a delete request.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
void delete() throws IOException, InterruptedException {
    String url = "https://httpbin.org/delete";

    HttpClient client = HttpClient.newBuilder()
            .version(HttpClient.Version.HTTP_1_1)
            .followRedirects(HttpClient.Redirect.NORMAL)
            .connectTimeout(Duration.ofSeconds(20))
            .build();

    HttpRequest request = HttpRequest
            .newBuilder()
            .DELETE()
            .uri(URI.create(url))
            .build();

    HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

    System.out.println(response.body());
}

Delete request with body

Out of the box, the Delete does not support a BodyPublisher as a parameter when you use the builder. To send a Delete request with a body you can use the method of the builder (line 20). The method allows you to set the HTTP method and a body.

In the following example, a delete request with a body is sent to the endpoint.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
void deleteWithBody() throws IOException, InterruptedException {
    String url = "https://httpbin.org/delete";

    HttpClient client = HttpClient.newBuilder()
            .version(HttpClient.Version.HTTP_1_1)
            .followRedirects(HttpClient.Redirect.NORMAL)
            .connectTimeout(Duration.ofSeconds(20))
            .build();

    String body = """
            {
                "valueName": "value"
            }
            """;

    HttpRequest.BodyPublisher bodyPublisher = HttpRequest.BodyPublishers.ofString(body);

    HttpRequest request = HttpRequest
            .newBuilder()
            .method("DELETE", bodyPublisher)
            .uri(URI.create(url))
            .build();

    HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

    System.out.println(response.body());
}

Conclusion

This tutorial gave you an overview of how to create Get, Post, Put, and Delete HTTP requests in Java 11 and higher. I covered the steps on how to create the httpClient, request, and send it to an endpoint. The last example showed how to send a body with HTTP methods that don't take a body parameter by default.