问题
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