apache httpclient multipart upload

ht‮/:spt‬/www.theitroad.com

Apache HttpClient provides support for multipart/form-data requests, which are commonly used for file uploads. Multipart requests allow you to upload files along with other form data in a single request.

Here's an example that demonstrates how to use Apache HttpClient to upload a file using a multipart request:

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
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.HttpClientBuilder;

import java.io.File;
import java.io.IOException;

public class HttpClientExample {
    public static void main(String[] args) throws Exception {
        HttpClient httpClient = HttpClientBuilder.create().build();

        HttpPost httpPost = new HttpPost("http://www.example.com/upload");

        FileBody fileBody = new FileBody(new File("path/to/file"));
        HttpEntity entity = MultipartEntityBuilder.create()
                .addPart("file", fileBody)
                .addTextBody("description", "File upload")
                .build();

        httpPost.setEntity(entity);

        try {
            HttpResponse response = httpClient.execute(httpPost);
            System.out.println(response.getStatusLine().getStatusCode());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In this example, we create a new instance of HttpClient using the HttpClientBuilder class. We then create an HttpPost request to the URL "http://www.example.com/upload".

We create a FileBody object to represent the file we want to upload, and add it to a MultipartEntityBuilder object along with a text body representing the description of the upload.

We then set the resulting entity as the entity of the HttpPost request using the setEntity() method.

Finally, we execute the request using the configured HttpClient and print out the HTTP status code of the response.

Note that this example assumes that the server expects the file to be uploaded using the key "file" and the description using the key "description". You should consult the server documentation to determine the correct keys to use.