编辑:其他答案更好(使用Resource
)https://stackoverflow.com/a/36226006/116509
我原来的答案:
您可以execute
用于这种低级操作。在这个片段中,我使用了 Commons IO 的copy
方法来复制输入流。您需要HttpMessageConverterExtractor
针对您期望的响应类型自定义。
final InputStream fis = new FileInputStream(new File("c:\\autoexec.bat")); // or whatever
final RequestCallback requestCallback = new RequestCallback() {
@Override
public void doWithRequest(final ClientHttpRequest request) throws IOException {
request.getHeaders().add("Content-type", "application/octet-stream");
IOUtils.copy(fis, request.getBody());
}
};
final RestTemplate restTemplate = new RestTemplate();
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setBufferRequestBody(false);
restTemplate.setRequestFactory(requestFactory);
final HttpMessageConverterExtractor<String> responseExtractor =
new HttpMessageConverterExtractor<String>(String.class, restTemplate.getMessageConverters());
restTemplate.execute("http://localhost:4000", HttpMethod.POST, requestCallback, responseExtractor);
(感谢 Baz 指出你需要打电话setBufferRequestBody(false)
,否则会失败)