Skip to content

Sending a Request Body

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

The body of a request can be used to send content expected by the remote service. 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. Filling a Request Body

To send a plain CharSequence within the request body, simply annotate the argument with @Entity.

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

...

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

request-body: sahan@example.com


####2. Apache HC HTTP Entities

Apache HC refers to a request with a body as an HttpEntityEnclosingRequest. Such a request may contain an implementation of HttpEntity which provides the body content. A request definition may specify an HttpEntity directly by annotating it with @Entity.

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

...

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

request-body: sahan@example.com


####3. Request Entity Translation

If @Entity does not annotate an HttpEntity, the annotated argument will be translated to an appropriate implementation of HttpEntity based on its type. This translation proceeds as outlined below.

Order Argument Type Translated Entity
1 byte[], Byte[] ByteArrayEntity
2 java.io.File FileEntity
3 java.io.InputStream BufferedHttpEntity
4 CharSequence StringEntity
5 java.io.Serializable SerializableEntity

```java

@PUT("/documents/new") void putDocument(@Entity File document);

...

endpoint.putDocument(new File(documentUri));

> `request-body: <contents of file>`