通过java模拟发送multipart/form-data请求-MultipartEntityBuilder

通过java模拟发送multipart/form-data请求-MultipartEntityBuilder

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import java.io.File;

public class UploadFileTest {
    public static void main(String[] args) throws Exception {
        File file1 = new File("D:\\images\\assets\\headImgs\\head_0.png");
        File file2 = new File("D:\\images\\assets\\headImgs\\head_1.png");
        File file3 = new File("D:\\images\\assets\\headImgs\\head_2.png");

        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost("http://127.0.0.1:80/upload");

        HttpEntity reqEntity = MultipartEntityBuilder.create()
                .addTextBody("status", "这是一条来自java后台的测试微博,文本中必须包含至少一个第三方分享到微博的网页URL,并且字数不能超过140字。http://www.baidu.com")
                .addBinaryBody("img1", file1, ContentType.IMAGE_PNG, file1.getName())
                .addBinaryBody("img2", file2, ContentType.IMAGE_PNG, file2.getName())
                .addBinaryBody("img3", file3, ContentType.IMAGE_PNG, file3.getName())
                .addTextBody("access_token", "2.00yOFlzGV4RsoDf88fdf1a7fINBEJB")
                .build();
        httpPost.setEntity(reqEntity);
        try {
            CloseableHttpResponse response = httpclient.execute(httpPost);
            try {
                int code = response.getStatusLine().getStatusCode();
                String info = response.getStatusLine().getReasonPhrase();
                if(code != 200) {
                    throw new Exception(String.valueOf(code) + "&" + info);
                }
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    System.out.println("Response content length: " + resEntity.getContentLength());
                }
                EntityUtils.consume(resEntity);
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
    }
}

参考

java后台如何模拟multipart/form-data请求 实现上传多图和普通文本?

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值