BAEL-5487-java-httpclient-custom-header (#12269)

Co-authored-by: tienvn4 <tienvn4@ghtk.co>
This commit is contained in:
vunamtien 2022-05-27 18:48:42 +07:00 committed by GitHub
parent d0b326355c
commit 9c40bfe297
1 changed files with 46 additions and 0 deletions

View File

@ -0,0 +1,46 @@
package com.baeldung.httpclient;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class HttpClientHeader {
public static HttpResponse<String> callWithCustomHeader(String url) throws URISyntaxException, IOException, InterruptedException {
HttpClient httpClient = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.header("X-Our-Header-1", "value1")
.header("X-Our-Header-1", "value2")
.header("X-Our-Header-2", "value2")
.uri(new URI(url)).build();
return httpClient.send(request, HttpResponse.BodyHandlers.ofString());
}
public static HttpResponse<String> callWithCustomHeaderV2(String url) throws URISyntaxException, IOException, InterruptedException {
HttpClient httpClient = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.headers("X-Our-Header-1", "value1", "X-Our-Header-1", "value2")
.uri(new URI(url)).build();
return httpClient.send(request, HttpResponse.BodyHandlers.ofString());
}
public static HttpResponse<String> callWithCustomHeaderV3(String url) throws URISyntaxException, IOException, InterruptedException {
HttpClient httpClient = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.setHeader("X-Our-Header-1", "value1")
.setHeader("X-Our-Header-1", "value2")
.uri(new URI(url)).build();
return httpClient.send(request, HttpResponse.BodyHandlers.ofString());
}
}