RESTEasy 客户端框架身份验证凭据

2022-09-03 18:12:05

RESTEasy(JAX-RS实现)有一个很好的客户端框架,例如:

ServiceApi client = ProxyFactory.create(ServiceApi.class, baseUri);

如何向此客户端提供 HTTP 身份验证凭据?


答案 1

jnorris的答案使用了一些不推荐使用的类。下面是使用未弃用类的更新方法。

    import org.apache.http.HttpStatus;
    import org.apache.http.auth.Credentials;
    import org.apache.http.auth.UsernamePasswordCredentials;
    import org.apache.http.impl.client.DefaultHttpClient;
    ...
    DefaultHttpClient httpClient = new DefaultHttpClient();

    Credentials credentials = new UsernamePasswordCredentials(userName,
            password);
    httpClient.getCredentialsProvider().setCredentials(
            org.apache.http.auth.AuthScope.ANY, credentials);

    ClientExecutor clientExecutor = new ApacheHttpClient4Executor(
            httpClient);
    proxy = ProxyFactory
            .create(UserAccessProxy.class, host, clientExecutor);

答案 2

可以使用 ClientExcutor 提供凭据。

   Credentials credentials = new UsernamePasswordCredentials(userId, password);
   HttpClient httpClient = new HttpClient();
   httpClient.getState().setCredentials(AuthScope.ANY, credentials);
   httpClient.getParams().setAuthenticationPreemptive(true);

   ClientExecutor clientExecutor = new ApacheHttpClientExecutor(httpClient);

   ServiceApi client = ProxyFactory.create(ServiceApi.class, baseUri, clientExecutor);

推荐