Java Code Examples for java.net.http.HttpClient

The following examples show how to use java.net.http.HttpClient. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: Java-Coding-Problems   Source File: ViaBody.java    License: MIT License 6 votes vote down vote up
public void bodyExample() throws IOException, InterruptedException {
    
    HttpClient client = HttpClient.newHttpClient();

    HttpRequest request = HttpRequest.newBuilder()
            .header("Content-Type", "application/json")
            .POST(BodyPublishers.ofString(
                    "{\"email\":\"[email protected]\",\"password\":\"cityslicka\"}"))
            .uri(URI.create("https://reqres.in/api/login"))
            .build();

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

    System.out.println("Status code: " + response.statusCode());
    System.out.println("\n Body: " + response.body());
}
 
Example 2
Source Project: Java-Coding-Problems   Source File: ViaAuthenticator.java    License: MIT License 6 votes vote down vote up
public void authenticatorExample() throws IOException, InterruptedException {

        HttpClient client = HttpClient.newBuilder()
                .authenticator(new Authenticator() {
                    @Override
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(
                                "username",
                                "password".toCharArray());
                    }
                }).build();

        HttpRequest request = HttpRequest.newBuilder()
                // ...           
                .build();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
    }
 
Example 3
Source Project: Java-Coding-Problems   Source File: Main.java    License: MIT License 6 votes vote down vote up
public static void main(String[] args) throws IOException, InterruptedException {

        HttpClient client = HttpClient.newHttpClient();

        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://reqres.in/api/users/2"))
                .build();

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

        System.out.println("Version: " + response.version());
        System.out.println("\nURI: " + response.uri());
        System.out.println("\nStatus code: " + response.statusCode());
        System.out.println("\nHeaders: " + response.headers());
        System.out.println("\n Body: " + response.body());
    }
 
Example 4
Source Project: Java-Coding-Problems   Source File: Main.java    License: MIT License 6 votes vote down vote up
public static void main(String[] args) throws IOException, InterruptedException {

        HttpClient client = HttpClient.newHttpClient();

        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://http2.golang.org/serverpush"))
                .build();

        client.sendAsync(request, HttpResponse.BodyHandlers.ofString(), pushPromiseHandler())
                .thenApply(HttpResponse::body)
                .thenAccept((b) -> System.out.println("\nMain resource:\n" + b))
                .join();

        System.out.println("\nPush promises map size: " + promisesMap.size() + "\n");

        promisesMap.entrySet().forEach((entry) -> {
            System.out.println("Request = " + entry.getKey()
                    + ", \nResponse = " + entry.getValue().join().body());
        });
    }
 
Example 5
Source Project: Java-Coding-Problems   Source File: Main.java    License: MIT License 6 votes vote down vote up
public static void main(String[] args) throws IOException, InterruptedException {

        Map<Object, Object> data = new LinkedHashMap<>();
        data.put("author", "Lorem Ipsum Generator");
        data.put("filefield", Path.of("LoremIpsum.txt"));
        String boundary = UUID.randomUUID().toString().replaceAll("-", "");

        HttpClient client = HttpClient.newHttpClient();        
        
        HttpRequest request = HttpRequest.newBuilder()
                .header("Content-Type", "multipart/form-data;boundary=" + boundary)
                .POST(MultipartBodyPublisher.ofMultipart(data, boundary))
                .uri(URI.create("http://jkorpela.fi/cgi-bin/echoraw.cgi"))
                .build();

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

        System.out.println("Status code: " + response.statusCode());
        System.out.println("\n Body: " + response.body());
    }
 
Example 6
Source Project: demo-java-x   Source File: Http2Api.java    License: MIT License 6 votes vote down vote up
private static CompletableFuture<Void> reactiveSearch(HttpClient client, URI url, String term) {
	HttpRequest request = HttpRequest.newBuilder()
			.GET()
			.uri(url)
			.build();
	StringFinder finder = new StringFinder(term);
	client.sendAsync(request, BodyHandlers.fromLineSubscriber(finder))
			.exceptionally(ex -> {
				finder.onError(ex);
				return null;
			});
	return finder
			.found()
			.exceptionally(Http2Api::handleError)
			.thenAccept(found -> handleResult(url, found));
}
 
