使用Java 中的基本驗證進行驗證
要模擬對HTTP 要求使用基本驗證的curl 指令,可以使用HttpClient庫在爪哇。然而,在使用這個庫時遇到了一些問題。
第一次嘗試使用 Commons HttpClient 3.0 時,回傳了 500 內部伺服器錯誤。有問題的程式碼是:
import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.UsernamePasswordCredentials; import org.apache.commons.httpclient.auth.AuthScope; import org.apache.commons.httpclient.methods.PostMethod; ... // Set authentication credentials client.getState().setCredentials( new AuthScope("ipaddress", 443, "realm"), new UsernamePasswordCredentials("test1", "test1") ); ...
使用 Commons HttpClient 4.0.1 時發生同樣的錯誤:
import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; ... // Set authentication credentials httpclient.getCredentialsProvider().setCredentials( new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials("test1", "test1") ); ...
問題在於處理驗證的方式。使用 HttpClient 4 進行基本驗證的正確方法是在發送請求之前設定「Authorization」標頭:
// Create a Base64 encoded string for the credentials String encoding = Base64.getEncoder().encodeToString((user + ":" + pwd).getBytes()); // Create the HTTP request with the correct header HttpPost httpPost = new HttpPost("http://host:port/test/login"); httpPost.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + encoding); // Execute the request and handle the response accordingly HttpResponse response = httpClient.execute(httpPost);
按照此方法,可以使用 Java 中的 HttpClient 庫成功實現基本驗證。
以上是如何在Java中使用HttpClient實現基本身份驗證?的詳細內容。更多資訊請關注PHP中文網其他相關文章!