Skip to main content
查利博客

Java 11 HTTP Client Examples

As of Java SE 11, the language provides a new HTTP client API that aims at removing the HttpURLConnectionAPI which is low level and not user-friendly. The API supports HTTP 1.1/2 and is completely asynchronous. This article shows you how to use the new Java 11 HTTP Client APIs to send both synchronous and asynchronous HTTP GET, POST, PUT, DELETE and PATCH requests. For further information about different types of HTTP requests, you can check my previous article here.

Create a java.net.http.HttpClient #

The java.net.http.HttpClient class is responsible for sending HTTP requests and receving HTTP responses. An HttpClient is created through a builder which can be used to configure per-client state. For instance, the protocol version (HTTP 1.1 and HTTP 1.2), timeout, a proxy, etc. Once built, it is immtutable.

HttpClient Example:

mport java.net.Authenticator;
import java.net.CookieHandler;
import java.net.ProxySelector;
import java.net.http.HttpClient;
import java.net.http.HttpClient.Redirect;
import java.time.Duration;
import java.util.concurrent.Executors;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLParameters;

public class HttpClientExample {
  public HttpClientExample() throws Exception {
  }

  private final HttpClient httpClient = HttpClient.newBuilder()
      .authenticator(Authenticator.getDefault())
      .connectTimeout(Duration.ofSeconds(30))
      .cookieHandler(CookieHandler.getDefault())
      .executor(Executors.newFixedThreadPool(2))
      .followRedirects(Redirect.NEVER)
      .priority(1)
      .proxy(ProxySelector.getDefault())
      .sslContext(SSLContext.getDefault())
      .sslParameters(new SSLParameters())
      .version(HttpClient.Version.HTTP_2)
      .build();
}

Synchronous Examples #

GET REQUEST #

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class GetRequest {
  public static void main(String[] args) throws IOException, InterruptedException {
    HttpRequest getRequest = HttpRequest.newBuilder()
        .GET()
        .uri(URI.create("http://localhost:8080/user/1"))
        .build();

    HttpResponse<String> response = HttpClient.newHttpClient().send(getRequest, HttpResponse.BodyHandlers.ofString());
    System.out.println(response.statusCode());
    System.out.println(response.body());
  }
}

Output

200
{"username":"caizhenhua","password":"123"}

POST REQUEST #

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpHeaders;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpRequest.BodyPublishers;

public class PostRequest {
  public static void main(String[] args) throws IOException, InterruptedException {
    HttpRequest postRequest = HttpRequest.newBuilder()
        .POST(BodyPublishers.ofString("{\"username\": \"admin\", \"password\": \"123\"}"))
        .uri(URI.create("http://localhost:8080/user"))
        .header("Content-Type", "application/json")
        .build();

    HttpResponse<String> response = HttpClient.newHttpClient().send(postRequest, HttpResponse.BodyHandlers.ofString());
    HttpHeaders headers = response.headers();
    headers.map().forEach((k, v) -> System.out.println(k + ":" + v));
    System.out.println(response.statusCode());
    System.out.println(response.body());
  }
}

Output:

content-type:[application/json]
date:[Wed, 13 Oct 2021 16:43:19 GMT]
transfer-encoding:[chunked]
200
{"username":"admin","password":"123"}

PUT REQUEST #

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpRequest.BodyPublishers;

public class PutRequest {
  public static void main(String[] args) throws IOException, InterruptedException {
    HttpRequest putRequest = HttpRequest.newBuilder()
        .PUT(BodyPublishers.ofString("{\"username\": \"test\", \"password\": \"123\"}"))
        .uri(URI.create("http://localhost:8080/user/6"))
        .header("Content-Type", "application/json")
        .build();

    HttpResponse<String> response = HttpClient.newHttpClient().send(putRequest, HttpResponse.BodyHandlers.ofString());
    System.out.println(response.version());
    System.out.println(response.statusCode());
    System.out.println(response.body());
  }
}

Output:

HTTP_1_1
200
{"username":"test","password":"123"}

DELETE REQUEST #

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class DeleteRequest {
  public static void main(String[] args) throws IOException, InterruptedException {
    HttpRequest deleteRequest = HttpRequest.newBuilder()
        .DELETE()
        .uri(URI.create("http://localhost:8080/user/6"))
        .build();

    HttpResponse<String> response = HttpClient.newHttpClient().send(deleteRequest, HttpResponse.BodyHandlers.ofString());
    System.out.println(response.statusCode());
    System.out.println(response.body());
  }
}

Output:

200

PATCH REQUEST #

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse;

