Ion Morozan
Ion Morozan

Reputation: 783

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?

Upvotes: 2

Views: 4601

Answers (2)

Rys
Rys

Reputation: 5164

In case of using spring mvc you can use @RequestHeader annotation

Upvotes: 1

mmccomb
mmccomb

Reputation: 13817

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/

Upvotes: 2

Related Questions