如何为通过Resteasy Client API构建的请求设置cookie

时间:2014-04-29 07:20:52

标签: java cookies resteasy

我正在编写针对使用JAX-RS注释注释并使用Spring Security保护的Web服务的集成测试。我使用Resteasy Client代理框架来生成代理,我可以从中调用方法来测试Web服务。例如, 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();

如何在Resteasy构建的请求中添加cookie?我已经尝试注册ClientRequestFilter但它不起作用。

谢谢,

1 个答案:

答案 0 :(得分:6)

注册ClientRequestFilter确实有效,如下所示:

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);
    }
}