RestTemplate: exchange() vs postForEntity() vs execute()

前端 未结 4 1860
说谎
说谎 2021-02-02 12:36

I am working on Rest API using Spring boot and I had to access an application\'s endpoint. I used RestTemplate for it. I was able to do it using 2 methods,

4条回答
  •  生来不讨喜
    2021-02-02 13:18

    RestTemplate is a synchronous client to perform HTTP requests. It offers templates for common scenarios for each HTTP method, in addition to the generalized exchange(...) and execute(...) methods that support less frequent cases.

    The Spring Integration documentation summarizes the usage of each method:

    postForEntity

    Create a new resource via POST and return the representation from the response.

    exchange

    More generalized, and less opinionated version, of the above methods that provides extra flexibility when needed. It accepts RequestEntity, including HTTP method, URL, headers, and body as input, and returns a ResponseEntity.

    These methods allow the use of ParameterizedTypeReference instead of Class to specify a response type with generics.

    execute

    The most generalized way to perform a request, with full control over request preparation and response extraction via callback interfaces.


    In the end, both postForEntity(...), exchange(...) and execute(...) methods will invoke the protected doExecute(...) method, which will perform the actual HTTP request. You can check the source code for details

提交回复
热议问题