下面列出了怎么用org.apache.http.entity.mime.MultipartEntityBuilder的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 构建POST方法请求参数
* @return
*/
private HttpEntity buildPostParam(List<NameValuePair> nameValuePairs, List<File> files) {
if(CollectionUtils.isEmpty(nameValuePairs) && CollectionUtils.isEmpty(files)) {
return null;
}
if(!CollectionUtils.isEmpty(files)) {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
for (File file : files) {
builder.addBinaryBody(file.getName(), file, ContentType.APPLICATION_OCTET_STREAM, file.getName());
}
for (NameValuePair nameValuePair : nameValuePairs) {
//设置ContentType为UTF-8,默认为text/plain; charset=ISO-8859-1,传递中文参数会乱码
builder.addTextBody(nameValuePair.getName(), nameValuePair.getValue(), ContentType.create("text/plain", Consts.UTF_8));
}
return builder.build();
} else {
try {
return new UrlEncodedFormEntity(nameValuePairs);
} catch (UnsupportedEncodingException e) {
LOGGER.error(e.getMessage(), e.toString());
}
}
return null;
}
private void performUpload() {
Path gzLog = compressLog();
try (CloseableHttpClient client = buildHttpClient()) {
HttpPost post = new HttpPost(CRASH_REPORT_URL);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
FileBody logFile = new FileBody(gzLog.toFile(), ContentType.DEFAULT_BINARY);
builder.addPart("log", logFile);
StringBody uid = new StringBody(userId, ContentType.TEXT_PLAIN);
builder.addPart("uid", uid);
HttpEntity postEntity = builder.build();
post.setEntity(postEntity);
HttpResponse response = client.execute(post);
if (response.getStatusLine().getStatusCode() != 200) {
logger.debug("Error uploading crash report: {}", response.getStatusLine());
}
} catch (IOException e) {
logger.error("Error uploading crash report: {}", e.getLocalizedMessage());
}
}
private static HttpEntity createMessageForComplexForm() {
HttpEntity reqEntity = null;
try {
StringBody companyText = new StringBody("{\"type\": \"Open Source\"}", ContentType.APPLICATION_JSON);
StringBody personList = new StringBody(
"[{\"name\":\"Richard Stallman\",\"age\":63}, {\"name\":\"Linus Torvalds\",\"age\":46}]",
ContentType.APPLICATION_JSON);
reqEntity = MultipartEntityBuilder.create().addTextBody("id", "1")
.addPart("company", companyText)
.addPart("people", personList).addBinaryBody("file", new File(
Thread.currentThread().getContextClassLoader().getResource("sample.txt").toURI()), ContentType.DEFAULT_BINARY, "sample.txt")
.build();
} catch (URISyntaxException e) {
log.error("Error while getting the file from resource." + e.getMessage(), e);
}
return reqEntity;
}
@Test
public final void givenCharArrayandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws IOException {
final String message = "This is a multipart post";
final byte[] bytes = "binary code".getBytes();
final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addBinaryBody("file", bytes, ContentType.DEFAULT_BINARY, TEXTFILENAME);
builder.addTextBody("text", message, ContentType.TEXT_PLAIN);
final HttpEntity entity = builder.build();
post.setEntity(entity);
response = client.execute(post);
final int statusCode = response.getStatusLine()
.getStatusCode();
final String responseString = getContent();
final String contentTypeInHeader = getContentTypeHeader();
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
// assertTrue(responseString.contains("Content-Type: multipart/form-data;"));
assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;"));
System.out.println(responseString);
System.out.println("POST Content Type: " + contentTypeInHeader);
}
public String importImage(File file) throws IOException {
if(getGalleryId() != null) {
String url = getImportImageUrl();
HttpGet get = new HttpGet(url);
HttpResponse response = client.execute(get, context);
this.cookies = response.getFirstHeader(Constant.SET_COOKIE_HEADER).getValue();
// load file in form
FileBody cbFile = new FileBody(file);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart("physical", cbFile);
builder.addPart("title", new StringBody("Image importée via ZestWriter", Charset.forName("UTF-8")));
builder.addPart(Constant.CSRF_ZDS_KEY, new StringBody(getCookieValue(cookieStore, Constant.CSRF_COOKIE_KEY), ContentType.MULTIPART_FORM_DATA));
Pair<Integer, String> resultPost = sendPost(url, builder.build());
Document doc = Jsoup.parse(resultPost.getValue());
Elements endPoints = doc.select("input[name=avatar_url]");
if(!endPoints.isEmpty()) {
return getBaseUrl() + endPoints.first().attr("value").trim();
}
}
return "http://";
}
/**
* 构造HttpUriRequest请求.
*
* @param method 请求方法
* @param url 请求地址
* @param params 请求(key,value)数据
* @param data 请求体文本数据
* @param file 请求体二进制文件
*/
private static HttpUriRequest buildRequest(String method, String url, Map<String, String> params,
String data, File file) {
RequestBuilder builder = RequestBuilder.create(method).setUri(url);
if (params != null) {
for (String key : params.keySet()) {
builder.addParameter(new BasicNameValuePair(key, params.get(key)));
}
}
if (data != null) {
builder.setEntity(new StringEntity(data, Const.Charset.UTF_8));
}
if (file != null) {
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create().addBinaryBody("media", file);
builder.setEntity(entityBuilder.build());
}
return builder.build();
}
HttpEntity getRequestEntity(ContentReader reader, String sourceMimetype, String sourceExtension,
String targetExtension, long timeoutMs, String[] args, StringJoiner sj)
{
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
ContentType contentType = ContentType.create(sourceMimetype);
builder.addBinaryBody("file", reader.getContentInputStream(), contentType, "tmp."+sourceExtension);
builder.addTextBody("targetExtension", targetExtension);
sj.add("targetExtension" + '=' + targetExtension);
for (int i=0; i< args.length; i+=2)
{
if (args[i+1] != null)
{
builder.addTextBody(args[i], args[i + 1]);
sj.add(args[i] + '=' + args[i + 1]);
}
}
if (timeoutMs > 0)
{
String timeoutMsString = Long.toString(timeoutMs);
builder.addTextBody("timeout", timeoutMsString);
sj.add("timeout=" + timeoutMsString);
}
return builder.build();
}
@Test
public void testAuthorizationFailed() throws Exception {
HttpPost post = new HttpPost(httpsAdminServerUrl + "/ota/start?token=" + 123);
post.setHeader(HttpHeaderNames.AUTHORIZATION.toString(), "Basic " + Base64.getEncoder().encodeToString("123:123".getBytes()));
String fileName = "test.bin";
InputStream binFile = OTATest.class.getResourceAsStream("/static/ota/" + fileName);
ContentBody fileBody = new InputStreamBody(binFile, ContentType.APPLICATION_OCTET_STREAM, fileName);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart("upfile", fileBody);
HttpEntity entity = builder.build();
post.setEntity(entity);
try (CloseableHttpResponse response = httpclient.execute(post)) {
assertEquals(403, response.getStatusLine().getStatusCode());
String error = TestUtil.consumeText(response);
assertNotNull(error);
assertEquals("Authentication failed.", error);
}
}
private URI uploadPackageAndGetURI(final CloseableHttpClient httpclient)
throws IOException, URISyntaxException {
File file = new File(this.topologyPackageLocation);
String uploaderUri = HttpUploaderContext.getHeronUploaderHttpUri(this.config);
post = new HttpPost(uploaderUri);
FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart(FILE, fileBody);
HttpEntity entity = builder.build();
post.setEntity(entity);
HttpResponse response = execute(httpclient);
String responseString = EntityUtils.toString(response.getEntity(),
StandardCharsets.UTF_8.name());
LOG.fine("Topology package download URI: " + responseString);
return new URI(responseString);
}
public static byte[] convert(String baseUrl, InputStream sourceInputStream) throws IOException {
int timeoutMillis = 5000;
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(timeoutMillis)
.setConnectionRequestTimeout(timeoutMillis)
.setSocketTimeout(timeoutMillis * 1000).build();
CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
HttpPost httpPost = new HttpPost(baseUrl + "/lool/convert-to/pdf");
HttpEntity multipart = MultipartEntityBuilder.create()
.setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
.addBinaryBody("data", sourceInputStream, ContentType.MULTIPART_FORM_DATA, "anything")
.build();
httpPost.setEntity(multipart);
CloseableHttpResponse response = client.execute(httpPost);
byte[] convertedFileBytes = EntityUtils.toByteArray(response.getEntity());
client.close();
return convertedFileBytes;
}
@Test
public void testUrlMatrixParamsShouldReplaceJobVariables() throws Exception {
File jobFile = new File(RestSchedulerJobTaskTest.class.getResource("config/job_matrix_params.xml").toURI());
String schedulerUrl = getResourceUrl("submit;var=matrix_param_val");
HttpPost httpPost = new HttpPost(schedulerUrl);
setSessionHeader(httpPost);
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create()
.addPart("file",
new FileBody(jobFile,
ContentType.APPLICATION_XML));
httpPost.setEntity(multipartEntityBuilder.build());
HttpResponse response = executeUriRequest(httpPost);
assertHttpStatusOK(response);
JSONObject jsonObj = toJsonObject(response);
final String jobId = jsonObj.get("id").toString();
assertNotNull(jobId);
waitJobState(jobId, JobStatus.FINISHED, TimeUnit.MINUTES.toMillis(1));
}
@Test
public void testMultipartRequestTooLargeManyParts() throws Exception {
CloseableHttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost("http://localhost:" + PORT + "/bookstore/books/image");
String ct = "multipart/mixed";
post.setHeader("Content-Type", ct);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
HttpEntity entity = builder.addPart("image", new ByteArrayBody(new byte[1024 * 9], "testfile.png"))
.addPart("image", new ByteArrayBody(new byte[1024 * 11], "testfile2.png")).build();
post.setEntity(entity);
try {
CloseableHttpResponse response = client.execute(post);
assertEquals(413, response.getStatusLine().getStatusCode());
} finally {
// Release current connection to the connection pool once you are done
post.releaseConnection();
}
}
@Test
public void testOTAWrongToken() throws Exception {
HttpPost post = new HttpPost(httpsAdminServerUrl + "/ota/start?token=" + 123);
post.setHeader(HttpHeaderNames.AUTHORIZATION.toString(), "Basic " + Base64.getEncoder().encodeToString(auth));
String fileName = "test.bin";
InputStream binFile = OTATest.class.getResourceAsStream("/static/ota/" + fileName);
ContentBody fileBody = new InputStreamBody(binFile, ContentType.APPLICATION_OCTET_STREAM, fileName);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart("upfile", fileBody);
HttpEntity entity = builder.build();
post.setEntity(entity);
try (CloseableHttpResponse response = httpclient.execute(post)) {
assertEquals(400, response.getStatusLine().getStatusCode());
String error = TestUtil.consumeText(response);
assertNotNull(error);
assertEquals("Invalid token.", error);
}
}
public static String sendPostFile(String url, File file, Map<String, String> data) {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
RequestConfig requestConfig =
RequestConfig.custom().setConnectTimeout(200000).setSocketTimeout(200000000).build();
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(requestConfig);
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
multipartEntityBuilder.setCharset(Charset.forName("UTF-8"));
multipartEntityBuilder.addBinaryBody("file", file);
if (data != null) {
data.forEach((k, v) -> {
multipartEntityBuilder.addTextBody(k, v);
});
}
HttpEntity httpEntity = multipartEntityBuilder.build();
httpPost.setEntity(httpEntity);
try {
CloseableHttpResponse response = httpClient.execute(httpPost);
return EntityUtils.toString(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public void execute() throws AppException {
if(!desiredState.getImage().isValid()) {
LOG.info("No image configured, doing nothing.");
return;
}
LOG.info("Updating API-Image from: " + desiredState.getImage().getFilename());
URI uri;
HttpEntity entity;
try {
uri = new URIBuilder(cmd.getAPIManagerURL()).setPath(RestAPICall.API_VERSION+"/proxies/"+actualState.getId()+"/image").build();
entity = MultipartEntityBuilder.create()
.addBinaryBody("file", ((DesiredAPI)this.desiredState).getImage().getInputStream(), ContentType.create("image/jpeg"), desiredState.getImage().getBaseFilename())
.build();
RestAPICall apiCall = new POSTRequest(entity, uri, this);
apiCall.setContentType(null);
apiCall.execute();
} catch (Exception e) {
throw new AppException("Can't update API-Image.", ErrorCode.UNXPECTED_ERROR, e);
}
}
private HttpPost postForm(String url, Map<String, String> params, Map<String, File> files, String charset) {
if (StringUtils.isBlank(charset)) {
charset = "UTF-8";
}
HttpPost httpPost = new HttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
if (null != params) {
Set<String> keySet = params.keySet();
for (String key : keySet) {
builder.addTextBody(key, params.get(key), ContentType.create("text/plain", Charset.forName(charset)));
}
}
if (CollectionUtils.isBlank(files)) {
for (String filename : files.keySet()) {
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addBinaryBody(filename, files.get(filename), ContentType.DEFAULT_BINARY, filename);
}
}
httpPost.setEntity(builder.build());
return httpPost;
}
/**
* This is the http request builder for file uploads, using Apache Http Client. In case you want to build
* or prepare the requests differently, you can override this method.
*
* Note-
* With file uploads you can send more headers too from the testcase to the server, except "Content-Type" because
* this is reserved for "multipart/form-data" which the client sends to server during the file uploads. You can
* also send more request-params and "boundary" from the test cases if needed. The boundary defaults to an unique
* string of local-date-time-stamp if not provided in the request.
*
* You can override this method via @UseHttpClient(YourCustomHttpClient.class)
*
* @param httpUrl
* @param methodName
* @param reqBodyAsString
* @return
* @throws IOException
*/
public RequestBuilder createFileUploadRequestBuilder(String httpUrl, String methodName, String reqBodyAsString) throws IOException {
Map<String, Object> fileFieldNameValueMap = getFileFieldNameValue(reqBodyAsString);
List<String> fileFieldsList = (List<String>) fileFieldNameValueMap.get(FILES_FIELD);
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
/*
* Allow fileFieldsList to be null.
* fileFieldsList can be null if multipart/form-data is sent without any files
* Refer Issue #168 - Raised and fixed by santhoshTpixler
*/
if(fileFieldsList != null) {
buildAllFilesToUpload(fileFieldsList, multipartEntityBuilder);
}
buildOtherRequestParams(fileFieldNameValueMap, multipartEntityBuilder);
buildMultiPartBoundary(fileFieldNameValueMap, multipartEntityBuilder);
return createUploadRequestBuilder(httpUrl, methodName, multipartEntityBuilder);
}
public String uploadFile(String url, String path) throws IOException {
HttpPost post = new HttpPost(url);
try {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
FileBody fileBody = new FileBody(new File(path)); //image should be a String
builder.addPart("file", fileBody);
post.setEntity(builder.build());
CloseableHttpResponse response = client.execute(post);
return readResponse(response);
} finally {
post.releaseConnection();
}
}
/**
* Private helper method to abstract creating a POST/PUT request.
* Side Effect: Adds the body to the request
*
* @param request A PUT or POST request
* @param body Map of Key Value pairs
* @param contentType The intended content type of the body
*/
protected static void addBodyToRequest(HttpEntityEnclosingRequestBase request, Map<String, Object> body, ContentType contentType) {
if (body != null) {
if (contentType == ContentType.MULTIPART_FORM_DATA) {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
for (Map.Entry<String, Object> entry : body.entrySet()) {
builder.addTextBody(entry.getKey(), (String) entry.getValue());
}
request.setEntity(builder.build());
} else {
JSONObject jsonBody = new JSONObject(body);
StringEntity strBody = new StringEntity(jsonBody.toJSONString(), ContentType.APPLICATION_JSON);
request.setEntity(strBody);
}
}
}
@Override
public Boolean execute(SetStickerSetThumb setStickerSetThumb) throws TelegramApiException {
assertParamNotNull(setStickerSetThumb, "setStickerSetThumb");
setStickerSetThumb.validate();
try {
String url = getBaseUrl() + AddStickerToSet.PATH;
HttpPost httppost = configuredHttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setLaxMode();
builder.setCharset(StandardCharsets.UTF_8);
builder.addTextBody(SetStickerSetThumb.USERID_FIELD, setStickerSetThumb.getUserId().toString(), TEXT_PLAIN_CONTENT_TYPE);
builder.addTextBody(SetStickerSetThumb.NAME_FIELD, setStickerSetThumb.getName(), TEXT_PLAIN_CONTENT_TYPE);
addInputFile(builder, setStickerSetThumb.getThumb(), SetStickerSetThumb.THUMB_FIELD, true);
HttpEntity multipart = builder.build();
httppost.setEntity(multipart);
return setStickerSetThumb.deserializeResponse(sendHttpPostRequest(httppost));
} catch (IOException e) {
throw new TelegramApiException("Unable to add sticker to set", e);
}
}
/**
* 英文海关识别,使用Base64编码后的文件方式,使用Token认证方式访问服务
* @param token token认证串
* @param formFile 文件路径
* @throws IOException
*/
public static void requestOcrCustomsFormEnBase64(String token, String formFile) {
// 1.构建英文海关单据识别服务所需要的参数
String url = "https://ais.cn-north-1.myhuaweicloud.com/v1.0/ocr/action/ocr_form";
Header[] headers = new Header[] {new BasicHeader("X-Auth-Token", token) };
try {
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
FileBody fileBody = new FileBody(new File(formFile), ContentType.create("image/jpeg", "utf-8"));
multipartEntityBuilder.addPart("file", fileBody);
// 2.传入英文海关单据识别服务对应的参数, 使用POST方法调用服务并解析输出识别结果
HttpResponse response = HttpClientUtils.post(url, headers, multipartEntityBuilder.build());
System.out.println(response);
String content = IOUtils.toString(response.getEntity().getContent());
System.out.println(content);
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testImprovedUploadMethod() throws Exception {
HttpPost post = new HttpPost(httpsAdminServerUrl + "/ota/start?token=" + clientPair.token);
post.setHeader(HttpHeaderNames.AUTHORIZATION.toString(), "Basic " + Base64.getEncoder().encodeToString(auth));
String fileName = "test.bin";
InputStream binFile = OTATest.class.getResourceAsStream("/static/ota/" + fileName);
ContentBody fileBody = new InputStreamBody(binFile, ContentType.APPLICATION_OCTET_STREAM, fileName);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart("upfile", fileBody);
HttpEntity entity = builder.build();
post.setEntity(entity);
String path;
try (CloseableHttpResponse response = httpclient.execute(post)) {
assertEquals(200, response.getStatusLine().getStatusCode());
path = TestUtil.consumeText(response);
assertNotNull(path);
assertTrue(path.startsWith("/static"));
assertTrue(path.endsWith("bin"));
}
String responseUrl = "http://127.0.0.1:18080" + path;
verify(clientPair.hardwareClient.responseMock, timeout(500)).channelRead(any(), eq(internal(7777, "ota " + responseUrl)));
HttpGet index = new HttpGet("http://localhost:" + properties.getHttpPort() + path);
try (CloseableHttpResponse response = httpclient.execute(index)) {
assertEquals(200, response.getStatusLine().getStatusCode());
assertEquals("application/octet-stream", response.getHeaders("Content-Type")[0].getValue());
}
}
@Test
public void testPostFileUpload() throws org.apache.http.ParseException, IOException, AviApiException {
File f = new File("/mnt/files/hsmpackages/safenet.tar");
CloseableHttpClient httpClient = HttpClients.createDefault();
stubFor(post(urlEqualTo("/api/fileservice/hsmpackages?hsmtype=safenet"))
.withMultipartRequestBody(aMultipart().withName("uri").withBody(containing("controller://hsmpackages")))
.withMultipartRequestBody(aMultipart().withName("file").withBody(binaryEqualTo(f.getName().getBytes())))
.willReturn(ok()));
HttpUriRequest request = RequestBuilder
.post("http://localhost:8090/api/fileservice/hsmpackages?hsmtype=safenet")
.setEntity(MultipartEntityBuilder.create()
.addTextBody("uri", "controller://hsmpackages", ContentType.TEXT_PLAIN)
.addBinaryBody("file", f.getName().getBytes()).build())
.build();
HttpResponse response = httpClient.execute(request);
verify(postRequestedFor(urlEqualTo("/api/fileservice/hsmpackages?hsmtype=safenet")));
int responseCode = response.getStatusLine().getStatusCode();
if (responseCode > 299) {
StringBuffer errMessage = new StringBuffer();
errMessage.append("Failed : HTTP error code : ");
errMessage.append(responseCode);
if (null != response.getEntity()) {
errMessage.append(" Error Message :");
errMessage.append(EntityUtils.toString(response.getEntity()));
}
throw new AviApiException(errMessage.toString());
}
}
private void setMultiPartEntity(HttpPost httpPost, Map<String, String> params)
throws Exception {
ContentType utf8TextPlain = ContentType.create("text/plain", Consts.UTF_8);
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
for (String paramKey : params.keySet()) {
if (paramKey.equals(RequestBodyKey.FILE_CONTENT)) {
entityBuilder.addBinaryBody(RequestBodyKey.FILE_CONTENT, params
.get(RequestBodyKey.FILE_CONTENT).getBytes(Charset.forName("ISO-8859-1")));
} else {
entityBuilder.addTextBody(paramKey, params.get(paramKey), utf8TextPlain);
}
}
httpPost.setEntity(entityBuilder.build());
}
private static HttpUriRequest getUploadFileRequest(String method, URI uri, ContentBody contentBody,
@Nullable List<Header> headers, @Nullable List<NameValuePair> parameters, int socketTimeoutMs) {
// Build the Http entity
HttpEntity entity = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
.addPart(contentBody.getFilename(), contentBody).build();
// Build the request
RequestBuilder requestBuilder =
RequestBuilder.create(method).setVersion(HttpVersion.HTTP_1_1).setUri(uri).setEntity(entity);
addHeadersAndParameters(requestBuilder, headers, parameters);
setTimeout(requestBuilder, socketTimeoutMs);
return requestBuilder.build();
}
public Session addParams(Map<String,String> map){
MultipartEntityBuilder multipartEntity= (MultipartEntityBuilder) this.getProviderService().provider();
for(String key:map.keySet()){
multipartEntity.addTextBody(key,map.get(key));
}
return this;
}
@MethodSource("fileContentTypes")
@ParameterizedTest
void testAddFilePart(Optional<String> contentTypeAsString, ContentType contentType) throws IOException
{
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
String name = "fileKey";
String fileName = "requestBody.txt";
RequestPartType.FILE.addPart(builder, name, "/" + fileName, contentTypeAsString);
assertHttpEntity(builder, buildExpectedEntity(name + "\"; filename=\"" + fileName,
contentType, "binary", "{body}"));
}
/**
* 上传文件
* @param url URL
* @param name 文件的post参数名称
* @param file 上传的文件
* @return
*/
public static String postFile(String url,String name,File file){
try {
HttpEntity reqEntity = MultipartEntityBuilder.create().addBinaryBody(name, file).build();
Request request = Request.Post(url);
request.body(reqEntity);
HttpEntity resEntity = request.execute().returnResponse().getEntity();
return resEntity != null ? EntityUtils.toString(resEntity) : null;
} catch (Exception e) {
logger.error("postFile请求异常," + e.getMessage() + "\n post url:" + url);
e.printStackTrace();
}
return null;
}
@Test
public final void givenFileandMultipleTextParts_whenUploadwithAddPart_thenNoExceptions() throws IOException {
final URL url = Thread.currentThread()
.getContextClassLoader()
.getResource("uploads/" + TEXTFILENAME);
final File file = new File(url.getPath());
final FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY);
final StringBody stringBody1 = new StringBody("This is message 1", ContentType.MULTIPART_FORM_DATA);
final StringBody stringBody2 = new StringBody("This is message 2", ContentType.MULTIPART_FORM_DATA);
//
final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart("file", fileBody);
builder.addPart("text1", stringBody1);
builder.addPart("text2", stringBody2);
final HttpEntity entity = builder.build();
//
post.setEntity(entity);
response = client.execute(post);
final int statusCode = response.getStatusLine()
.getStatusCode();
final String responseString = getContent();
final String contentTypeInHeader = getContentTypeHeader();
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
// assertTrue(responseString.contains("Content-Type: multipart/form-data;"));
assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;"));
System.out.println(responseString);
System.out.println("POST Content Type: " + contentTypeInHeader);
}
private HttpEntity createDatasetFormData(String title) throws IOException {
MultipartEntityBuilder mb = MultipartEntityBuilder.create();
mb.addTextBody("title", title);
mb.addTextBody("repositoryId", "system");
mb.addTextBody("description", "Test");
mb.addTextBody("keywords", "Test");
return mb.build();
}