ClientResponse(org.springframework.web.reactive.function.client.ClientResponse)在使用WebClient时显示类之间的不一致 [英] ClientResponse(org.springframework.web.reactive.function.client.ClientResponse) showing inconsistency across the classes while using WebClient

查看:772
本文介绍了ClientResponse(org.springframework.web.reactive.function.client.ClientResponse)在使用WebClient时显示类之间的不一致的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开始使用WebClient(org.springframework.web.reactive.function.client.WebClient)调用其余服务.我有2个类,分别是Utility.java和ServiceImpl.java. ServiceImpl.java是我使用WebClient的地方.我正在拨打的帖子看起来像-

I have started using WebClient(org.springframework.web.reactive.function.client.WebClient) for calling rest services. I have 2 classes say Utility.java and ServiceImpl.java. ServiceImpl.java is where I use WebClient. A post call I am making looks like -

ClientResponse response = webClient.post()
            .uri(path)
            .body(Mono.just(inputDTO),InputDTO.class)
            .exchange()
            .block();

(上面的ClientResponse是org.springframework.web.reactive.function.client.ClientResponse) (我正在使用检索的即时交换,因为我想要标题以及状态码)

(ClientResponse above is org.springframework.web.reactive.function.client.ClientResponse) (I am using exchange instaed of retrive because I want headers as well as status code)

现在尝试将此响应转换为某些DTO-ResponseDTO.

Now trying to convert this response into some DTO - ResponseDTO.

Mono<ResponseEntity<ResponseDTO>> mono = response.toEntity(ResponseDTO.class);
        ResponseEntity<ResponseDTO> resEntity = mono.block();
        ResponseDTO myObj = resEntity.getBody();

所以myObj是ResponseDTO类的对象.

So myObj is an object of ResponseDTO class.

问题是-当我在实用程序类中执行将响应转换为ResponseDTO.java"时,我得到了myObj = null.但是,如果我在ServiceImpl.java中执行此操作(仅在调用post API之后),它将返回正确的主体(ResponseDTO对象). 即使我以ServiceImpl.java中的两种不同方法执行转换和调用后操作,也会发生相同的问题. 我需要在这里配置一些东西吗?

The issue is - when I perform the conversion of 'response into ResponseDTO.java' in my utility class, I get myObj = null. But if I do it in my ServiceImpl.java (just after calling post API), it returns the proper body (ResponseDTO object). The same issue occurs even if I perform the conversion and post call operation in two different methods in the ServiceImpl.java. Do I need to configure something here?

推荐答案

我知道了问题所在. 调用REST API之后,如果我是第一次从响应中读取响应后,响应中的主体就会被冲洗掉.我正在阅读主体内容的服务实现类中有一条Sysout语句.

I figured out what was the issue. After calling REST api, body in the response if flushed out after I read it from the response for the first time. I had a Sysout statement in service implementation class where I was reading the body content.

建议:仅读取一次正文内容并将其存储在变量中.在任何需要的地方使用它.

Recommendation: Read the body content only once and store it in a variable. Use it wherever required.

这篇关于ClientResponse(org.springframework.web.reactive.function.client.ClientResponse)在使用WebClient时显示类之间的不一致的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