public class PatchRequest {
  public static void main(String[] args) throws IOException, InterruptedException {

    HttpRequest patchRequest = HttpRequest.newBuilder()
        .method("PATCH", BodyPublishers.ofString("{\"username\": \"admin\", \"password\": \"root\"}"))
        .uri(URI.create("http://localhost:8080/user/1"))
        .header("Content-Type", "application/json")
        .build();

    HttpResponse<String> response = HttpClient.newHttpClient().send(patchRequest, HttpResponse.BodyHandlers.ofString());
    System.out.println(response.statusCode());
    System.out.println(response.body());
  }
}

Output:

200
{"username":"admin","password":"root"}

Asynchronous Examples #

GET REQUEST #

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.concurrent.TimeUnit;

public class GetRequest {
  public static void main(String[] args) throws Exception {
    HttpRequest getRequest = HttpRequest.newBuilder()
        .GET()
        .uri(URI.create("http://localhost:8080/user/1"))
        .build();

    HttpClient.newHttpClient().sendAsync(getRequest, HttpResponse.BodyHandlers.ofString())
      .thenApply(response -> {
        System.out.println(response.statusCode());
        return response; })
      .thenApply(HttpResponse::body)
      .thenAccept(System.out::println)
      .get(5, TimeUnit.SECONDS);
  }
}

Output:

200
{"username":"admin","password":"root"}

POST REQUEST #

 import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse;
import java.util.concurrent.TimeUnit;

public class PostRequest {
  public static void main(String[] args) throws Exception {
    HttpRequest postRequest = HttpRequest.newBuilder()
        .POST(BodyPublishers.ofString("{\"username\": \"admin\", \"password\": \"123\"}"))
        .uri(URI.create("http://localhost:8080/user"))
        .header("Content-Type", "application/json")
        .build();

    HttpClient.newHttpClient().sendAsync(postRequest, HttpResponse.BodyHandlers.ofString())
    .thenApply(response -> {
      System.out.println(response.statusCode());
      return response; })
    .thenApply(HttpResponse::body)
    .thenAccept(System.out::println)
    .get(5, TimeUnit.SECONDS);
  }
}

Output:

200
{"username":"admin","password":"123"}

PUT REQUEST #

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse;
import java.util.concurrent.TimeUnit;

public class PutRequest {
  public static void main(String[] args) throws Exception {
    HttpRequest putRequest = HttpRequest.newBuilder()
        .PUT(BodyPublishers.ofString("{\"username\": \"test\", \"password\": \"123\"}"))
        .uri(URI.create("http://localhost:8080/user/6"))
        .header("Content-Type", "application/json")
        .build();

    HttpClient.newHttpClient().sendAsync(putRequest, HttpResponse.BodyHandlers.ofString())
    .thenApply(response -> {
      System.out.println(response.statusCode());
      return response; })
    .thenApply(HttpResponse::body)
    .thenAccept(System.out::println)
    .get(5, TimeUnit.SECONDS);
  }
}

Output:

200
{"username":"test","password":"123"}

DELETE REQUEST #

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.concurrent.TimeUnit;

public class DeleteRequest {
  public static void main(String[] args) throws Exception {
    HttpRequest deleteRequest = HttpRequest.newBuilder()
        .DELETE()
        .uri(URI.create("http://localhost:8080/user/2"))
        .build();

    HttpClient.newHttpClient().sendAsync(deleteRequest, HttpResponse.BodyHandlers.ofString())
    .thenApply(response -> {
      System.out.println(response.statusCode());
      return response; })
    .thenApply(HttpResponse::body)
    .thenAccept(System.out::println)
    .get(5, TimeUnit.SECONDS);
  }
}

Output:

200

PATCH REQUEST #

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse;
import java.util.concurrent.TimeUnit;

public class PatchRequest {
  public static void main(String[] args) throws Exception {

    HttpRequest patchRequest = HttpRequest.newBuilder()
        .method("PATCH", BodyPublishers.ofString("{\"username\": \"admin\", \"password\": \"root\"}"))
        .uri(URI.create("http://localhost:8080/user/1"))
        .header("Content-Type", "application/json")
        .build();

    HttpClient.newHttpClient().sendAsync(patchRequest, HttpResponse.BodyHandlers.ofString())
    .thenApply(response -> {
      System.out.println(response.statusCode());
      return response; })
    .thenApply(HttpResponse::body)
    .thenAccept(System.out::println)
    .get(5, TimeUnit.SECONDS);
  }
}

Output:

200
{"username":"admin","password":"root"}