问题
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