Example 7
Source Project: Java-Coding-Problems   Source File: Main.java    License: MIT License 6 votes vote down vote up
public static void main(String[] args) throws IOException, InterruptedException {

        HttpClient client = HttpClient.newHttpClient();

        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://http2.golang.org/serverpush"))
                .build();

        client.sendAsync(request, HttpResponse.BodyHandlers.ofString(), pushPromiseHandler())
                .thenApply(HttpResponse::body)
                .thenAccept((b) -> System.out.println("\nMain resource:\n" + b))
                .join();

        asyncPushRequests.forEach(CompletableFuture::join);

        System.out.println("\nFetched a total of " + asyncPushRequests.size() + " push requests");
    }
 
Example 8
Source Project: Java-Coding-Problems   Source File: Main.java    License: MIT License 6 votes vote down vote up
public static void main(String[] args) throws IOException, InterruptedException {

        HttpClient client = HttpClient.newHttpClient();

        HttpRequest request = HttpRequest.newBuilder()
                .header("Accept-Encoding", "gzip")
                .uri(URI.create("https://davidwalsh.name"))
                .build();

        HttpResponse<InputStream> response = client.send(
                request, HttpResponse.BodyHandlers.ofInputStream());

        System.out.println("Status code: " + response.statusCode());

        String encoding = response.headers().firstValue("Content-Encoding").orElse("");
        System.out.println("\nEncoding: " + encoding + "\n");

        if ("gzip".equals(encoding)) {
            String gzipAsString = gzipToString(response.body());
            System.out.println(gzipAsString);
        } else {
            String isAsString = isToString(response.body());
            System.out.println(isAsString);
        }
    }
 
Example 9
Source Project: tutorials   Source File: HttpClientUnitTest.java    License: MIT License 6 votes vote down vote up
@Test
public void shouldReturnOKStatusForAuthenticatedAccess() throws URISyntaxException, IOException, InterruptedException {
    HttpRequest request = HttpRequest.newBuilder()
        .uri(new URI("https://postman-echo.com/basic-auth"))
        .GET()
        .build();
    HttpResponse<String> response = HttpClient.newBuilder()
        .authenticator(new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("postman", "password".toCharArray());
            }
        })
        .build()
        .send(request, HttpResponse.BodyHandlers.ofString());

    assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
}
 
Example 10
/**
 * Test changing port.
 *
 * @throws Exception when an error occurs.
 */
@Test
@Disabled
public void testChangingPort() throws Exception {
    System.setProperty("java.naming.factory.initial", "cloud.piranha.jndi.memory.DefaultInitialContextFactory");
    final MicroPiranha piranha = new MicroPiranha();
    piranha.configure(new String[]{"--port", "8088"});
    Thread thread = new Thread(piranha);
    thread.start();
    Thread.sleep(3000);
    try {
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder(URI.create("http://localhost:8088/does-not-exist")).build();
        HttpResponse<Void> response = client.send(request, HttpResponse.BodyHandlers.discarding());
        assertEquals(response.statusCode(), 404);
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }
    piranha.stop();
    Thread.sleep(3000);
}
 
Example 11
Source Project: tutorials   Source File: HttpClientUnitTest.java    License: MIT License 6 votes vote down vote up
@Test
public void shouldReturnSampleDataContentWhenConnectViaSystemProxy() throws IOException, InterruptedException, URISyntaxException {
    HttpRequest request = HttpRequest.newBuilder()
        .uri(new URI("https://postman-echo.com/post"))
        .headers("Content-Type", "text/plain;charset=UTF-8")
        .POST(HttpRequest.BodyPublishers.ofString("Sample body"))
        .build();
  
    
    HttpResponse<String> response = HttpClient.newBuilder()
        .proxy(ProxySelector.getDefault())
        .build()
        .send(request, HttpResponse.BodyHandlers.ofString());
    
    assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
    assertThat(response.body(), containsString("Sample body"));
}
 
Example 12
Source Project: tutorials   Source File: HttpClientUnitTest.java    License: MIT License 6 votes vote down vote up
@Test
public void shouldStoreCookieWhenPolicyAcceptAll() throws URISyntaxException, IOException, InterruptedException {
    HttpRequest request = HttpRequest.newBuilder()
        .uri(new URI("https://postman-echo.com/get"))
        .GET()
        .build();

    HttpClient httpClient = HttpClient.newBuilder()
        .cookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_ALL))
        .build();

    httpClient.send(request, HttpResponse.BodyHandlers.ofString());

    assertTrue(httpClient.cookieHandler()
        .isPresent());
}
 
Example 13
/**
 * Test file not found.
 *
 * @throws Exception when an error occurs.
 */
