romixch romixch - 10 days ago 5x
JSON Question

How can I set a custom Content-Type to jax-rs client?

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

public interface MyEntityServiceV2 {
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):

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

Client client = ClientBuilder.newClient();
WebTarget 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.

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.

Oh and I can’t change the service declaration.

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


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.