1HttpClientPostJSON.java
2
3package com.mkyong.java11.jep321;
4
5import java.io.IOException;
6import java.net.URI;
7import java.net.http.HttpClient;
8import java.net.http.HttpRequest;
9import java.net.http.HttpResponse;
10import java.time.Duration;
11
12public class HttpClientPostJSON {
13
14 private static final HttpClient httpClient = HttpClient.newBuilder()
15 .version(HttpClient.Version.HTTP_2)
16 .connectTimeout(Duration.ofSeconds(10))
17 .build();
18
19 public static void main(String[] args) throws IOException, InterruptedException {
20
21 // json formatted data
22 String json = new StringBuilder()
23 .append("{")
24 .append("\"name\":\"mkyong\",")
25 .append("\"notes\":\"hello\"")
26 .append("}").toString();
27
28 // add json header
29 HttpRequest request = HttpRequest.newBuilder()
30 .POST(HttpRequest.BodyPublishers.ofString(json))
31 .uri(URI.create("https://httpbin.org/post"))
32 .setHeader("User-Agent", "Java 11 HttpClient Bot") // add request header
33 .header("Content-Type", "application/json")
34 .build();
35
36 HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
37
38 // print status code
39 System.out.println(response.statusCode());
40
41 // print response body
42 System.out.println(response.body());
43
44 }
45
46}