How to get full REST request body using Jersey?
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.
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 {
...
}
You could use the @Consumes annotation to get the full body:
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
@Path("doc")
public class BodyResource
{
@POST
@Consumes(MediaType.APPLICATION_XML)
public void post(Document doc) throws TransformerConfigurationException, TransformerException
{
Transformer tf = TransformerFactory.newInstance().newTransformer();
tf.transform(new DOMSource(doc), new StreamResult(System.out));
}
}
Note : Don't forget the "Content-Type: application/xml" header by the request.
Try this using this single code:
import javax.ws.rs.POST;
import javax.ws.rs.Path;
@Path("/serviceX")
public class MyClassRESTService {
@POST
@Path("/doSomething")
public void someMethod(String x) {
System.out.println(x);
// String x contains the body, you can process
// it, parse it using JAXB and so on ...
}
}
The url for try rest services ends .... /serviceX/doSomething
链接地址: http://www.djcxy.com/p/12360.html