Skip to content

Receiving a Response Body

Lahiru Sahan Jayasinghe edited this page Jan 5, 2014 · 2 revisions

The body of a response may contain the results of a request invocation. This is quite common in RESTful services where the targeted resource is communicated between the server and the client using the request and response bodies.


####1. Extracting a Response Body

To extract the body of a response as a plain String, simple define the return type of the method as a CharSequence.

@GET("/users/{user}")
String getUser(@PathParam("user") String user);

...

String response = gitHubEndpoint.getUser("sahan");

response: { "login": "sahan", "id": 1979186, "avatar_url": ... }


####2. Ignoring a Response Body

If you have no use for the response body and wish to simply ignore it, define the return type of the method as void or Void.

@POST("/user/emails")
void addEmail(@Entity String email);

...

gitHubEndpoint.addEmail("sahan@example.com");

response-body (ignored): sahan@example.com


####3. Receiving `HttpResponse` and `HttpEntity`

If the return type is defined as HttpResponse, no special action will taken to process the response body. The response given by Apache HC will be returned as it is. Likewise, if the return type is defined as HttpEntity, the raw HttpEntity contained within the HttpResponse is returned. Refer the documentation on HttpResponse and HttpEntity for more information.

@GET("/users/{user}")
HttpResponse getUser(@PathParam("user") String user);

@GET("/users/{user}/gists")
HttpEntity getGists(@PathParam("user") String user);

...

HttpResponse response = gitHubEndpoint.getUser("sahan");
HttpEntity entity = gitHubEndpoint.getGists("sahan");

response.getEntity(): { "login": "sahan", "id": 1979186, "avatar_url": ... }
entity: [ { "url": "https://api.github.com/gists/352cfb... ]


####4. Status Codes `204` and `205`

Responses with the status codes 204 and 205 represent a success status but do not return any content. A brief summary of these status codes are given below.

Code Name Description
204 No Content Response content should not be expected, e.g. a DELETE request.
205 Reset Content Instructs a reset on the client, e.g. to clear the submission form.

Unless the return type is void or Void, a request which receives a response with either of these codes will return null.