Java - 使用 Apache httpclient 的 HTTPS 基本身份验证

Java - HTTPS Basic authentification with Apache httpclient

我正在尝试使用 Apache httpclient 从具有基本身份验证的 HTTPS 服务器获取一些数据(json 数据 -> restful 服务器)。 SSL 证书是自签名的。 服务器对浏览器调用的响应非常好,在使用 curl 时也是如此。

但是使用 java Apache httpclient,那就是另一回事了。

客户端:

基本身份验证有效:如果忘记授权 header 或者我设置了错误的 base64 编码 login:password,服务器会向我发送 401 错误。

https/SSL 部分正在工作:我成功地从在线 restful json 服务器获取数据,但遗憾的是无法找到在线 restful json 具有用于测试目的的基本身份验证的服务器...

        try {

            CloseableHttpClient httpClient = null;
            try {
                httpClient = HttpClients.custom()
                        .setSSLSocketFactory(new SSLConnectionSocketFactory(SSLContexts.custom()
                                        .loadTrustMaterial(null, new TrustSelfSignedStrategy())
                                        .build()
                                )
                        )
                .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                        .build();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (KeyManagementException e) {
                e.printStackTrace();
            } catch (KeyStoreException e) {
                e.printStackTrace();
            }

            HttpGet getRequest = new HttpGet("https://localhost:5050/getdata");
            getRequest.addHeader("Accept", "*/*");
            getRequest.addHeader("Authorization", "Basic UBJ0aHVyOmFo0XElYHU=");
            HttpResponse response = httpClient.execute(getRequest);

调试告诉我:

Caused by: org.apache.http.ProtocolException: The server failed to respond with a valid HTTP response

没错!这不是我想要获得的有效 HTTP 响应,它是有效的 HTTPS 响应!

我想我遗漏了什么...

已解决!

错误来自服务器端:我的回复没有包含任何headers...

httpclient 似乎喜欢来自服务器的良好响应。对于浏览器或 curl 而言并非如此:它们可以接收垃圾,显示它们将 !