@Test
public void testFileNotFound() throws Exception {
    HttpServer server = createServer(8765);
    server.start();
    try {
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder(URI.create("http://localhost:8765/this_is_certainly_not_there")).build();
        HttpResponse<Void> response = client.send(request, HttpResponse.BodyHandlers.discarding());
        assertEquals(response.statusCode(), 404);
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    } finally {
        server.stop();
    }
}
 
Example 14
/**
 * Test SO_TIMEOUT.
 */
@Test
public void testSoTimeout() {
    DefaultHttpServer server = new DefaultHttpServer(
            8765, new DefaultHttpServerProcessor(), 2000);
    assertEquals(server.getSoTimeout(), 2000);
    server.start();
    try {
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder(URI.create("http://localhost:8765/")).build();
        HttpResponse<Void> response = client.send(request, HttpResponse.BodyHandlers.discarding());
        assertEquals(response.statusCode(), 200);
    } catch (IOException | InterruptedException ioe) {
        throw new RuntimeException(ioe);
    } finally {
        server.stop();
    }
}
 
Example 15
Source Project: hellokoding-courses   Source File: HttpClientExamples.java    License: MIT License 6 votes vote down vote up
@Test
public void postAsync() {
    HttpClient client = HttpClient.newHttpClient();

    HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create("http://localhost:8081/test/resource"))
        .header("Accept", "application/json")
        .POST(HttpRequest.BodyPublishers.ofString("ping!"))
        .build();

    CompletableFuture<HttpResponse<String>> completableFuture =
        client.sendAsync(request, HttpResponse.BodyHandlers.ofString());
    completableFuture
        .thenApplyAsync(HttpResponse::headers)
        .thenAcceptAsync(System.out::println);
    HttpResponse<String> response = completableFuture.join();

    assertThat(response.statusCode()).isEqualTo(200);
}
 
Example 16
Source Project: hellokoding-courses   Source File: HttpClientExamples.java    License: MIT License 6 votes vote down vote up
@Test
public void postJson() throws IOException, InterruptedException {
    HttpClient client = HttpClient.newHttpClient();

    Book book = new Book(1, "Java HttpClient in practice");
    String body = objectMapper.writeValueAsString(book);

    HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create("http://localhost:8081/test/resource"))
        .header("Accept", "application/json")
        .header("Content-Type", "application/json")
        .POST(HttpRequest.BodyPublishers.ofString(body))
        .build();

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

    assertThat(response.statusCode()).isEqualTo(200);
    assertThat(objectMapper.readValue(response.body(), Book.class).id).isEqualTo(1);
}
 
Example 17
Source Project: hellokoding-courses   Source File: HttpClientExamples.java    License: MIT License 6 votes vote down vote up
@Test
public void basicAuthentication() throws IOException, InterruptedException {
    HttpClient client = HttpClient.newHttpClient();

    String encodedAuth = Base64.getEncoder()
        .encodeToString(("user" + ":" + "pass").getBytes(StandardCharsets.UTF_8));

    HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create("http://localhost:8081/test/secure"))
        .header("Authorization", "Basic " + encodedAuth)
        .build();

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

    assertThat(response.statusCode()).isEqualTo(200);
}
 
Example 18
Source Project: jmbe   Source File: GitHub.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Obtain the latest release object from the repository.
 * @param repositoryURL for the GitHub api
 * @return the latest release or null
 */
public static Release getLatestRelease(String repositoryURL)
{
    HttpClient httpClient = HttpClient.newHttpClient();
    HttpRequest request = HttpRequest.newBuilder().uri(URI.create(repositoryURL)).build();

    try
    {
        HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());

        if(response.statusCode() == 200)
        {
            return parseResponse(response.body());
        }
        else
        {
            mLog.error("Error while fetching latest releases - HTTP:" + response.statusCode());
        }
    }
    catch(IOException | InterruptedException e)
    {
        mLog.error("Error while detecting the current release version of JMBE library", e);
    }

    return null;
}
 
Example 19
/**
 * Test process method.
 *
 * @throws Exception when a serious error occurs.
 */
@Test
public void testProcess() throws Exception {
    DefaultWebApplicationServer server = new DefaultWebApplicationServer();
    HttpServer httpServer = new DefaultHttpServer(8180, server, false);
    DefaultWebApplication application = new DefaultWebApplication();
    application.setContextPath("/context");
    application.addServlet("snoop", new TestSnoopServlet());
    application.addServletMapping("snoop", "/snoop/*");
    server.addWebApplication(application);
    server.initialize();
    server.start();
    httpServer.start();
    try {
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder(new URI("http://localhost:8180/context/snoop/index.html")).build();
        HttpResponse<Void> response = client.send(request, HttpResponse.BodyHandlers.discarding());
        assertEquals(response.statusCode(), 200);
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }
    httpServer.stop();
    server.stop();
}
 
