Java 11 HttpClient 不发送基本身份验证
2022-09-02 02:51:42
我编写了以下 HttpClient 代码,但它没有导致标头被发送到服务器:Authorization
public static void main(String[] args) {
var client = HttpClient.newBuilder()
.authenticator(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username", "password".toCharArray());
}
})
.version(HttpClient.Version.HTTP_1_1)
.build();
var request = HttpRequest.newBuilder()
.uri("https://service-that-needs-auth.example/")
.build();
client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenAccept(System.out::println)
.join();
}
我从调用的服务收到 HTTP 401 错误。在我的情况下,它是Atlassian Jira Cloud API。
我已经确认我的方法没有被HttpClient调用。getPasswordAuthentication()
为什么它不起作用,我该怎么办?