Shekhar Khairnar
Shekhar Khairnar

Reputation: 2691

RESTful web service - multiple POST methods. How to called a specific one from android application?

I have written a web service using a RESTful approach and I have more than one method which accept POST requests, like:

@Path("/user")
class User{
    @POST
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    @Produces(MediaType.APPLICATION_JSON)
    public UserMasterDto getUserDetails(MultivaluedMap<String, String> userParams) {
         // other stuff..
    }

    @POST
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    @Produces(MediaType.APPLICATION_JSON)
    public UserMasterDto getUserDetails2(MultivaluedMap<String, String> userParams){
         // other stuff..
    }
}

I want to call a specific method, say getUserDetails2, from an Android application. What do I need to do?

Upvotes: 0

Views: 4845

Answers (1)

Bogdan
Bogdan

Reputation: 24580

The way you currently have your service code setup I think it will throw some sort of media type conflict exception because you have two methods that both serve request on the same URL and for the same consuming media type.

If you want to call one or the other method, you need to disambiguate them. A very simple solution is something like this:

@Path("/user")
public class User {

    @Path("1")
    @POST
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    @Produces(MediaType.APPLICATION_JSON)
    public UserMasterDto getUserDetails(MultivaluedMap<String, String> userParams) {
        // ...
    }

    @Path("2")
    @POST
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    @Produces(MediaType.APPLICATION_JSON)
    public UserMasterDto getUserDetails2(MultivaluedMap<String, String> userParams) {
        // ...
    }
}

Notice the extra @Path on the methods. Now from your client, if you access /user/1 the first method is called, if you access /user/2 the second one will be called.

You could even have just one method and discriminate based on the path parameter, something like this:

@Path("/user")
public class User {

    @Path("{x}")
    @POST
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    @Produces(MediaType.APPLICATION_JSON)
    public UserMasterDto getUserDetails(
            @PathParam("x") int x,
            MultivaluedMap<String, String> userParams) {

        if (x == 1) {
            //do something
        } else if (x == 2) {
            //do something else
        }

        // ...
    }
}

you can even use regular expressions and if multiple methods could apply for the same URL then there are some precedence rules triggered.

Just remember that REST is not about calling methods on the server but accessing resources. So to avoid confusions (people might think 1 and 2 are the IDs of some users) you might want to carefully chose your URLs (the above is just an example). It really depends on how you like it best and what your exact needs are.

Upvotes: 5

Related Questions