How can one get the full HTTP REST request body for a POST
request using Jersey?
In our case the data will be XML. Size would vary from 1K to 1MB.
The docs seem to indicate you should use MessageBodyReader
but I can't see any examples.
How can one get the full HTTP REST request body for a POST
request using Jersey?
In our case the data will be XML. Size would vary from 1K to 1MB.
The docs seem to indicate you should use MessageBodyReader
but I can't see any examples.
It does seem you would have to use a MessageBodyReader
here. Here's an example, using jdom:
import org.jdom.Document;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.Provider;
import javax.ws.rs.ext.MediaType;
import javax.ws.rs.ext.MultivaluedMap;
import java.lang.reflect.Type;
import java.lang.annotation.Annotation;
import java.io.InputStream;
@Provider // this annotation is necessary!
@ConsumeMime("application/xml") // this is a hint to the system to only consume xml mime types
public class XMLMessageBodyReader implements MessageBodyReader<Document> {
private SAXBuilder builder = new SAXBuilder();
public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) {
// check if we're requesting a jdom Document
return Document.class.isAssignableFrom(type);
}
public Document readFrom(Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) {
try {
return builder.build(entityStream);
}
catch (Exception e) {
// handle error somehow
}
}
}
Add this class to the list of resources your jersey deployment will process (usually configured via web.xml, I think). You can then use this reader in one of your regular resource classes like this:
@Path("/somepath") @POST
public void handleXMLData(Document doc) {
// do something with the document
}
I haven't verified that this works exactly as typed, but that's the gist of it. More reading here:
Turns out you don't have to do much at all.
See below - the parameter x
will contain the full HTTP body (which is XML in our case).
@POST
public Response go(String x) throws IOException {
...
}