spring Spring项目中生产代码的RestTemplate vs Apache Http Client
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31483874/
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
RestTemplate vs Apache Http Client for production code in spring project
提问by brain storm
we have a Spring project that is about to go into production. Currently, the project is using Apache Http Client
. There is a thought of using RestTemplate
as HttpClient
.
我们有一个即将投入生产的 Spring 项目。目前,该项目正在使用Apache Http Client
. 有一种使用RestTemplate
as的想法HttpClient
。
I am digging around to see any notable advantage of using RestTemplate
over Apache's
. Also, it would be interesting to know what HTTP transport does RestTemplate in its implementation. Apache Http Client has been used by several groups for many years and has a good reputation.
我正在四处寻找使用RestTemplate
over 的任何显着优势Apache's
。此外,了解 HTTP 传输在 RestTemplate 的实现中做了什么会很有趣。Apache Http Client 已被多个团体使用多年,并享有良好的声誉。
would we be risking moving to RestTemplate
?
我们会冒险搬到RestTemplate
吗?
Further, this blogpoints that RestTemplate needs to be configured for production, although the configuration is minimal.
此外,该博客指出需要为生产配置 RestTemplate,尽管配置是最小的。
Thanks
谢谢
回答by JB Nizet
RestTemplate and HttpClient don't operate at the same abstraction level.
RestTemplate 和 HttpClient 不在同一抽象级别上运行。
HttpClient is a general-purpose library to communicate using HTTP, whereas RestTemplate is a higher-level abstraction, dealing with JSON/XML transformation of entities, etc.
HttpClient 是使用 HTTP 进行通信的通用库,而 RestTemplate 是更高级别的抽象,处理实体的 JSON/XML 转换等。
RestTemplate delegates to a ClientHttpRequestFactory, and one of the implementations of this interfaceuses Apache's HttpClient.
RestTemplate委托给 ClientHttpRequestFactory,该接口的实现之一使用 Apache 的 HttpClient。
So, if the goal is to communicate with a Restful API, and you still want to use HttpClient, you can use RestTemplate over HttpClient.
因此,如果目标是与 Restful API 进行通信,而您仍想使用 HttpClient,则可以使用 RestTemplate 而非 HttpClient。
Note that what I just said is exactly what the blog you linked to explains:
请注意,我刚才所说的正是您链接到的博客所解释的:
So, the solution is to use the org.springframework.http.client.HttpComponentsClientHttpRequestFactory, which is a ClientHttpRequestFactory delegating the creation of the requests to an HttpClient.
因此,解决方案是使用 org.springframework.http.client.HttpComponentsClientHttpRequestFactory,它是一个 ClientHttpRequestFactory,将请求的创建委托给 HttpClient。