Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
277 views
in Technique[技术] by (71.8m points)

java - Passing an object to a REST Web Service using 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..

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think the usage of the @PathParam is not correct here. A @PathParam is can basically be a String (see its javadoc for more info).

You can

  1. use the @PathParam as a String parameter or
  2. don't define WolRequest as a @PathParam.

The first approach:

@Path("test")
public class Test {

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

        return response;
    }

This will accept urls like: "text/12", 12 will then be the String nid. It doesn't look like this will help what you are trying to do.

The second approach:

@Path("test")
public class Test {

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

        return response;
    }

Your client code can be like you specified, only the url for PUT is: "test". Perhaps you need a combination of both one @PathParam for your id and one "normal" parameter to get your request data.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...