问题描述: 在 Apache HTTP Client 5.3 版本中,NTCredentials(用于NTLM身份验证)不再起作用。
解决方法: 可以通过使用 HttpClient 5.3 提供的新的身份验证方式来解决此问题。下面是一个示例代码,展示了如何使用新的身份验证方式进行NTLM身份验证。
import org.apache.hc.client5.http.auth.*;
import org.apache.hc.core5.http.*;
import org.apache.hc.core5.http.auth.*;
public class HttpClientExample {
public static void main(String[] args) throws Exception {
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY,
new NTCredentials("username", "password", "workstation", "domain"));
HttpClientContext context = HttpClientContext.create();
context.setCredentialsProvider(credsProvider);
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet("http://example.com");
HttpResponse response = client.execute(request, context);
System.out.println(response.getStatusLine().getStatusCode());
}
}
在上面的示例中,我们首先创建了一个 CredentialsProvider
,并设置了NTLM凭据。然后,我们创建了一个 HttpClientContext
,并将 CredentialsProvider
设置为上下文的凭据提供者。接下来,我们创建一个 HttpClient
,并执行一个带有身份验证的GET请求。
注意事项:
在使用这个示例代码时,请确保将 username
,password
,workstation
和 domain
替换为实际的值。
此外,还应该确保将以下依赖项添加到项目的 pom.xml 文件中:
org.apache.httpcomponents.client5
httpclient5
5.3
org.apache.httpcomponents.client5
httpclient5-win
5.3
这些依赖项将为你提供所需的类和方法来实现新的身份验证方式。