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}
1package com.zetcode;
2
3import com.fasterxml.jackson.databind.ObjectMapper;
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.util.HashMap;
11
12public class HttpClientPost {
13
14 public static void main(String[] args) throws IOException, InterruptedException {
15
16 var values = new HashMap<String, String>() {{
17 put("name", "John Doe");
18 put ("occupation", "gardener");
19 }};
20
21 var objectMapper = new ObjectMapper();
22 String requestBody = objectMapper
23 .writeValueAsString(values);
24
25 HttpClient client = HttpClient.newHttpClient();
26 HttpRequest request = HttpRequest.newBuilder()
27 .uri(URI.create("https://httpbin.org/post"))
28 .POST(HttpRequest.BodyPublishers.ofString(requestBody))
29 .build();
30
31 HttpResponse<String> response = client.send(request,
32 HttpResponse.BodyHandlers.ofString());
33
34 System.out.println(response.body());
35 }
36}
37