How to call another rest api from my controller in Micronaut like in Spring-Boot RestTemplate?

主宰稳场 提交于 2020-02-07 05:10:30

问题


I have the following function from Spring Boot. I cannot do it with declarative client thus my uri domain changed after every call so i need a RestTemplate like in Spring Boot.

How can i achieve the same in Micronaut?

private static void getEmployees()
{
   final String uri = "http://localhost:8080/springrestexample/employees.xml";

   RestTemplate restTemplate = new RestTemplate();
   String result = restTemplate.getForObject(uri, String.class);

   System.out.println(result);
}

回答1:


Something like this is a good starting point...

import io.micronaut.http.HttpResponse;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
import io.micronaut.http.client.RxHttpClient;
import io.micronaut.http.client.annotation.Client;

import javax.inject.Inject;

@Controller("/")
public class SomeController {
    // The url does not have to be
    // hardcoded here.  Could be
    // something like
    // @Client("${some.config.setting}")
    @Client("http://localhost:8080")
    @Inject
    RxHttpClient httpClient;

    @Get("/someuri")
    public HttpResponse someMethod() {
        String result = httpClient.toBlocking().retrieve("/springrestexample/employees.xml");
        System.out.println(result);

        // ...

        return HttpResponse.ok();
    }
}

I hope that helps.

EDIT

Another similar approach:

import io.micronaut.http.HttpResponse;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
import io.micronaut.http.client.RxHttpClient;
import io.micronaut.http.client.annotation.Client;

@Controller("/")
public class SomeController {
    private final RxHttpClient httpClient;

    public SomeController(@Client("http://localhost:8080") RxHttpClient httpClient) {
        this.httpClient = httpClient;
    }

    @Get("/someuri")
    public HttpResponse someMethod() {
        String result = httpClient.toBlocking().retrieve("/springrestexample/employees.xml");
        System.out.println(result);

        // ...

        return HttpResponse.ok();
    }
}


来源:https://stackoverflow.com/questions/57002518/how-to-call-another-rest-api-from-my-controller-in-micronaut-like-in-spring-boot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!