通过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请求 实现上传多图和普通文本?