Apache HttpClient 4.5 Multipart Upload Request Example

摘要: In this tutorial, we demonstrate how to do a multipart upload http request using Apache HttpClient 4.5.

In this tutorial, we demonstrate how to do a multipart upload http request using Apache HttpClient 4.5.

Maven dependencies

We use maven to manage our dependencies and are using Apache HttpClient version 4.5. Add the following dependency to your project.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                             http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <groupId>com.memorynotfound.apache.httpclient</groupId>
    <artifactId>multipart-upload</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <url>https://memorynotfound.com</url>
    <name>httpclient - ${project.artifactId}</name>

    <dependencies>
        <!-- Apache HttpClient -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.3</version>
        </dependency>
        <!-- Apache HttpClient Mime -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.5.3</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

Multipart File Upload

In this example we’ll show how to to a multipart file upload using HttpClient 4.5. We create an HttpEntity using the MultipartEntityBuilder. When we created the builder, we add a binary body – containing the file that’ll be uploaded and also a text body. Next, we create an HTTP Request using the RequestBuilder and assign the previously created HttpEntity.

package com.memorynotfound.httpclient;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.File;
import java.io.IOException;

/**
 * This example demonstrates the use of {@link HttpPost} request method.
 * And sending Multipart Form requests
 */
public class HttpClientMultipartUploadExample {

    public static void main(String... args) throws IOException {

        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {

            File file = new File(HttpClientMultipartUploadExample.class.getResource("/java-duke.png").getFile());
            String message = "This is a multipart post";

            // build multipart upload request
            HttpEntity data = MultipartEntityBuilder.create()
                    .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
                    .addBinaryBody("upfile", file, ContentType.DEFAULT_BINARY, file.getName())
                    .addTextBody("text", message, ContentType.DEFAULT_BINARY)
                    .build();

            // build http request and assign multipart upload data
            HttpUriRequest request = RequestBuilder
                    .post("http://httpbin.org/post")
                    .setEntity(data)
                    .build();

            System.out.println("Executing request " + request.getRequestLine());

            // Create a custom response handler
            ResponseHandler<String> responseHandler = response -> {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            };
            String responseBody = httpclient.execute(request, responseHandler);
            System.out.println("----------------------------------------");
            System.out.println(responseBody);
        }
    }
}

Output

The previous application prints the following info to the console. As you can see, all the previous multipart file upload is included in the message with the appropriate headers.

Executing request POST http://httpbin.org/post HTTP/1.1
----------------------------------------
{
  "args": {}, 
  "data": "", 
  "files": {
    "upfile": "data:application/octet-stream;base64,iVBORw0KGgoAAAANSUhEUgAA...(droped);
  }, 
  "form": {
    "text": "This is a multipart post"
  }, 
  "headers": {
    "Accept-Encoding": "gzip,deflate", 
    "Connection": "close", 
    "Content-Length": "53709", 
    "Content-Type": "multipart/form-data; boundary=FZeK0gT2nwmgfoGEPlsNzRKBTD5EqyXfl3T", 
    "Host": "httpbin.org", 
    "User-Agent": "Apache-HttpClient/4.5.3 (Java/1.8.0_20)"
  }, 
  "json": null, 
  "origin": "123.123.123.123", 
  "url": "http://httpbin.org/post"
}

Download

上一篇: Spring Security + Spring LDAP Authentication Configuration Example
下一篇: Apache HttpClient 4.5 Custom HTTP Headers Example
 评论 ( What Do You Think )
名称
邮箱
网址
评论
验证
   
 

 


  • 微信公众号

  • 我的微信

站点声明:

1、一号门博客CMS,由Python, MySQL, Nginx, Wsgi 强力驱动

2、部分文章或者资源来源于互联网, 有时候很难判断是否侵权, 若有侵权, 请联系邮箱:summer@yihaomen.com, 同时欢迎大家注册用户,主动发布无版权争议的 文章/资源.

3、鄂ICP备14001754号-3, 鄂公网安备 42280202422812号