簡體   English   中英

Java-使用Apache httpclient進行HTTPS基本身份驗證

[英]Java - HTTPS Basic authentification with Apache httpclient

我正在嘗試使用Apache httpclient從具有基本身份驗證的HTTPS服務器獲取一些數據(json數據->靜態服務器)。 SSL證書是自簽名的。 服務器對瀏覽器調用以及使用curl時的響應都很好。

但是,使用Java Apache httpclient則是另一回事了。

客戶端 :

基本身份驗證有效 :如果忘記授權標頭或設置錯誤的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響應,而是有效的HTTP S響應!

我想我缺少了什么...

解決了!

錯誤是來自服務器端的 :我的響應未包含任何標頭。

httpclient似乎很喜歡服務器發出的響應。 對於瀏覽器或curl而言,情況並非如此: 它們可以接收垃圾,顯示垃圾桶

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM