
spring restTemplate 默认工厂
SimpleClientHttpRequestFactory 使用 HttpURLConnection.openConnection()
public class SimpleClientHttpRequestFactory implements ClientHttpRequestFactory, AsyncClientHttpRequestFactory {
...
@Override
public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException {
HttpURLConnection connection = openConnection(uri.toURL(), this.proxy);
prepareConnection(connection, httpMethod.name());
if (this.bufferRequestBody) {
return new SimpleBufferingClientHttpRequest(connection, this.outputStreaming);
}
else {
return new SimpleStreamingClientHttpRequest(connection, this.chunkSize, this.outputStreaming);
}
}
/**
* {@inheritDoc}
* <p>Setting the {@link #setTaskExecutor taskExecutor} property is required before calling this method.
*/
@Override
public AsyncClientHttpRequest createAsyncRequest(URI uri, HttpMethod httpMethod) throws IOException {
Assert.state(this.taskExecutor != null, "Asynchronous execution requires TaskExecutor to be set");
HttpURLConnection connection = openConnection(uri.toURL(), this.proxy);
prepareConnection(connection, httpMethod.name());
if (this.bufferRequestBody) {
return new SimpleBufferingAsyncClientHttpRequest(
connection, this.outputStreaming, this.taskExecutor);
}
else {
return new SimpleStreamingAsyncClientHttpRequest(
connection, this.chunkSize, this.outputStreaming, this.taskExecutor);
}
}
...

本文深入探讨了Spring RestTemplate的默认工厂SimpleClientHttpRequestFactory的工作原理。该工厂使用HttpURLConnection来创建请求,根据配置选择是否缓冲请求体,并支持同步和异步请求处理。通过分析源码,理解其如何准备连接和选择合适的ClientHttpRequest实现。
368

被折叠的 条评论
为什么被折叠?



