Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Consume Restful method from URL with Date Param Java

I have a restful web service method like this one:

@GET
@Path("/generateInfo")
@Produces(MediaType.APPLICATION_JSON)
public String generateInfo(
        @QueryParam("a") String a,
        @QueryParam("b") String b, 
        @QueryParam("date") Date date) {
    // ...business code...
    return "hello world";
}

How can I invoke that method from a WebBrowser?, the problem is the Date param that when i try is giving me 404 not found or 500 internal server error.

like image 975
Sergio Avatar asked Feb 14 '13 16:02

Sergio


1 Answers

I would suggest accepting the date as a String and parsing it yourself. Like so:

@GET
@Path("/generateInfo")
@Produces(MediaType.APPLICATION_JSON)
public String generateInfo(
        @QueryParam("a") String a,
        @QueryParam("b") String b, 
        @QueryParam("date") String date) {

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    Date dateObj = sdf.parse(date);

    return "hello world";
}

The way to make this request via a browser is:

http://localhost/your_service/generateInfo?date=2013-02-14

Things to consider when parsing dates:

  • SimpleDateFormat is very flexible with parsing different date formats. The ISO standard for date strings is: yyyy-MM-dd

  • The Joda Java date API is accepted as a more complete implementation of date/time, and some believe that it is more optimised than Java's native date API particularly for parsing dates.

  • it is often better to provide dates as epoch timestamps, especially if your application operates over different timezones. However, you must be aware of HTTP caching issues when accepting epoch timestamps (e.g. if your clients are not truncating epoch timestamps then you will get lots of cache misses). I would refer back to ISO-8601 as formatted dates are easier to HTTP cache.

like image 110
pestrella Avatar answered Sep 27 '22 21:09

pestrella