Search code examples
javarestjax-wsuser-agent

How to detect if a call to a REST server in java was from a mobile device?


I have developed a REST based server in java for Android devices and Desktop Devices and now I want to make a difference between those two entities.

I want to know when an Android device is accessing the methods(Create/Read/Update/Delete) and when Desktop Web App.

Here is a snapshot of my code:

@Path("/v2")
public class RESTfulGeneric {

@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/get")
public Response Get() {
        ResponseBuilder builder = Response.status(Response.Status.OK);
        ....
        return builder.build();
    }

@POST
@Consumes({MediaType.APPLICATION_JSON })
@Path("/create/{Name}")
public Response Post(String Table, @PathParam("Name") String Name) {

        ResponseBuilder builder = Response.status(Response.Status.OK);
        ..........
            return builder.build();
    }

}

How can I know, or what should verify in order to know that an Android device is calling those methods?

I know that there is this request.getHeader("User-Agent") that could help me, but this request is availabe only in Servlets.

Any idea?


Solution

  • You can grab the user-agent header from the request by adding a parameter to your request handling methods i.e.

    public Response Post(String Table, @PathParam("Name") String Name, @HeaderParam("user-agent") String userAgent) {
        if (userAgent.contains("Android")) {
            // mobile specific logic
        }
    }
    

    Here's a useful list of Android user-agents...

    http://www.gtrifonov.com/2011/04/15/google-android-user-agent-strings-2/