我正在寻找一种方法将包含param名称和值的地图传递给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
}
}
答案 0 :(得分:2)
在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