【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>
在WebFlux的注解模式下没有找到有用的直接从 ServerHttpRequest 读取请求报文流的方法,下面是我自己摸索出来的方法,主要借鉴了Spring Security的源码, 重点是需要注入 Webflux的解码器
@Autowired
private ServerCodecConfigurer serverCodecConfigurer = null;
然后在进行如下处理:
@PostMapping("/connect")
public Mono<Void> connect(final ServerHttpRequest request, final ServerHttpResponse response) {
log.debug("connect...");
final ResolvableType reqDataType = ResolvableType.forClass(byte[].class);
return response.writeWith(serverCodecConfigurer.getReaders().stream()
.filter(reader -> reader.canRead(reqDataType, MediaType.ALL))
.findFirst()
.orElseThrow(() -> new IllegalStateException("No Data"))
.readMono(reqDataType, request, Collections.emptyMap())
.cast(byte[].class)
.map(bytes -> {
try {
final String reqBody = new String(bytes, StandardCharsets.UTF_8);
log.info("reqBody => \n {}", reqBody);
///TODO: 实现自己的业务
final NettyDataBufferFactory nettyDataBufferFactory = new NettyDataBufferFactory(new UnpooledByteBufAllocator(false));
return nettyDataBufferFactory.wrap("ok".getBytes(StandardCharsets.UTF_8));
} catch (Throwable ex) {
log.warn("connect-exp: {}", ex.getMessage());
return null;
}
})
);
}
来源:oschina
链接:https://my.oschina.net/u/4316432/blog/3143334