
使用 HttpClient 在 Java 中实现 HTTP 基本身份验证
Prelude
尝试使用基本身份验证模拟curl命令时Java,考虑这一点至关重要以下:
HttpClient 3.0
1 2 3 4 5 6 7 8 9 10 11 12 | public class HttpBasicAuth {
public static void main(String[] args) {
client.getState().setCredentials(
new AuthScope( "hostname" ),
new UsernamePasswordCredentials( "username" , "password" )
);
}
}
|
登录后复制
HttpClient 4.0.1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | public class HttpBasicAuth {
public static void main(String[] args) {
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getCredentialsProvider().setCredentials(
new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
new UsernamePasswordCredentials( "username" , "password" )
);
}
}
|
登录后复制
常见问题
两者中在 HttpClient 3.0 和 4.0.1 示例中,由于范围定义无效,可能会出现内部服务器错误 (500)。正确的范围定义取决于目标服务器配置。通过将范围设置为 AuthScope.ANY_HOST 和 AuthScope.ANY_PORT,您假设凭据适用于任何主机和端口,但情况可能并非如此。验证目标服务器配置并使用适当的范围定义应该可以解决此错误。
替代方法 (HttpClient 4.0.1)
使用 HttpClient 实现基本身份验证的另一种方法4.0.1如下:
1 2 3 4 5 6 7 8 9 10 11 | public class HttpBasicAuth {
public static void main(String[] args) {
String encoding = Base64.getEncoder().encodeToString((user + ":" + pwd).getBytes());
HttpPost httpPost = new HttpPost( "http://host:post/test/login" );
httpPost.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + encoding);
}
}
|
登录后复制
以上是如何使用 HttpClient 在 Java 中实现 HTTP 基本身份验证:避免常见陷阱?的详细内容。更多信息请关注PHP中文网其他相关文章!