使用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
标题。
答案 0 :(得分:1)
我设法使用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(......);
希望它有所帮助。
答案 1 :(得分:0)
我有同样的问题。我还没有用RestTemplate解决它。我用这样的方式解决了它:
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost uploadFile = new HttpPost("you_url");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
FileBody fileBody = new FileBody(tempFile.toFile(), ContentType.MULTIPART_FORM_DATA, "file_name");
builder.addPart("parameter_name", fileBody);
HttpEntity multipart = builder.build();
uploadFile.setEntity(multipart);
try (CloseableHttpResponse response = httpClient.execute(uploadFile)) {
//....
}