有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用Apache httpclient进行Java HTTPS基本身份验证

我试图使用ApacheHttpClient通过基本身份验证从HTTPS服务器获取一些数据(json数据->;restful服务器)。SSL证书是自签名的。 服务器对浏览器调用和使用curl时的响应都非常好

然而,使用JavaApacheHttpClient,情况就完全不同了

客户端:

基本身份验证正在工作:如果忘记了授权标头或我设置了错误的base64编码登录:密码,服务器将向我发送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响应

我想我错过了什么


共 (1) 个答案

  1. # 1 楼答案

    解决了

    错误来自服务器端:我的响应没有包含任何标题

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