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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/52364187/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 00:25:16  来源:igfitidea点击:

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

javaspring-bootresttemplate

提问by Praveen Kumar

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

我正在使用 Spring Boot 处理 Rest API,我必须访问应用程序的端点。我用过RestTemplate。我能够使用两种方法来做到这一点,

  • postForEntity():

    responseEntity = 
        restTemplate.postForEntity(uri, httpEntity, ResponseClass.class);
    
  • exchange():

    responseEntity = 
        restTemplate.exchange(uri, HttpMethod.POST, httpEntity, ResponseClass.class);
    
  • postForEntity()

    responseEntity = 
        restTemplate.postForEntity(uri, httpEntity, ResponseClass.class);
    
  • exchange()

    responseEntity = 
        restTemplate.exchange(uri, HttpMethod.POST, httpEntity, ResponseClass.class);
    

I would like to know the usage and differences of these two methods.

我想知道这两种方法的用法和区别。

I also see another method execute(). Please shed some light on it. How and when to use it.

我还看到了另一种方法execute()。请解释一下。如何以及何时使用它。

采纳答案by Paul Benn

The RestTemplateis a very versatile object.

RestTemplate是一个非常通用的对象。

Let's start with execute, since it's the most generic method:

让我们从 开始execute,因为它是最通用的方法:

execute(String url, HttpMethod method, @Nullable RequestCallback requestCallback,
        @Nullable ResponseExtractor<T> responseExtractor, Object... uriVariables)

Note the uriVariablescan be passed as a Maptoo.

注意uriVariables也可以作为 a 传递Map

executeis designed to be applicable in the highest variety of scenarios possible:

execute旨在适用于尽可能多的场景:

  • The first and second parameters allow any valid combination of URL and method.
  • The request can be modified in a myriad of different ways by passing a custom RequestCallback(a @FunctionalInterfacewith just one method doWithRequest(ClientHttpRequest request)) before sending it.
  • The response returned from the remote resource can be deserialized in any way necessary by passing a custom ResponseExtractor.
  • 第一个和第二个参数允许 URL 和方法的任何有效组合。
  • 通过在发送之前传递自定义RequestCallback@FunctionalInterface只有一种方法doWithRequest(ClientHttpRequest request)),可以以多种不同的方式修改请求。
  • 从远程资源返回的响应可以通过传递自定义ResponseExtractor.

Compare this with exchange:

将其与exchange

exchange(String url, HttpMethod method, @Nullable HttpEntity<?> requestEntity,
         Class<T> responseType, Object... uriVariables)

There are two major differences here:

这里有两个主要区别:

  • You can now pass an HttpEntitydirectly, whereas before it needed to be set manually using the RequestCallback.
  • Deserialization mechanics are provided out of the box by passing the desired response type Class.
  • 您现在可以HttpEntity直接传递,而在此之前需要使用RequestCallback.
  • 通过传递所需的响应类型来提供开箱即用的反序列化机制Class

As you can see, this is much more convenient for everyday use.

如您所见,这对于日常使用来说更加方便。

Methods like getForEntityand postForEntityare even shorter, easier to understand versions of this:

getForEntitypostForEntity这样的方法更短、更容易理解:

getForEntity(String url, Class<T> responseType, Object... uriVariables)

postForEntity(String url, @Nullable Object request, Class<T> responseType,
              Object... uriVariables)

Notice postForEntitynow allows you to POST any Objectdirectly without a wrapper. There is no performance benefit or detriment to using these instead of execute, as they call executethemselves under the hood - it's simply a matter of convenience.

注意postForEntity现在允许您在Object没有包装器的情况下直接发布任何内容。使用这些代替 没有性能上的好处或损害execute,因为他们execute在幕后自称 - 这只是一个方便的问题。

回答by ksadjad

If you look at the implementation of both postForEntity and exchange method you will see that both use the execute methods in the back. Using the exchange method will give you more freedom for calling different http methods.

如果您查看 postForEntity 和 exchange 方法的实现,您会发现两者都使用了后面的 execute 方法。使用 exchange 方法可以让您更自由地调用不同的 http 方法。

回答by cassiomolin

RestTemplateis a synchronousclient 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.

RestTemplate是一个同步客户端来执行 HTTP 请求。它提供了常见的场景模板,每个HTTP方法,除了广义exchange(...)execute(...)方法的支持不太频繁的情况下。

The Spring Integration documentationsummarizes the usage of each method:

Spring集成文档总结了每种方法的用法:

postForEntity

Create a new resource via POSTand return the representation from the response.

postForEntity

通过创建一个新资源POST并从响应中返回表示。

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 ParameterizedTypeReferenceinstead of Classto specify a response type with generics.

exchange

上述方法的更通用和更少固执的版本,可在需要时提供额外的灵活性。它接受RequestEntity,包括 HTTP 方法、URL、标头和正文作为输入,并返回一个ResponseEntity.

这些方法允许使用ParameterizedTypeReference而不是Class使用泛型指定响应类型。

execute

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

execute

执行请求的最通用方式,通过回调接口完全控制请求准备和响应提取。



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 codefor details

最后,两个postForEntity(...)exchange(...)execute(...)方法将调用受保护的doExecute(...)方法,该方法将执行实际的HTTP请求。您可以查看源代码以了解详细信息

回答by Aditya Rewari

Execute(..)The most raw form of method, to make REST call.

Execute(..)最原始的方法形式,用于进行 REST 调用。

Exchange(..)A wrapper over Execute method.

Exchange(..)对 Execute 方法的包装。

PostForEntity(..)A wrapper method, which further eases the use for making REST calls. You specify the request type in the method name itself(getForEntity, postForEntity), so, need not mention request type in the parameter. The method name in itself becomes self explanatory.

PostForEntity(..)一种包装方法,它进一步简化了进行 REST 调用的使用。您在方法名称本身(getForEntity,postForEntity)中指定请求类型,因此,无需在参数中提及请求类型。方法名称本身变得不言自明。

In Exchange & postForEntity, response has to be in Json formats. This Json is further converted to Model class by json-mapper libraries. While, in Execute, we accept response in any format, as we pass the deserializer in Response Executor argument.

Exchange 和 postForEntity 中,响应必须是Json 格式。这个 Json 被 json-mapper 库进一步转换为 Model 类。而在Execute 中,我们接受任何格式的响应,因为我们在 Response Executor 参数中传递了反序列化器。