使用 Apache HttpClient 4 的抢先式基本身份验证

新手上路,请多包涵

是否有比 此处 描述的方法更简单的方法来设置 http 客户端以进行抢占式基本身份验证?

在以前的版本 (3.x) 中,它曾经是一个简单的方法调用(例如 httpClient.getParams().setAuthenticationPreemptive(true) )。

我想避免的主要事情是将 BasicHttpContext 添加到我执行的每个方法中。

原文由 yossis 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 682
2 个回答

如果不每次都传递上下文,很难做到这一点,但您可以通过使用请求拦截器来做到这一点。这是我们使用的一些代码(从他们的 JIRA,iirc 中找到):

 // Pre-emptive authentication to speed things up
BasicHttpContext localContext = new BasicHttpContext();

BasicScheme basicAuth = new BasicScheme();
localContext.setAttribute("preemptive-auth", basicAuth);

httpClient.addRequestInterceptor(new PreemptiveAuthInterceptor(), 0);

(...)

static class PreemptiveAuthInterceptor implements HttpRequestInterceptor {

    public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
        AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);

        // If no auth scheme avaialble yet, try to initialize it
        // preemptively
        if (authState.getAuthScheme() == null) {
            AuthScheme authScheme = (AuthScheme) context.getAttribute("preemptive-auth");
            CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
            HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
            if (authScheme != null) {
                Credentials creds = credsProvider.getCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()));
                if (creds == null) {
                    throw new HttpException("No credentials for preemptive authentication");
                }
                authState.setAuthScheme(authScheme);
                authState.setCredentials(creds);
            }
        }

    }

}

原文由 Mat Mannion 发布,翻译遵循 CC BY-SA 2.5 许可协议

如果您希望强制 HttpClient 4 对单个请求进行身份验证,则以下方法将起作用:

 String username = ...
String password = ...
UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);

HttpRequest request = ...
request.addHeader(new BasicScheme().authenticate(creds, request));

原文由 Adam Batkin 发布,翻译遵循 CC BY-SA 2.5 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题