Micronaut HTTP Client - just the response body

In a previous post, we used io.micronaut.http.client.BlockingHttpClient to get response from an HTTP endpoint. We used the exchange method as follows.

HttpResponse response = client.toBlocking().exchange("/greeting", String)
If you are using Java instead of Groovy, you will pass "String.class" instead of "String".

We had to pass an extra argument to get the response body. There are cases when all you need is the response body as a Java object. For these cases, you could make use of the retrieve method as follows.

package com.nareshak.demo

import io.micronaut.http.client.annotation.Client
import io.micronaut.runtime.server.EmbeddedServer
import io.micronaut.test.annotation.MicronautTest
import io.micronaut.http.client.RxHttpClient
import spock.lang.AutoCleanup
import spock.lang.Specification
import spock.lang.Shared

import javax.inject.Inject

class GreetingControllerSpec extends Specification {

    @Shared @Inject
    EmbeddedServer embeddedServer

    @Shared @AutoCleanup @Inject @Client("/")
    RxHttpClient client

    def "greeting endpoint should return Hello"() {
        String result = client.toBlocking().retrieve("/greeting")

        result == "Hello"

Let's compare the two methods.

HttpResponse response = client.toBlocking().exchange("/greeting", String)
String result = client.toBlocking().retrieve("/greeting")

When using the retrieve method, String is the default response body type. Hence we didn't have to pass it as an argument. Also, the method readily returns the response body. Thus we saved a few additional method calls, which we had to invoke when the exchange method returned an instance of HttpResponse.

If your endpoint returns an instance of Greeting class, you could invoke retrieve as follows.

Greeting greeting = client.toBlocking().retrieve("/greeting", Greeting)

Now both exchange and retrieve have their use-cases. If all you want is the response body, the retrieve method helps you to be concise and straightforward. If you are also interested in the response status or headers, you will have to opt for the exchange method. If you are writing test cases, it's unlikely you write any conditional logic based on the response status (they should be separate test cases). Hence retrieve is the most favourable option here.

Micronaut version used: 2.0.0.

Show Comments