7.1.2 Posting a Request Body

All the examples up until now have used the same HTTP method i.e GET. The HttpRequest interface has factory methods for all the different HTTP methods. The following table summarizes the available methods:

Table 1. HttpRequest Factory Methods
MethodDescriptionAllows Body

HttpRequest.GET(java.lang.String)

Constructs an HTTP GET request

false

HttpRequest.OPTIONS(java.lang.String)

Constructs an HTTP OPTIONS request

false

HttpRequest.HEAD(java.lang.String)

Constructs an HTTP HEAD request

false

HttpRequest.POST(java.lang.String,T)

Constructs an HTTP POST request

true

HttpRequest.PUT(java.lang.String,T)

Constructs an HTTP PUT request

true

HttpRequest.PATCH(java.lang.String,T)

Constructs an HTTP PATCH request

true

HttpRequest.DELETE(java.lang.String)

Constructs an HTTP DELETE request

true

A create method also exists to construct a request for any HttpMethod type. Since the POST, PUT and PATCH methods require a body, a second argument which is the body object is required.

The following example demonstrates how to send a simply String body:

Sending a String body

  1. Flowable<HttpResponse<String>> call = client.exchange(
  2. POST("/hello", "Hello John") (1)
  3. .contentType(MediaType.TEXT_PLAIN_TYPE)
  4. .accept(MediaType.TEXT_PLAIN_TYPE), (2)
  5. String.class (3)
  6. );

Sending a String body

  1. Flowable<HttpResponse<String>> call = client.exchange(
  2. POST("/hello", "Hello John") (1)
  3. .contentType(MediaType.TEXT_PLAIN_TYPE)
  4. .accept(MediaType.TEXT_PLAIN_TYPE), (2)
  5. String.class (3)
  6. )

Sending a String body

  1. val call = client.exchange(
  2. POST("/hello", "Hello John") (1)
  3. .contentType(MediaType.TEXT_PLAIN_TYPE)
  4. .accept(MediaType.TEXT_PLAIN_TYPE), String::class.java (3)
  5. )
1The POST method is used with the first argument being the URI and the second argument the body
2The content type and accepted type are set to text/plain (the default content type is application/json)
3The expected response type is a String