Spring boot Webclient's retrieve vs exchange

こ雲淡風輕ζ 提交于 2020-12-30 05:08:38

问题


I have started using WebClient in my Spring boot project recently. Can somebody throw some light on the differences/usages between exchange and retrieve method in WebClient.

I undertand that exchange returns Mono<ClientResponse> and retrieve returns ResponseSpec, I just want to know when/why I should use each one of them.

Much Thanks.


回答1:


According to spring Webclient api documentation the difference between the two is that exchange retrieve in addition to the body other http response information like headers and status, while retrieve only returns body information.

So If you only need the body information you should use retrieve, because it is a shortcut for exchange and then get the body, but if you need other information like http status you must use exchange.




回答2:


Adding to @JArgente's answer.

According to the official documentation of the retrieve() method:

Perform the HTTP request and retrieve the response body.

...

This method is a shortcut to using exchange() and decoding the response body through ClientResponse.

and the exchange() method

Perform the HTTP request and return a ClientResponse with the response status and headers. You can then use methods of the response to consume the body:


The retrieve() method decodes the ClientResponse object and hands you the ready-made object for your use. It doesn't have a very nice api for handling exceptions.

However on the other hand the exchange() method hands you the ClientResponse object itself along with the response status and headers. With exchange method you get fine grained control over your response objects and a better way to handle the response object and the exceptions.

If you just want to consume some api go with retrieve().

If you want a better control over your response objects, headers and exceptions, go with exchange().



来源:https://stackoverflow.com/questions/58410352/spring-boot-webclients-retrieve-vs-exchange

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!