Skip to content

Commit 13d446c

Browse files
vunamtientienvn4
andauthored
BAEL-5487-java-httpclient-custom-header (eugenp#12269)
Co-authored-by: tienvn4 <tienvn4@ghtk.co>
1 parent b7025e4 commit 13d446c

1 file changed

Lines changed: 46 additions & 0 deletions

File tree

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package com.baeldung.httpclient;
2+
3+
import java.io.IOException;
4+
import java.net.URI;
5+
import java.net.URISyntaxException;
6+
import java.net.http.HttpClient;
7+
import java.net.http.HttpRequest;
8+
import java.net.http.HttpResponse;
9+
10+
public class HttpClientHeader {
11+
12+
public static HttpResponse<String> callWithCustomHeader(String url) throws URISyntaxException, IOException, InterruptedException {
13+
HttpClient httpClient = HttpClient.newHttpClient();
14+
15+
HttpRequest request = HttpRequest.newBuilder()
16+
.header("X-Our-Header-1", "value1")
17+
.header("X-Our-Header-1", "value2")
18+
.header("X-Our-Header-2", "value2")
19+
.uri(new URI(url)).build();
20+
21+
return httpClient.send(request, HttpResponse.BodyHandlers.ofString());
22+
}
23+
24+
public static HttpResponse<String> callWithCustomHeaderV2(String url) throws URISyntaxException, IOException, InterruptedException {
25+
HttpClient httpClient = HttpClient.newHttpClient();
26+
27+
HttpRequest request = HttpRequest.newBuilder()
28+
.headers("X-Our-Header-1", "value1", "X-Our-Header-1", "value2")
29+
.uri(new URI(url)).build();
30+
31+
return httpClient.send(request, HttpResponse.BodyHandlers.ofString());
32+
}
33+
34+
public static HttpResponse<String> callWithCustomHeaderV3(String url) throws URISyntaxException, IOException, InterruptedException {
35+
HttpClient httpClient = HttpClient.newHttpClient();
36+
37+
HttpRequest request = HttpRequest.newBuilder()
38+
.setHeader("X-Our-Header-1", "value1")
39+
.setHeader("X-Our-Header-1", "value2")
40+
.uri(new URI(url)).build();
41+
42+
return httpClient.send(request, HttpResponse.BodyHandlers.ofString());
43+
}
44+
45+
46+
}

0 commit comments

Comments
 (0)