Pages

Tuesday, January 17, 2012

JAX-RS Tip of the Day: Use OPTIONS Method to Determine Resource Capabilities

Did you know that you can make an OPTIONS method call to a JAX-RS resource to determine its capabilites? JAX-RS supports a complete set of HTTP methods including OPTIONS.

If you make a specific URI request to a resource, it will return the supported methods like GET, PUT, HEAD, and OPTIONS. In addition, Jersey supports returning the WADL file by default. This allows tools like NetBeans to take advantage of the resource.

So I guess some examples are in order. The first example is a request to the server URI which in this case is GlassFish 3.1.1. This is followed by a request to a specific resource on the server instance.
curl -X OPTIONS -v http://localhost:8080
* About to connect() to localhost port 8080 (#0)
*   Trying ::1... Operation not permitted
*   Trying 127.0.0.1... connected
> OPTIONS / HTTP/1.1
> User-Agent: curl/7.22.0 (i686-pc-cygwin) libcurl/7.22.0 OpenSSL/0.9.8r zlib/1.2.5 libidn/1.22 libssh2/1.2.7
> Host: localhost:8080
> Accept: */*
>
< HTTP/1.1 200 OK
< X-Powered-By: Servlet/3.0 JSP/2.2 (GlassFish Server Open Source Edition 3.1.1 Java/Sun Microsystems Inc./1.6)
< Server: GlassFish Server Open Source Edition 3.1.1
< Allow: GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS
< Content-Length: 0
< Date: Tue, 17 Jan 2012 14:31:17 GMT
<
* Connection #0 to host localhost left intact
* Closing connection #0
As you can see the command reports that GlassFish supports all standard HTTP 1.1 methods as denoted by the Allow: header. This example calls a specific resource on the server which only supports a subset of the HTTP methods based on the annotations in the resource. The methods always supported by a resource are HEAD and OPTIONS, but this has two methods annotated as @GET and @POST. Additionally, not that the Content-Type: application/vnd.sun.wadl+xml is returned which includes the WADL for this particular resource.
curl -X OPTIONS -v http://localhost:8080/RESTApproachFormParameter/resources/example
* About to connect() to localhost port 8080 (#0)
*   Trying ::1... Operation not permitted
*   Trying 127.0.0.1... connected
> OPTIONS /RESTApproachFormParameter/resources/example HTTP/1.1
> User-Agent: curl/7.22.0 (i686-pc-cygwin) libcurl/7.22.0 OpenSSL/0.9.8r zlib/1.2.5 libidn/1.22 libssh2/1.2.7
> Host: localhost:8080
> Accept: */*
>
< HTTP/1.1 200 OK
< X-Powered-By: Servlet/3.0 JSP/2.2 (GlassFish Server Open Source Edition 3.1.1 Java/Sun Microsystems Inc./1.6)
< Server: GlassFish Server Open Source Edition 3.1.1
< Allow: OPTIONS,POST,GET,HEAD
< Content-Type: application/vnd.sun.wadl+xml
< Content-Length: 1085
< Date: Tue, 17 Jan 2012 15:01:49 GMT
<
* Connection #0 to host localhost left intact
* Closing connection #0
In summary, you can take advantage of the OPTIONS method to determine what a particular resource will provide for you without any knowledge of the subject domain.

No comments:

Post a Comment