Example 20
Source Project: openapi-generator   Source File: ApiClient.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Ctor.
 */
public ApiClient() {
  builder = HttpClient.newBuilder();
  mapper = new ObjectMapper();
  mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
  mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
  mapper.configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, false);
  mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
  mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
  mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
  mapper.registerModule(new JavaTimeModule());
  JsonNullableModule jnm = new JsonNullableModule();
  mapper.registerModule(jnm);
  URI baseURI = URI.create("http://petstore.swagger.io:80/v2");
  scheme = baseURI.getScheme();
  host = baseURI.getHost();
  port = baseURI.getPort();
  basePath = baseURI.getRawPath();
  interceptor = null;
  readTimeout = null;
  responseInterceptor = null;
}
 
Example 21
/**
 * Test start method.
 *
 * @throws Exception when an error occurs.
 */
@Test
@Disabled
public void testStart() throws Exception {
    System.setProperty("java.naming.factory.initial", "cloud.piranha.jndi.memory.DefaultInitialContextFactory");
    final MicroPiranha piranha = new MicroPiranha();
    piranha.configure(new String[]{});
    Thread thread = new Thread(piranha);
    thread.start();
    Thread.sleep(3000);
    try {
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder(URI.create("http://localhost:8080/does-not-exist")).build();
        HttpResponse<Void> response = client.send(request, HttpResponse.BodyHandlers.discarding());
        assertEquals(response.statusCode(), 404);
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }
    piranha.stop();
    Thread.sleep(3000);
}
 
Example 22
/**
 * Test processing.
 *
 * @throws Exception when an error occurs.
 */
@Test
public void testProcessing2() throws Exception {
    HttpServer server = createServer(8765);
    server.start();
    try {
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder(URI.create("http://localhost:8765")).build();
        HttpResponse<Void> response = client.send(request, HttpResponse.BodyHandlers.discarding());
        assertEquals(response.statusCode(), 200);
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    } finally {
        server.stop();
    }
}
 
Example 23
Source Project: teku   Source File: ExternalMessageSignerService.java    License: Apache License 2.0 6 votes vote down vote up
private SafeFuture<BLSSignature> sign(final Bytes signingRoot) {
  final String publicKey = blsPublicKey.getPublicKey().toString();
  return SafeFuture.ofComposed(
      () -> {
        final String requestBody = createSigningRequestBody(signingRoot);
        final URI uri = signingServiceUrl.toURI().resolve("/signer/sign/" + publicKey);
        final HttpRequest request =
            HttpRequest.newBuilder()
                .uri(uri)
                .timeout(timeout)
                .POST(BodyPublishers.ofString(requestBody))
                .build();
        return HttpClient.newHttpClient()
            .sendAsync(request, BodyHandlers.ofString())
            .handleAsync(this::getBlsSignature);
      });
}
 
Example 24
Source Project: java11-examples   Source File: Example.java    License: MIT License 6 votes vote down vote up
public static void asyncGet(String uri) throws Exception {
    HttpClient client = HttpClient.newHttpClient();
    HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create(uri))
            .build();

    CompletableFuture<HttpResponse<String>> responseCompletableFuture = client.sendAsync(request, HttpResponse.BodyHandlers.ofString());
    responseCompletableFuture.whenComplete((resp, t) -> {
        if (t != null) {
            t.printStackTrace();
        } else {
            System.out.println(resp.body());
            System.out.println(resp.statusCode());
        }
    }).join();
}
 
Example 25
Source Project: mangooio   Source File: WebSocketControllerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testWebSocketConnection() throws Exception {
    // given
    final HttpClient httpClient = HttpClient.newHttpClient();
    final Config config = Application.getInstance(Config.class);
    final String uri = "ws://" + config.getConnectorHttpHost() + ":" + config.getConnectorHttpPort() + "/websocket";

    // when
    Listener listener = new Listener() {
        @Override
        public void onOpen(WebSocket webSocket) {
            connected = true;
        }
    };
    httpClient.newWebSocketBuilder().buildAsync(new URI(uri), listener).join();
    
    // then
    assertThat(connected, equalTo(true));
}
 
