开发者社区> 问答> 正文

java后台如何模拟multipart/form-data请求 实现上传多图和普?400报错

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

项目要发送多图微博,

图片说明

根据微博API打算利用后台拼接multipart/form-data请求 
有没有大神能能教教如何拼接这个请求

展开
收起
爱吃鱼的程序员 2020-06-02 17:24:04 1544 0
1 条回答
写回答
取消 提交回答
  • https://developer.aliyun.com/profile/5yerqm5bn5yqg?spm=a2c6h.12873639.0.0.6eae304abcjaIB

    我这段代码是没问题的:addBinaryBody方法的第一个字段就是表单项,不能同名。

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

     

    ######回复 @银杏卡卡 : 谢谢你耐心回复 我在微博开放平台17年的公告下面的网友评论里找到了 确实只能上传一张图片 这个API文档都没人维护更新 很气人 浪费了大量时间######回复 @泽西岛屿 : 图片看不到######回复 @银杏卡卡 : 我提问的那个截图就是微博API对于发布图文微博的介绍 有点迷茫 没说可以多图也没说不可以 按照他的字段格式提交多图微博的请求却只有一个图片######回复 @泽西岛屿 : 我没弄过这种,微博提供的接口文档有介绍没?是否支持多文件上传呢?如果是那边不支持你们也没办法,直接pass掉好了######回复 @银杏卡卡 : 很苦恼啊 循环多次就变成了多条微博 项目要求是一条微博配多图 有点难受######

    用HttpClient不是很简单吗

    ######
    package org.apache.http.examples.entity.mime;
    
    import java.io.File;
    
    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.entity.mime.MultipartEntityBuilder;
    import org.apache.http.entity.mime.content.FileBody;
    import org.apache.http.entity.mime.content.StringBody;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.util.EntityUtils;
    
    /**
     * Example how to use multipart/form encoded POST request.
     */
    public class ClientMultipartFormPost {
    
        public static void main(String[] args) throws Exception {
            if (args.length != 1)  {
                System.out.println("File path not given");
                System.exit(1);
            }
            CloseableHttpClient httpclient = HttpClients.createDefault();
            try {
                HttpPost httppost = new HttpPost("http://localhost:8080" +
                        "/servlets-examples/servlet/RequestInfoExample");
    
                FileBody bin = new FileBody(new File(args[0]));
                StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);
    
                HttpEntity reqEntity = MultipartEntityBuilder.create()
                        .addPart("bin", bin)
                        .addPart("comment", comment)
                        .build();
    
    
                httppost.setEntity(reqEntity);
    
                System.out.println("executing request " + httppost.getRequestLine());
                CloseableHttpResponse response = httpclient.execute(httppost);
                try {
                    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();
            }
        }
    
    }

    HttpClient官方例子:

     

    ######代码在下边,求指教######因为发布图文微博 微博要求图片上传格式是binary 我用的MultipartEntityBuilder和CloseableHttpClient 但是现在只能上传一张图片 不知道怎么传多图######单张图片的很简单 已经实现了 发布多图微博的时候只能传一张图片 不知道有没有什么好方法######
    package com.aaa;
    
    import java.io.File;
    import java.io.IOException;
    import java.nio.charset.Charset;
    
    import org.apache.hc.client5.http.classic.methods.HttpPost;
    import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder;
    import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
    import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
    import org.apache.hc.client5.http.impl.classic.HttpClients;
    import org.apache.hc.core5.http.ContentType;
    import org.apache.hc.core5.http.HttpEntity;
    import org.apache.hc.core5.http.io.entity.EntityUtils;
    
    public class weibo {
    	public static void main(String[] args) throws Exception {
    		
    		File file = new File("E:\\article\\weibo_20190114161835827.jpeg");
    		File file1 = new File("E:\\article\\weibo_20190114161836750.jpeg");
    		File file2 = new File("E:\\article\\weibo_20190114161837173.jpeg");
    		File file3 = new File("E:\\article\\weibo_20190114161837190.jpeg");
    		
    		CloseableHttpClient httpclient = HttpClients.createDefault();
    		HttpPost httpPost = new HttpPost("https://api.weibo.com/2/statuses/share.json");
    		
    		MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    		ContentType strContent = ContentType.create("text/plain",Charset.forName("UTF-8"));
    		ContentType imageContent = ContentType.create("image/jpeg");
    		builder.addTextBody("status", "这是一条来自java后台的测试微博,文本中必须包含至少一个第三方分享到微博的网页URL,并且字数不能超过140字。http://www.baidu.com", strContent);
    		builder.addBinaryBody("pic", file,imageContent, file.getName());
    		builder.addBinaryBody("pic", file1,imageContent, file1.getName());
    		builder.addBinaryBody("pic", file2,imageContent, file2.getName());
    		builder.addBinaryBody("pic", file3,imageContent, file3.getName());
    		builder.addTextBody("access_token", "2.00yOFlzGV4RsoDf88fdf1a7fINBEJB");
    //		builder.addBinaryBody("name=\"pic\"; filename=\"weibo_20190114161835827.jpeg\"", new File("E:\\article\\weibo_20190114161835827.jpeg"));
    //		builder.addBinaryBody("name=\"pic\"; filename=\"weibo_20190114161835827.jpeg\"", new File("E:\\article\\weibo_20190114161835827.jpeg"));
    		
    		HttpEntity parameterEntity = builder.build();
    		httpPost.setEntity(parameterEntity);
    		
            CloseableHttpResponse response = httpclient.execute(httpPost);
            if (response.getCode() != 200) {
                throw new Exception(String.valueOf(response.getCode()) + "&" + response.getReasonPhrase());
            }
    
            HttpEntity resultEntity = response.getEntity();
            if (resultEntity == null) {
                throw new Exception("response null");
            }
            String result = EntityUtils.toString(resultEntity);
            System.out.println("微博发送完毕:" + result);
    		
    	}
    }

     

    2020-06-02 17:24:17
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载