我想根据状态来决定在用WebClient做一个HTTP请求后要做什么。我见过一些例子,当状态不是OK时,人们抛出Mono.error(),但是当捕捉到异常时,我们无法访问正文。
我尝试只返回ClientResponse,但是一旦传递调用,主体就会被消耗掉,所以主体是空的。我有类似下面这样的代码:
WebClient client = WebClient.builder()
.baseUrl("https://jsonplaceholder.typicode.com")
.build();
ClientResponse response = client.post().uri("/posts")
.body(BodyInserters.fromValue("{id: 101, title: 'foo', body: 'bar', userId: 1}"))
.exchangeToMono(apiResponse -> {
return Mono.just(apiResponse);
})
.block();
if (response.statusCode().equals(HttpStatus.OK)) {
// do something
} else {
String body = response.bodyToMono(String.class).block(); // this is empty because the body is consumed, I think
}那么,在使用WebClient时,有没有什么方法可以直接获取原始响应呢?或者我应该使用其他东西?
发布于 2021-03-16 04:26:08
我转而使用OkHttp,因为它可以更好地控制响应。你可以这样做:
OkHttpClient client = new OkHttpClient();
String json = "{\"id\": 101, \"title\": \"foo\", \"body\": \"bar\", \"userId\": 1}";
MediaType JSON = MediaType.get("application/json; charset=utf-8");
RequestBody body = RequestBody.create(json, JSON);
Request request = new Request.Builder()
.url("https://jsonplaceholder.typicode.com/posts")
.post(body)
.build();
Call call = client.newCall(request);
Response response = call.execute();
int statusCode = response.code();
String bodyString = response.body().string();https://stackoverflow.com/questions/66608869
复制相似问题