Skip to content

Commit 2922438

Browse files
Merge pull request eugenp#12040 from Attila96/feature/java_httpclient_basic_authentication-bael-5458
[BAEL-5485] Java HttpClient Basic Authentication
2 parents 5524ec0 + a276831 commit 2922438

1 file changed

Lines changed: 67 additions & 0 deletions

File tree

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
package com.baeldung.httpclient.basicauthentication;
2+
3+
import java.io.IOException;
4+
import java.net.Authenticator;
5+
import java.net.PasswordAuthentication;
6+
import java.net.URI;
7+
import java.net.URISyntaxException;
8+
import java.net.http.HttpClient;
9+
import java.net.http.HttpRequest;
10+
import java.net.http.HttpResponse;
11+
import java.net.http.HttpResponse.BodyHandlers;
12+
import java.util.Base64;
13+
14+
import org.slf4j.Logger;
15+
import org.slf4j.LoggerFactory;
16+
17+
public class HttpClientBasicAuthentication {
18+
19+
private static final Logger logger = LoggerFactory.getLogger(HttpClientBasicAuthentication.class);
20+
21+
public static void main(String[] args) throws URISyntaxException, IOException, InterruptedException {
22+
useClientWithAuthenticator();
23+
useClientWithHeaders();
24+
}
25+
26+
private static void useClientWithAuthenticator() throws URISyntaxException, IOException, InterruptedException {
27+
HttpClient client = HttpClient.newBuilder()
28+
.authenticator(new Authenticator() {
29+
@Override
30+
protected PasswordAuthentication getPasswordAuthentication() {
31+
return new PasswordAuthentication("postman", "password".toCharArray());
32+
}
33+
})
34+
.build();
35+
36+
HttpRequest request = HttpRequest.newBuilder()
37+
.GET()
38+
.uri(new URI("https://postman-echo.com/basic-auth"))
39+
.build();
40+
41+
HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
42+
43+
logger.info("Status using authenticator {}", response.statusCode());
44+
}
45+
46+
private static void useClientWithHeaders() throws IOException, InterruptedException, URISyntaxException {
47+
HttpClient client = HttpClient.newBuilder()
48+
.build();
49+
50+
HttpRequest request = HttpRequest.newBuilder()
51+
.GET()
52+
.uri(new URI("https://postman-echo.com/basic-auth"))
53+
.header("Authorization", getBasicAuthenticationHeader("postman", "password"))
54+
.build();
55+
56+
HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
57+
58+
logger.info("Status using headers: {}", response.statusCode());
59+
}
60+
61+
private static final String getBasicAuthenticationHeader(String username, String password) {
62+
String valueToEncode = username + ":" + password;
63+
return "Basic " + Base64.getEncoder()
64+
.encodeToString(valueToEncode.getBytes());
65+
}
66+
67+
}

0 commit comments

Comments
 (0)