romixch
romixch

Reputation: 580

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 {
    @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):

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.

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?

Upvotes: 3

Views: 2699

Answers (1)

Andrew Rueckert
Andrew Rueckert

Reputation: 5225

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.

Upvotes: 1

Related Questions