【发布时间】:2021-11-10 11:51:23
【问题描述】:
我正在构建一个从某些端点读取 JSON 响应的应用程序,并且我正在尝试使用 NTLM 身份验证在 Apache HttpClient 中进行身份验证:
负责身份验证的类 HttpConnector 在其实例化后立即尝试进行身份验证:
public static HttpConnector on(String username, String password) {
HttpConnector connector = new HttpConnector(username, password);
Credentials credentials = new NTCredentials(username, password, "host", "domain");
connector.getHttpClient().getState().setCredentials(AuthScope.ANY, credentials);
return connector;
}
但我总是得到响应代码 401 Unauthorized。正如我在互联网上阅读的,包括在 Stackoverflow 中的这里,我使用了我试图在 HttpClient 中全局设置的 NTCredentials。我已经在 Postman 中测试了端点,在那里我成功获得了 JSON 响应,但 HttpClient 无法连接。
在我使用 GetMethod 的代码中:httpMethod = new GetMethod(url);
这里我也尝试过配置身份验证,但还是不行:
private void configureMethod(HttpMethod httpMethod) throws MalformedChallengeException {
httpMethod.getHostAuthState().setAuthRequested(true);
httpMethod.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
httpMethod.setDoAuthentication(true);
httpMethod.getParams().setParameter(
HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(3, false));
httpMethod.getHostAuthState().setAuthRequested(true);
httpMethod.getHostAuthState().setAuthScheme(
new NTLMScheme(
String.format("ntlm %s:%s", username, password)));
}
在调试期间,我看到我得到:Connection reset by peer: socket write error。它发生在HttpMethodDirector::executeWithRetry(final HttpMethod method) 方法中。
谁能帮助我,Apache HttpClient 中正确的 NTLM 身份验证设置是什么?我真的可以使用全局凭据集,还是必须为我创建的每个 HttpMethod 设置凭据以及如何设置?
提前谢谢你!
【问题讨论】:
标签: apache-commons-httpclient ntlm-authentication