how to set cookie for requests built via Resteasy Client API

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-24 03:22:38

问题


I am working on writing integration tests against web services that are annotated with JAX-RS annotations and secured with Spring Security. I use Resteasy Client proxy framework to generate proxies, from which I can invoke methods on to test the web services. For example, ResteasyClient client = new ResteasyClientBuilder().connectionPoolSize(10).connectionTTL(10, TimeUnit.SECONDS).build();

    ResteasyWebTarget target = client.target(properties.getRestWebBaseUrl());

    ProxyBuilder<UserClient> builder = target.proxyBuilder(UserClient.class);
    UserClient userClient = builder
            .defaultConsumes(MediaType.APPLICATION_JSON).build();

How do I add a cookie to the request being constructed by Resteasy? I have tried registering a ClientRequestFilter but it does not work.

Thanks,


回答1:


Registering a ClientRequestFilter does work, as follows :

ResteasyWebTarget target = client.target(properties.getRestWebBaseUrl());
Cookie cookie = new Cookie("foo", "bar");
client.register(new CookieClientRequestFilter(cookie));
ProxyBuilder<UserClient> builder = target.proxyBuilder(UserClient.class);
UserClient userClient = builder
        .defaultConsumes(MediaType.APPLICATION_JSON).build();

with :

import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.client.ClientRequestFilter;
import javax.ws.rs.core.Cookie;
import javax.ws.rs.ext.Provider;
import java.io.IOException;

@Provider
public class CookieClientRequestFilter implements ClientRequestFilter {
    private Cookie cookie;

    public CookieClientRequestFilter(Cookie cookie) {
        super();
        this.cookie = cookie;
    }

    @Override
    public void filter(ClientRequestContext clientRequestContext) throws IOException {
        List<Object> cookies = new ArrayList<>();
        cookies.add(this.cookie);
        clientRequestContext.getHeaders().put("Cookie", cookies);
    }
}


来源:https://stackoverflow.com/questions/23358105/how-to-set-cookie-for-requests-built-via-resteasy-client-api

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