背景
简介:
因为在实际的业务当中存在上传文件的场景。经常是通过ajax发送form-data形式的表单。所以在测试的时候需要构造表单的形式进行测试。
关键参数
-
Content-Type:multipart/form-data;
-
参数:
file
二进制类型
构造实例:
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 ="----WebKitFormBoundary0j3qBlYRoC96tFB3";
try {
//文件名
String