webclient 的实现如下:
public <T> WebClient.ResponseSpec sendRequest(HttpMethod method, String contentType, T body, String baseUrl, String path) {
try {
WebClient webClient = WebClient.builder().baseUrl(baseUrl).filter(logRequest()).build();
WebClient.ResponseSpec responseSpec = webClient.method(method)
.uri(path)
.header(HttpHeaders.CONTENT_TYPE, contentType)
.body(BodyInserters.fromObject(body))
.retrieve();
return responseSpec;
} catch (Exception e) {
throw new WebClientProcessingException("Exception when trying to execute request", e);
}
}
// This method returns filter function which will log request data
private static ExchangeFilterFunction logRequest() {
return ExchangeFilterFunction.ofRequestProcessor(clientRequest -> {
LOGGER.info("Request: {} {} {}", clientRequest.method(), clientRequest.url(), clientRequest.body());
clientRequest.headers().forEach((name, values) -> values.forEach(value -> LOGGER.info("{}={}", name, value)));
return Mono.just(clientRequest);
});
}
还有以下代码,创建用户对象和包含用户对象的命令,然后调用webclient发送请求
@Autowired
private BaseWebClient baseWebClient;
@Override
public void saveOrUpdateUser() {
UserPayload userPayload = new UserPayload();
userPayload.setUserId(111L);
userPayload.setCreatedAt(ZonedDateTime.now(DateTimeProps.systemTimeZone));
UserCommand userCommand = new UserCommand();
userCommand.setUser(userPayload);
baseWebClient.sendRequest(HttpMethod.POST, "application/json",
Stream.of(userCommand).collect(Collectors.toList()),
"http://localhost:8080",
"/users").onStatus(HttpStatus::isError, clientResponse -> {
throw new WebClientUserSaveOrUpdateeFailedException("Exception when trying to update user state")
.bodyToMono(String.class);
});
}
用户有效负载:
@Data
@NoArgsConstructor
@AllArgsConstructor
public class UserPayload {
Long userId;
ZonedDateTime createdAt;
}
用户命令:
@Data
@NoArgsConstructor
@AllArgsConstructor
public class UserCommand {
@JsonProperty("user")
UserPayload user;
}
Json 正在等待我的其他应用程序(我正在向其发送请求):
[
{ "user":
{
"userId": 1,
"createdAt": "2019-05-16T08:24:46.412Z"
}
}
]
使用:Spring boot 2、Lombok(用于 getter/setter)、gradle
当我尝试发送请求时没有任何反应。甚至也不例外。
我尝试过非常简单的案例以及同样的问题。
还有一点需要注意的是,是否可以记录正文?我的意思是以某种方式看到最终的 json
我想我错过了一些一般性的东西。