java - 如何向 ZeroCopyPost 添加 header

标签 java apache-httpclient-4.x apache-httpcomponents

我正在尝试使用零复制帖子将图像文件上传到网络存储服务器。

实现来自example在 Apache 网站上。我更改了示例中的一些部分,以便不会将响应下载到文件中。

这是我更改的源代码。

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 请求添加 header 。它是如何完成的?

最佳答案

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 也可以。

关于java - 如何向 ZeroCopyPost 添加 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20442758/

相关文章:

java - 无法登录网站

java - Android 中的 apache 的 HttpClient?

java - Dom4j 解析 - 如何以编程方式声明 HTML 实体? "The entity "nbsp“已引用,但未声明。”

java - 如何通过CSS显示上传的图片

java - HTTPClient 4.x 连接重用没有发生

执行 Apache HttpClient 时出现 java.lang.InterruptedException

cookies - 为什么 http 组件 HttpClient 会删除 Cookie 值中的引号?

java - 多部分实体生成器 : Omit Content-Type and Content-Transfer

java - 从扩展类中覆盖 compareTo - 发生了什么?

java - 部署 Web 应用程序时仅读取 .properties 文件一次