java http客户端缺少通过curl显示的标头

lsmepo6l  于 2021-08-20  发布在  Java
关注(0)|答案(2)|浏览(450)

我正在尝试使用java.net.http.httpclient向http端点发送一个简单的get。端点需要基本身份验证。很简单,我正在做每个人都在做的事情:

HttpClient httpClient = HttpClient.newBuilder()
                                  .version(HttpClient.Version.HTTP_1_1)
                                  .authenticator(new Authenticator(){
                                    @Override
                                    protected PasswordAuthentication getPasswordAuthentication() {
                                      return new PasswordAuthentication("guest","guest".toCharArray());
                                    }
                                   })
                                  .build();
HttpRequest request = HttpRequest.newBuilder()
                                 .GET()
                                 .uri(URI.create("localhost:15672/api/overview")
                                 .build();
HttpResponse<Void> httpResponse = httpClient.send(request, HttpResponse.BodyHandlers.discarding());

但是,这会引发ioexception“响应代码401缺少www authenticate标头”。对我来说,服务器最初用401进行响应,然后客户端在验证器的帮助下重新尝试请求,这并非完全不合理。标题是强制性的,如果没有,则保证例外。
到目前为止,一切顺利。但是,当我通过curl执行相同的请求时,会出现标题:

> curl -i http://localhost:15672/api/overview
HTTP/1.1 401 Unauthorized
content-length: 0
content-security-policy: script-src 'self' 'unsafe-eval' 'unsafe-inline'; object-src 'self'
date: Thu, 08 Jul 2021 11:06:45 GMT
server: Cowboy
vary: origin
www-authenticate: Basic realm="RabbitMQ Management"

我做错了什么?

ibrsph3r

ibrsph3r1#

与此同时,我发现了问题所在:我联系的服务器有问题。第一个get返回的正是curl结果。java httpclient正确响应并发送了第二个带有凭据的get。凭据是错误的(出于测试目的),但响应不是预期的403,而是另一个401,而第二个401响应缺少标头。

wa7juj8i

wa7juj8i2#

对于基本授权,您可以执行以下操作

String plainCreds = "myuser:mypassword";
byte[] base64Bytes = Base64.encodeBase64(plainCreds.getBytes());

HttpRequest request = HttpRequest.newBuilder()
   .get()
   .uri(URI.create("localhost:15672/api/overview"))
   .header("Authorization", "Basic " + new String(base64Bytes))
   .build();

相关问题