1

我正在测试Apache HttpAsyncClient,特别是我想在需要身份验证的地方发出异步 HTTP POST 请求。我用这个例子作为参考。到目前为止,我发现了如何设置应用程序类型和正文,但不知道如何设置凭据。

我尝试添加身份验证凭据

    HttpAsyncClientBuilder create = HttpAsyncClientBuilder.create();
    create.setTargetAuthenticationStrategy(new TargetAuthenticationStrategy());
    BasicCredentialsProvider basicCredentialsProvider = new BasicCredentialsProvider();
    Credentials defaultcreds = new UsernamePasswordCredentials("user", "password");
    basicCredentialsProvider.setCredentials(new AuthScope("http://localhost", 7351), defaultcreds);
    create.setDefaultCredentialsProvider(basicCredentialsProvider);

    final CloseableHttpAsyncClient httpclient = create.build();
    httpclient.start();
    ...

但我总是得到

    Sep 11, 2013 4:21:35 PM org.apache.http.impl.auth.HttpAuthenticator handleAuthChallenge
    WARNING: Malformed challenge: Authentication challenge is empty

我还没有找到解释如何为 CloseableHttpAsyncClient 设置身份验证数据的示例。任何人都可以帮助我吗?

4

1 回答 1

0

如果您希望默认情况下所有请求都共享凭据提供程序,则可以在客户端级别设置凭据提供程序

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom()
            .setDefaultCredentialsProvider(credentialsProvider)
            .build();
    httpclient.start();
    try {
        HttpGet request = new HttpGet("http://www.apache.org/");
        Future<HttpResponse> future = httpclient.execute(request, null);
        HttpResponse response = future.get();
        System.out.println("Response: " + response.getStatusLine());
        System.out.println("Shutting down");
    } finally {
        httpclient.close();
    }
    System.out.println("Done");

或将其设置在请求级别,如果您希望它仅应用于特定请求

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
    httpclient.start();
    try {
        HttpGet request = new HttpGet("http://www.apache.org/");
        HttpClientContext context = HttpClientContext.create();
        context.setCredentialsProvider(credentialsProvider);
        Future<HttpResponse> future = httpclient.execute(request, context, null);
        HttpResponse response = future.get();
        System.out.println("Response: " + response.getStatusLine());
        System.out.println("Shutting down");
    } finally {
        httpclient.close();
    }
    System.out.println("Done");

另请注意,Malformed challenge: Authentication challenge is empty警告可能是由服务器发送格式错误(空)的身份验证质询而不是 HttpClient 配置引起的。为请求提供用户凭据可能不一定能解决问题。

于 2013-09-12T09:15:21.773 回答