使用Spring RestTemplate
,将缓冲区请求主体设置为false并清空主体
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setBufferRequestBody(false);
requestFactory.setConnectTimeout(60_000);
RestTemplate restTemplate = RestTemplate(requestFactory);
restTemplate.exchange(uri, HttpMethod.PUT, new HttpEntity<>(httpHeaders), Void.class);
我收到
411 - Length Required
状态码作为回应。由于某种原因,Spring RestTemplate不会在请求中放置
Content-Length: 0
头。万一我在
requestFactory.setBufferRequestBody(false);
注释行,它可以完美工作。但是我需要它来发送大文件。UPD:查看调试日志后发现,该请求不包含
Content-Length
标头。 最佳答案
我设法用RestTemplate
和SimpleClientHttpRequestFactory
复制您的问题。切换到Apache HttpComponents HttpClient后,问题消失了。
这是我配置RestTemplate
的方式:
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
CloseableHttpClient httpClient = HttpClientBuilder
.create()
.build();
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);
factory.setBufferRequestBody(false);
RestTemplate restTemplate = new RestTemplate(factory);
restTemplate.exchange(......);
希望能帮助到你。
关于java - 使用无缓冲RestTemplate的PUT请求,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38008086/