How to set HTTP header in RESTEasy 3.0 client framework (with ResteasyClientBuilder and ResteasyWebTarget)?

不问归期 提交于 2019-12-07 07:57:25

问题


I'm trying to figure out how to set HTTP headers similar to what was explained here:

  • How to set HTTP header in RESTEasy client framework?, or here
  • RESTEasy client framework authentication credentials

However, I want to use RESTeasy 3.0 functionality (ResteasyClientBuilder and ResteasyWebtarget) and not the deprecated ProxyFactory, as explained here:

  • What is the substitute for Resteasy ProxyFactory class

And just to clarify, I also do not want to set the header(s) on every request / don't want them to be passed to the client, I'd like them to be set on ResteasyClientBuilder/ResteasyWebtarget level if possible.


回答1:


Found a solution.

The trick is to register a ClientRequestFilter with the ResteasyClient (line #2 of the method below):

public Resource getResource(Credentials credentials) {
    ResteasyClient client = new ResteasyClientBuilder().build();
    client.register(new AuthHeadersRequestFilter(credentials));
    return client.target(restServiceRoot).proxy(Resource.class);
}

And then have your request filter do something like:

public class AuthHeadersRequestFilter implements ClientRequestFilter {

    private final String authToken;

    public AuthHeadersRequestFilter(Credentials credentials) {
        authToken = credentials.getAuthorizationHeader();
    }

    @Override
    public void filter(ClientRequestContext requestContext) throws IOException {
        requestContext.getHeaders().add("Authorization", authToken);
    }
}


来源:https://stackoverflow.com/questions/21763700/how-to-set-http-header-in-resteasy-3-0-client-framework-with-resteasyclientbuil

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!