Example 26
Source Project: Learn-Java-12-Programming   Source File: HttpClientDemo.java    License: MIT License 6 votes vote down vote up
private static void getAsync(){
        HttpClient httpClient = HttpClient.newHttpClient();

        HttpRequest req = HttpRequest.newBuilder()
                .uri(URI.create("http://localhost:3333/something"))
                .GET()   // default
                .build();
/*
        CompletableFuture<Void> cf =
        httpClient.sendAsync(req, BodyHandlers.ofString())
                .thenAccept(resp -> System.out.println("Response: " +
                                resp.statusCode() + " : " + resp.body()));
*/
        CompletableFuture<String> cf =
                httpClient.sendAsync(req, BodyHandlers.ofString())
                        .thenApply(resp -> "Server responded: " + resp.body());

        System.out.println("The request was sent asynchronously...");
        try {
            System.out.println("CompletableFuture get: " +
                    cf.get(5, TimeUnit.SECONDS));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        System.out.println("Exit the client...");
    }
 
Example 27
Source Project: Learn-Java-12-Programming   Source File: HttpClientDemo.java    License: MIT License 6 votes vote down vote up
private static void push(){
    HttpClient httpClient = HttpClient.newHttpClient();

    HttpRequest req = HttpRequest.newBuilder()
            .uri(URI.create("http://localhost:3333/something"))
            .GET()
            .build();

    CompletableFuture cf =
            httpClient.sendAsync(req, BodyHandlers.ofString(), (PushPromiseHandler) HttpClientDemo::applyPushPromise);

    System.out.println("The request was sent asynchronously...");
    try {
        System.out.println("CompletableFuture get: " + cf.get(5, TimeUnit.SECONDS));
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    System.out.println("Exit the client...");
}
 
Example 28
Source Project: blog-tutorials   Source File: TelegramNotifier.java    License: MIT License 6 votes vote down vote up
public static void main(String[] args) throws IOException, InterruptedException {

        String message = "Hello World from Java 11";

        HttpClient client = HttpClient.newBuilder()
                .connectTimeout(Duration.ofSeconds(5))
                .version(HttpClient.Version.HTTP_2)
                .build();

        UriBuilder builder = UriBuilder
                .fromUri("https://api.telegram.org")
                .path("/{token}/sendMessage")
                .queryParam("chat_id", CHAT_ID)
                .queryParam("text", message);

        HttpRequest request = HttpRequest.newBuilder()
                .GET()
                .uri(builder.build("bot" + TOKEN))
                .timeout(Duration.ofSeconds(5))
                .build();

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

        System.out.println(response.statusCode());
        System.out.println(response.body());
    }
 
Example 29
Source Project: tutorials   Source File: HttpClientUnitTest.java    License: MIT License 5 votes vote down vote up
@Test
public void shouldProcessMultipleRequestViaStream() throws URISyntaxException, ExecutionException, InterruptedException {
    List<URI> targets = Arrays.asList(new URI("https://postman-echo.com/get?foo1=bar1"), new URI("https://postman-echo.com/get?foo2=bar2"));

    HttpClient client = HttpClient.newHttpClient();

    List<CompletableFuture<String>> futures = targets.stream()
        .map(target -> client.sendAsync(HttpRequest.newBuilder(target)
            .GET()
            .build(), HttpResponse.BodyHandlers.ofString())
            .thenApply(response -> response.body()))
        .collect(Collectors.toList());

    CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
        .join();

    if (futures.get(0)
        .get()
        .contains("foo1")) {
        assertThat(futures.get(0)
            .get(), containsString("bar1"));
        assertThat(futures.get(1)
            .get(), containsString("bar2"));
    } else {
        assertThat(futures.get(1)
            .get(), containsString("bar2"));
        assertThat(futures.get(1)
            .get(), containsString("bar1"));
    }

}
 
Example 30
Source Project: tutorials   Source File: HttpClientExample.java    License: MIT License 5 votes vote down vote up
public static void httpPostRequest() throws URISyntaxException, IOException, InterruptedException {
    HttpClient client = HttpClient.newBuilder()
        .version(HttpClient.Version.HTTP_2)
        .build();
    HttpRequest request = HttpRequest.newBuilder(new URI("http://jsonplaceholder.typicode.com/posts"))
        .version(HttpClient.Version.HTTP_2)
        .POST(BodyPublishers.ofString("Sample Post Request"))
        .build();
    HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
    String responseBody = response.body();
    System.out.println("httpPostRequest : " + responseBody);
}