使用 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中文网其他相关文章!