如何将自定义Content-Type设置为jax-rs客户端?

时间:2022-03-29 19:36:26

I am running some JAX-RS resources declared like this:

我正在运行一些声明如下的JAX-RS资源:

public interface MyEntityServiceV2 {
    @PUT
    @Consumes({"application/myentity-v2+json"})
    @Produces({"application/myentity-v2+json"})
    @Path("/{uuid:[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}}")
    Response putMyEntity(@PathParam("uuid") String uuid, MyEntityDto myEntity);
}

Now I want to test them using the Jersey-Client (or any other client if it helps to fix my issue):

现在我想使用Jersey-Client(或任何其他客户端,如果它有助于解决我的问题)测试它们:

MyEntityDto dto = new MyEntityDto();
Entity<MyEntityDto> entity = Entity.entity(dto, MediaType.APPLICATION_JSON_TYPE);

Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://localhost:7001/path/" + UUID.randomUUID().toString());
Invocation.Builder builder = target.request("application/myentity-v2+json");
builder.header("Content-Type", "application/myentity-v2+json");
Response response = builder.put(entity);

Unfortunately this does not work. The request always contains a content type of application/json. And this does not match the interface on the server.

不幸的是,这不起作用。请求始终包含application / json的内容类型。这与服务器上的接口不匹配。

As an alternative I can create the entity with my custom MediaType which also leads to an error because it can’t find the MessageBodyWriter for that type.

作为替代方案,我可以使用我的自定义MediaType创建实体,这也会导致错误,因为它无法找到该类型的MessageBodyWriter。

Oh and I can’t change the service declaration.

哦,我无法更改服务声明。

What do you think is the best way to test this resource?

您认为测试此资源的最佳方式是什么?

1 个解决方案

#1


1  

Create an entity with your custom MediaType, and then register a custom MessageBodyWriter with your Client. It could be as simple as extending an existing MessageBodyWrite to return true when isWritable is called, or you may have to implement the writeTo method.

使用自定义MediaType创建实体,然后向客户端注册自定义MessageBodyWriter。它可以像在调用isWritable时将现有MessageBodyWrite扩展为返回true一样简单,或者您可能必须实现writeTo方法。

#1


1  

Create an entity with your custom MediaType, and then register a custom MessageBodyWriter with your Client. It could be as simple as extending an existing MessageBodyWrite to return true when isWritable is called, or you may have to implement the writeTo method.

使用自定义MediaType创建实体,然后向客户端注册自定义MessageBodyWriter。它可以像在调用isWritable时将现有MessageBodyWrite扩展为返回true一样简单,或者您可能必须实现writeTo方法。