使用到的类
-
org.apache.http.entity.mime.MultipartEntityBuilder
-
ContentType
ContentType类
特点:
-
提供了对应到所有的ContentType类型的参数属性
//先根据接口的ContentType找到对应的属性--->multipart/form-data类型的属性对应的值是MULTIPART_FORM_DATA
ContentType contentType=ContentType.MULTIPART_FORM_DATA;
MultipartEntityBuilder类
MultipartEntityBuilder multipartEntityBuilder = new StringBody();//传入key,value
//StringBody类的构造器实现了传入的内容自动转为字符
//使用MultipartEntityBuilder类下的addPart方法,该方法实现了将传入的内容填入FormBodyPart内
//FormBodyPart类自动的构造了表单的格式
multipartEntityBuilder.addPart();//该方法传入key-value,value的类型可以是StringBody对象
//最后使用HttpEntity类将multipartEntityBuilder构建
HttpEntity reqEntity = multipartEntityBuilder.build();
整体实现代码
package AmazonListingAPI;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.util.EntityUtils;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
/**
* 测试Amazon上传图片的API
* @since JDK 1.8
* @date 2021/08/14
* @author Lucifer
*/
public class UploadFileAPITestNo2 {
//设置文件路径
private static File filePath = new File("C:\\Users\\Administrator\\Desktop\\Test_Work\\Test_Picture\\King.jpg");
public static void uploadFile(String url, String cookValue){
//设置Cookie
CookieStore cookieStore = new BasicCookieStore();
BasicClientCookie cookie = new BasicClientCookie("Cookie", cookValue);
try {
cookie.setDomain(new URL(url).getHost());
} catch (MalformedURLException e) {
e.printStackTrace();
}
cookie.setPath("/");
cookieStore.addCookie(cookie);
CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
String result = "";
//每个post参数之间的分隔。随意设定,只要不会和其他的字符串重复即可。
String boundary ="----WebKitFormBoundary5ZMULAAn6mngkXzn";
try {
//文件名
String fileName =