How do I use Java 11 HttpClient with basic authentication?
Using Java 11’s HttpClient with Basic Authentication is straightforward. Below is an example of how to configure and send an HTTP request using Basic Authentication: Steps: Encode the Username and Password: Basic Authentication requires the credentials (username and password) to be Base64 encoded in the format username:password. Set the Authorization Header: Attach the Base64 encoded […]
Artikel oleh Wayan · Sumber: Kode Java ↗
Terjemahan artikel ini belum tersedia. Isi asli ditampilkan.
Using Java 11’s HttpClient with Basic Authentication is straightforward. Below is an example of how to configure and send an HTTP request using Basic Authentication:
Steps:
- Encode the Username and Password: Basic Authentication requires the credentials (username and password) to be Base64 encoded in the format
username:password. - Set the Authorization Header: Attach the Base64 encoded value as an
Authorizationheader in the request. - Use HttpClient to Send the Request: Use
HttpClientto send the request to the desired endpoint.
Here’s an example implementation:
Example Code
package org.kodejava.net.http;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Base64;
public class HttpClientWithBasicAuth {
public static void main(String[] args) throws Exception {
// Define the username and password
String username = "username";
String password = "password";
// Encode the credentials in Base64 format
String auth = username + ":" + password;
String encodedAuth = Base64.getEncoder().encodeToString(auth.getBytes());
String authHeader = "Basic " + encodedAuth;
// Create the HttpClient
HttpClient client = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_2)
.build();
// Create the HttpRequest with the Authorization header
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://example.com/api/resource")) // Replace with your endpoint
.header("Authorization", authHeader)
.header("Content-Type", "application/json") // Optional, adjust if needed
.GET() // Use POST, PUT, or DELETE if required
.build();
// Send the request and get the response
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
// Print the response details
System.out.println("Status Code: " + response.statusCode());
System.out.println("Response Body: " + response.body());
}
}
Explanation
- Base64 Encoding:
- Concatenate the username and password using
:as the separator. - Encode the concatenated string in Base64 format.
- Concatenate the username and password using
- Authorization Header:
- The
Authorizationheader must includeBasicfollowed by the Base64-encoded credentials.
- The
- HttpClient Configuration:
- Use
HttpClient.newBuilder()to configureHttpClient. - You can set the HTTP version with
.version(HttpClient.Version.HTTP_2).
- Use
- HttpRequest Building:
- Use
HttpRequest.newBuilder()to construct the request. - Attach the
Authorizationheader to the HTTP request. - Specify the HTTP method (
GET,POST, etc.).
- Use
- Response Handling:
- Use
HttpResponse.BodyHandlers.ofString()to handle the response body as aString.
- Use
Output
If the credentials are correct, the HTTP server will process the request and return the desired response. Otherwise, the server will return HTTP 401 Unauthorized.
Notes:
- Replace `https://example.com/api/resource` with your actual endpoint.
- Ensure that the username and password are handled securely and are not hardcoded in production. Use secure configurations or credential storage mechanisms instead.
- Adjust the other headers (e.g.,
Content-Type) based on your API’s requirements.
