How to send a query params map using RESTEasy proxy client(如何使用RESTEasy代理客户端发送查询参数图)
问题描述
我正在寻找一种将包含参数名称和值的映射传递给Get Web Target的方法。我希望RESTEasy将我的映射转换为URL查询参数列表;然而,RESTEasy抛出了一个异常,说明Caused by: javax.ws.rs.ProcessingException: RESTEASY004565: A GET request cannot have a body.
。如何告诉RESTEasy将此映射转换为URL查询参数?
这是代理接口:
@Path("/")
@Consumes(MediaType.APPLICATION_JSON)
public interface ExampleClient {
@GET
@Path("/example/{name}")
@Produces(MediaType.APPLICATION_JSON)
Object getObject(@PathParam("name") String name, MultivaluedMap<String, String> multiValueMap);
}
用法如下:
@Controller
public class ExampleController {
@Inject
ExampleClient exampleClient; // injected correctly by spring DI
// this runs inside a spring controller
public String action(String objectName) {
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
// in the real code I get the params and values from a DB
params.add("foo", "bar")
params.add("jar", "car")
//.. keep adding
exampleClient.getObject(objectName, params); // throws exception
}
}
推荐答案
深入研究RESTEasy源代码几个小时后,我发现通过接口注释无法做到这一点。简而言之,RESTEasy从org.jboss.resteasy.client.jaxrs.internal.proxy.processors.ProcessorFactory
创建一个称为‘处理器’的东西来将注释映射到目标URI。
ClientRequestFilter
来解决这个问题真的很简单,它从请求主体(当然是在执行请求之前)获取Map,并将它们放在URI查询参数中。检查以下代码:
筛选器:
@Provider
@Component // because I'm using spring boot
public class GetMessageBodyFilter implements ClientRequestFilter {
@Override
public void filter(ClientRequestContext requestContext) throws IOException {
if (requestContext.getEntity() instanceof Map && requestContext.getMethod().equals(HttpMethod.GET)) {
UriBuilder uriBuilder = UriBuilder.fromUri(requestContext.getUri());
Map allParam = (Map)requestContext.getEntity();
for (Object key : allParam.keySet()) {
uriBuilder.queryParam(key.toString(), allParam.get(key));
}
requestContext.setUri(uriBuilder.build());
requestContext.setEntity(null);
}
}
}
PS:为简单起见,我使用了Map
而不是MultivaluedMap
这篇关于如何使用RESTEasy代理客户端发送查询参数图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!