我正在尝试使用零复制帖子将图像文件上传到网络存储服务器。
实现来自Apache网站中的example。我已经从示例中更改了一些部分,因此不会将响应下载到文件中。
这是我更改过的源代码。
private void upload() throws Exception {
CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
try {
httpclient.start();
File upload = new File("C:\\Users\\Jee\\profile.png");
ZeroCopyPost httpost = new ZeroCopyPost(requestURL+upload.getName(), upload,
ContentType.create("image/png"));
HttpAsyncResponseConsumer consumer = new BasicAsyncResponseConsumer();
Future<File> future = httpclient.execute(httpost, consumer, null);
File result = future.get();
System.out.println("Response file length: " + result.length());
System.out.println("Shutting down");
} finally {
httpclient.close();
}
System.out.println("Done");
}
我需要为此POST请求添加标头。怎么做?
答案 0 :(得分:2)
ZeroCopyPost zeroCopyPost = new ZeroCopyPost(
URI.create("/"),
new File("stuff"),
ContentType.DEFAULT_BINARY) {
@Override
protected HttpEntityEnclosingRequest createRequest(
final URI requestURI, final HttpEntity entity) {
HttpEntityEnclosingRequest request = super.createRequest(requestURI, entity);
request.setHeader("my-header", "whatever");
return request;
}
};
重写ZeroCopyPost#createRequest是推荐的方法。根据@Robert Rowntree建议覆盖#generateRequest也会有效。