gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 09:08:03 30 4
gpt4 key购买 nike

我正在致力于针对使用 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();

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

谢谢

最佳答案

注册 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();

与:

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

关于java - 如何为通过 Resteasy Client API 构建的请求设置 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23358105/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com