سؤال

I am trying to upload an image file to a web storage server using zero copy post.

The implementation comes from the example in the Apache website. I've changed some parts from the example so that the response is not downloaded in a file.

Here's the source code that I have changed.

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");
}

I need to add headers to this POST request. How is it done?

هل كانت مفيدة؟

المحلول

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;
    }
};

Overriding ZeroCopyPost#createRequest is the recommended way. Overriding #generateRequest per @Robert Rowntree recommendation would work as well.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top