如何使用 Micronaut 客户端注释映射 errorType,如果以编程方式我们可以提供主体类型和 errorType 对象以防成功和失败。
以编程方式调用客户端:
import io.micronaut.core.type.Argument;
import io.micronaut.http.HttpRequest;
import io.micronaut.http.HttpResponse;
import io.micronaut.http.MediaType;
import io.micronaut.http.client.DefaultHttpClient;
import io.micronaut.http.client.exceptions.HttpClientResponseException;
import io.micronaut.http.uri.UriBuilder;
import io.reactivex.Single;
import java.net.URL;
@Singleton
public class Test{
public User getUser(String id) {
try {
String uriPath = UriBuilder.of("url")
.queryParam("id", id)
.toString();
DefaultHttpClient httpClient = new DefaultHttpClient(new URL(""),httpClientConfiguration);
Single<HttpResponse<User>> single = Single.fromPublisher(httpClient.exchange(
HttpRequest.GET(uriPath).header(X_REQUEST_ID, REQUEST_ID).accept(MediaType.APPLICATION_JSON_TYPE),
Argument.of(User.class), //bodyType
Argument.of(Object.class) //errorType
));
HttpResponse<User> response = single.blockingGet();
User user = response.body();
return user;
} catch (HttpClientResponseException | Exception e ) {
}
}
}
使用注解调用客户端
import io.micronaut.http.HttpResponse;
import io.micronaut.http.MediaType;
import io.micronaut.http.annotation.Consumes;
import io.micronaut.http.annotation.Get;
import io.micronaut.http.annotation.Header;
import io.micronaut.http.client.annotation.Client;
import io.reactivex.Single;
@Client(value = "url",
path = "/user")
public interface TestClient {
@Get("?id=123")
@Consumes(MediaType.APPLICATION_JSON)
Single<HttpResponse<User>> getUser();
}