I am implementing a custom MessageBodyReader
that needs to resolve URIs against the request URI during processing. If the MessageBodyReader
is used in a JAX-RS server implementation, which eg. processes incoming POST requests, I can obtain the request URI from a UriInfo
object that is injected at runtime using @Context
(as described eg. at https://stackoverflow.com/a/3314076):
public class MyProvider implements MessageBodyReader {
@javax.ws.rs.core.Context
javax.ws.rs.core.UriInfo uriInfo;
@Override
public Iterable<URI> readFrom(Class<Iterable<URI>> clazz, Type genericType,
Annotation annotations[], MediaType mediaType,
MultivaluedMap httpHeaders, InputStream entityStream)
throws IOException, WebApplicationException {
URI requestURI = uriinfo.getAbsolutePath(); // NPE if called in a client
// Parsing entityStream resolving relative URIs using requestURI
}
}
If the MessageBodyReader
is called in a JAX-RS client implementation during the reading of an Response
's entity, the injection does not happen, hence I get a NullPointerException
(see above for the line) when I write a client using JAX-RS like:
Iterable<URI> it = ClientBuilder.newClient().target("http://example.org/").request().get()
.readEntity(new GenericType<Iterable<URI>>(){});
With the aim of resolving URIs, my question is:
How do I find out the request URI in readFrom(...)
in the case that the MessageBodyReader
is called in a JAX-RS client implementation?
My current workaround: Having read Chapter 10.4 "Filter and interceptor execution order" of the Jersey documentation, I found that in step 16, the ClientResponseFilter
, I have access to both the request URI and the response headers. Hence I wrote a ClientResponseFilter
that puts the request URI in a custom response header. Then, I can retrieve that custom header from the 5th parameter of readFrom(...)
.