简体   繁体   中英

A message body writer for Java type, class myPackage.Sample, and MIME media type, application/xml, was not found

I am using Jersey RESTful webservices. I wrote client as below but it throws above exception which i mentioned in the title.

public class MyRestClient {
    public static void main(String[] args) {    
        Client client = Client.create();        
        WebResource resource = client.resource("http://localhost:8080/myapp/rest/a/update/123");    
        Sample b1 = new Sample("debris");     
        ClientResponse response = resource.type(MediaType.APPLICATION_XML).put(ClientResponse.class, b1);

    }
}

Someone told to annotate Sample class with @XmlRootElement . But i cannot do it since Sample is generated by third party. Any help ?

This is a little difficult to answer without seeing your REST service class, but I'm guessing you're trying to consume your data as a Sample object in your service, as so:

@PUT
public Response updateSample(Sample sample) {
...

But this relies on Jersey being able to automatically marshall your XML data into a Sample object, which would require the JAXB annotations on the Sample class, as you pointed out, and since those are missing you are getting the error you describe.

instead, you can consume it as a String in your service, like so:

@PUT
public Response updateSample(String sampleStr) {
...

But now you're responsible for parsing your sampleStr data as xml and converting it into a Sample object (which is not necessarily a bad thing). But, since the Sample class is not annotated for XML, Jersey won't even be able to convert it into XML for your client to send.

See this article for more information on different ways to transfer data back and forth with Jersey REST services: http://usna86-techbits.blogspot.com/2013/08/restful-java-web-service-marshalling.html

You might have an easier time processing it manually on the server if you pass your data as JSON. Look at the JUnit test class towards the bottom of that article for ideas on how to do that.

Please include your service class if you need more assistance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM