-
Notifications
You must be signed in to change notification settings - Fork 43
java_conneg
<%= render :partial => 'shared/negotiation' %>
## Client side content negotiation
By default, all Restfulie client requests will not add anything to the Accept header so the server is free to provide the representation using any media type:
Response response = Restfulie.at('http://myhotels.caelum.com/1').get(); Hotel hotel = reponse.getResource(); System.out.println(hotel.getName());
By executing the above code, the client is unaware of which media type was used. Typical clients will notify its client API (Restfulie) which media types it is capable of handling. The following source code shows how to add the Accept header with two options, json:
Response response = Restfulie.at("http://myhotels.caelum.com/1").accepts("application/json").get()
// print the media type used to produce the response
System.out.println(response.getHeaders("Content-type"));
Hotel hotel = reponse.getResource();
System.out.println(hotel.getName());
The client can use the 'Content-type' http reader to communicate with the server showing the how the information been sent is represented.
Card card = new Card(4444);
// The card information will be sent as an xml, and the server will be aware of it throught Content-type
Response response = Restfulie.at("http://myhotels.caelum.com/1").as("application/xml").accept("application/json").post(card)
// print the media type used to produce the response
System.out.println(response.getHeader("Content-type"));
If both Content-type and Accept must be informated as above, and with the same representation, you can use a shortcut for it.
Card card = new Card();
// The handling() method will add application/xml for both Accept/Content-type header
Response response = Restfulie.at("http://myhotels.caelum.com/1").handling("application/xml").post(card)
// print the media type used to produce the response
System.out.println(response.getHeader("Content-type"));
Currently Restfulie Java supports the default xml, json representations.
TODO
If the service does not understand the media type sent, it will return a 406 Unaccepted response. The client is responsible for checking the response status and act accordingly.
Restfulie goes ahead and provides something more. The ConnegWhenUnaccepted feature allows your clients to retry a request if the service did not accept the media type you tried to send.
The client will automatically check if any of the media types supported by the service (through the Accept response header) is supported by the client itself, if so, it will re-send the response using the new media type.
Look at the features page for more details.