Java HttpClient Basic Authentication – Java HttpClient基本认证

最后修改: 2022年 4月 19日

1. Overview


In this short tutorial, we’ll take a look at basic authentication. We’ll see how it works and configure the Java HttpClient to use this kind of authentication.

在这个简短的教程中,我们将看一下基本认证。我们将看到它是如何工作的,并配置Java HttpClient以使用这种认证。

2. Basic Authentication


Basic authentication is a simple authentication method. Clients can authenticate via username and password. These credentials are sent in the Authorization HTTP header in a specific format. It begins with the Basic keyword, followed by a base64-encoded value of username:password. The colon character is important here. The header should strictly follow this format.

基本认证是一种简单的认证方法。客户端可以通过用户名和密码进行认证。这些证书在Authorization HTTP头中以特定格式发送。它以Basic关键字开始,后面是一个base64编码的username:password值。这里的冒号字符很重要。头部应该严格遵循这个格式。

For example, to authenticate with baeldung username and HttpClient password we must send this header:


Basic YmFlbGR1bmc6SHR0cENsaWVudA==

We can verify it by using a base64 decoder and checking the decoded result.


3. Java HttpClient

3.Java HttpClient[/strong

Java 9 introduced a new HttpClient as an incubated module which was standardized in Java 11. We’ll use Java 11, so we can simply import it from the package without any extra configuration or dependencies.

Java 9引入了一个新的HttpClient作为孵化模块,在Java 11中得到了标准化。我们将使用Java 11,所以我们可以简单地从包中导入它,而无需任何额外的配置或依赖。

Let’s start by executing a simple GET request without any authentication for now:


HttpClient client = HttpClient.newHttpClient();

HttpRequest request = HttpRequest.newBuilder()
  .uri(new URI(""))

HttpResponse<String> response = client.send(request, BodyHandlers.ofString());"Status {}", response.statusCode());

Firstly, we create an HttpClient, which can be used to execute HTTP requests. Secondly, we create an HttpRequest using the builder design pattern. The GET method sets the HTTP method of the request. The uri method sets the URL where we would like to send the request.

首先,我们创建一个HttpClient,它可以用来执行HTTP请求。其次,我们使用builder设计模式创建一个HttpRequestGET方法设置请求的 HTTP 方法。uri方法设置我们想发送请求的URL。

After that, we send the request using our client. The second parameter of the send method is a response body handler. This tells the client that we would like to treat the response body as a String.

之后,我们使用我们的客户端发送该请求。send方法的第二个参数是response body handler。这告诉客户端,我们想把响应体当作String

Let’s run our application and check the logs. The output should look like this:


INFO com.baeldung.httpclient.basicauthentication.HttpClientBasicAuthentication - Status 200

We see that the HTTP status is 200, meaning our request was successful. After this, let’s see how we can handle authentication.


4. Using HttpClient Authenticator


Before we configure authentication we need an URL to test it. Let’s use a Postman Echo endpoint that requires authentication. Firstly, change the previous URL to this and run the application again:

在我们配置认证之前,我们需要一个URL来测试它。让我们使用一个需要认证的Postman Echo端点。首先,将之前的URL改为这个,然后再次运行应用程序。

HttpRequest request = HttpRequest.newBuilder()
  .uri(new URI(""))

Let’s check the logs and look for the status code. This time we received HTTP status 401 “Unauthorized”. This response code means that the endpoint requires authentication but the client didn’t send any credentials.

让我们检查一下日志,找找状态代码。这次我们收到HTTP状态401 “未授权”。这个响应代码意味着端点需要认证,但客户端没有发送任何凭证。

Let’s change our client so that it sends the required authentication data. We can do this by configuring the HttpClient Builder and our client will use the credentials we set up. This endpoint accepts the username “postman” with the password “password”. Let’s add an authenticator to our client:

让我们改变我们的客户端,以便它能够发送所需的认证数据。我们可以通过配置HttpClient Builder来做到这一点,我们的客户端将使用我们设置的凭证。这个端点接受用户名“postman”和密码“password”。让我们为我们的客户端添加一个认证器

HttpClient client = HttpClient.newBuilder()
  .authenticator(new Authenticator() {
      protected PasswordAuthentication getPasswordAuthentication() {
          return new PasswordAuthentication("postman", "password".toCharArray());

Let’s run the application again. Now the request is successful and we receive HTTP status 200.


5. Authenticate Using HTTP Headers


We can use another approach to access endpoints that require authentication. We learned from previous sections how the Authorization header is constructed, so we can set its value manually. Although this has to be done per request instead of setting it once via an authenticator.


Let’s remove the authenticator and see how we can set the request headers. We need to construct the header value using base64 encoding:


private static final String getBasicAuthenticationHeader(String username, String password) {
    String valueToEncode = username + ":" + password;
    return "Basic " + Base64.getEncoder().encodeToString(valueToEncode.getBytes());

Let’s set this value for the Authorization header and run the application:


HttpRequest request = HttpRequest.newBuilder()
  .uri(new URI(""))
  .header("Authorization", getBasicAuthenticationHeader("postman", "password"))

Our request is successful which means that we constructed and set the header value correctly.


6. Conclusion


In this short tutorial, we saw what is basic authentication and how it works. We used the Java HttpClient with basic authentication by setting an authenticator for it. We used a different approach to authenticate by setting the HTTP header manually.

在这个简短的教程中,我们看到了什么是基本认证以及它是如何工作的。我们通过为Java HttpClient设置一个authenticator来使用基本认证。我们使用了一种不同的方法,通过手动设置HTTP头来进行认证。

As always, the source code for these examples is available over on GitHub.