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 PostRequest {
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}
1package com.zetcode;
2
3import java.io.IOException;
4import java.net.URI;
5import java.net.http.HttpClient;
6import java.net.http.HttpRequest;
7import java.net.http.HttpResponse;
8
9public class GetRequestJava11 {
10
11 public static void main(String[] args) throws IOException, InterruptedException {
12
13 HttpClient client = HttpClient.newHttpClient();
14 HttpRequest request = HttpRequest.newBuilder()
15 .uri(URI.create("http://webcode.me"))
16 .build();
17
18 HttpResponse<String> response = client.send(request,
19 HttpResponse.BodyHandlers.ofString());
20
21 System.out.println(response.body());
22 }
23}
24