使用 Jersey 将对象传递给 REST Web 服务

2022-01-21 00:00:00 java jersey

I have a simple WS that is a @PUT and takes in an object

@Path("test")
public class Test {

    @PUT
    @Path("{nid}"}
    @Consumes("application/xml")
    @Produces({"application/xml", "application/json"})
    public WolResponse callWol(@PathParam("nid") WolRequest nid) {
        WolResponse response = new WolResponse();
        response.setResult(result);
        response.setMessage(nid.getId());

        return response;
    }

and my client side code is...

WebResource wr = client.resource(myurl);
WolResponse resp = wr.accept("application/xml").put(WolResponse.class, wolRequest);

I am trying to pass an instance of WolRequest into the @PUT Webservice. I am constantly getting 405 errors trying to do this..

How can I pass an object from the client to the server via Jersey ? Do I use a query param or the request ?

Both my POJOs (WolRequest and WolResponse) have the XMlRootElement tag defined so i can produce and consume xml..

解决方案

Check this link https://www.vogella.com/tutorials/REST/article.html

As per the code sample of method putTodo of class TodoResource , your code should be like this.

@Path("test")
public class Test{

    @PUT
    @Consumes("application/xml")
    @Produces({"application/xml", "application/json"})
    public WolResponse callWol(JAXBElement<WolRequest> nid) {
        WolResponse response = new WolResponse();
        response.setResult(result);
        response.setMessage(nid.getValue().getId());

        return response;
   }
}

Hope this will solve your problem.

相关文章