下面列出了org.apache.http.entity.mime.MultipartEntityBuilder#addPart ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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();
}
}
/**
* 发送 post请求(带文件)
*
* @param httpUrl
* 地址
* @param maps
* 参数
* @param fileLists
* 附件
*/
public ResponseContent sendHttpPost(String httpUrl, Map<String, String> maps, List<File> fileLists,
Map<String, String> headers, RequestConfig requestConfig, int executionCount, int retryInterval) {
HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
MultipartEntityBuilder meBuilder = MultipartEntityBuilder.create();
if (null != maps && maps.size() > 0) {
for (String key : maps.keySet()) {
meBuilder.addPart(key, new StringBody(maps.get(key), ContentType.TEXT_PLAIN));
}
}
for (File file : fileLists) {
FileBody fileBody = new FileBody(file);
meBuilder.addPart("files", fileBody);
}
HttpEntity reqEntity = meBuilder.build();
httpPost.setEntity(reqEntity);
return sendHttpPost(httpPost, headers, requestConfig, executionCount, retryInterval);
}
@Test
public void testFormParamWithMultipart() throws IOException, URISyntaxException {
HttpURLConnection connection = request("/test/v1/formParam", HttpMethod.POST);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addPart("name", new StringBody("wso2", ContentType.TEXT_PLAIN));
builder.addPart("age", new StringBody("10", ContentType.TEXT_PLAIN));
HttpEntity build = builder.build();
connection.setRequestProperty("Content-Type", build.getContentType().getValue());
try (OutputStream out = connection.getOutputStream()) {
build.writeTo(out);
}
InputStream inputStream = connection.getInputStream();
String response = StreamUtil.asString(inputStream);
IOUtils.closeQuietly(inputStream);
connection.disconnect();
assertEquals(response, "wso2:10");
}
@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);
}
}
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());
}
}
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://";
}
@Override
protected CloseableHttpResponse send(CloseableHttpClient httpClient, String baseUrl) throws Exception {
//1)构建实体
MultipartEntityBuilder entBuilder = MultipartEntityBuilder.create();
for (String key : params.keySet()) {
Object item = params.get(key);
if(item instanceof File){
File file = (File)item;
if((!file.exists()) || (file.isDirectory())){
throw new Exception("file error");
}
entBuilder.addPart(key, new FileBody(file));
}else if(item instanceof String){
String value = (String)item;
entBuilder.addPart(key, new StringBody(value, ContentType.TEXT_PLAIN));
}else{
throw new Exception(item.getClass().toString()+" not support");
}
}
HttpEntity reqEntity = entBuilder.build();
//2)发送并等待回复
HttpPost request = new HttpPost(baseUrl);
request.setEntity(reqEntity);
return httpClient.execute(request);
}
@Test
public void testOTAFailedWhenNoDevice() throws Exception {
clientPair.hardwareClient.stop();
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);
try (CloseableHttpResponse response = httpclient.execute(post)) {
assertEquals(400, response.getStatusLine().getStatusCode());
String error = TestUtil.consumeText(response);
assertNotNull(error);
assertEquals("No device in session.", error);
}
}
/**
* POST方式发送名值对请求URL,上传文件(包括图片)
*
* @param url
* @return
* @throws HttpException
* @throws IOException
*/
public ResponseStatus postEntity(String url, String urlEncoding) throws HttpException, IOException {
if (url == null)
return null;
HttpEntity entity = null;
HttpRequestBase request = null;
CloseableHttpResponse response = null;
try {
this.parseUrl(url);
HttpPost httpPost = new HttpPost(toUrl());
//对请求的表单域进行填充
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
for (NameValuePair nameValuePair : this.getNVBodies()) {
entityBuilder.addPart(nameValuePair.getName(),
new StringBody(nameValuePair.getValue(), ContentType.create("text/plain", urlEncoding)));
}
for (ContentBody contentBody : getContentBodies()) {
entityBuilder.addPart("file", contentBody);
}
entityBuilder.setCharset(CharsetUtils.get(urlEncoding));
httpPost.setEntity(entityBuilder.build());
request = httpPost;
response = client.execute(request);
//响应状态
StatusLine statusLine = response.getStatusLine();
// 获取响应对象
entity = response.getEntity();
ResponseStatus ret = new ResponseStatus();
ret.setStatusCode(statusLine.getStatusCode());
getResponseStatus(entity, ret);
return ret;
} finally {
close(entity, request, response);
}
}
private String upload(String filename) throws Exception {
InputStream logoStream = UploadAPITest.class.getResourceAsStream("/" + filename);
HttpPost post = new HttpPost("http://localhost:" + properties.getHttpPort() + "/upload");
ContentBody fileBody = new InputStreamBody(logoStream, ContentType.APPLICATION_OCTET_STREAM, filename);
StringBody stringBody1 = new StringBody("Message 1", ContentType.MULTIPART_FORM_DATA);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart("upfile", fileBody);
builder.addPart("text1", stringBody1);
HttpEntity entity = builder.build();
post.setEntity(entity);
String staticPath;
try (CloseableHttpResponse response = httpclient.execute(post)) {
assertEquals(200, response.getStatusLine().getStatusCode());
staticPath = TestUtil.consumeText(response);
assertNotNull(staticPath);
assertTrue(staticPath.startsWith("/static"));
assertTrue(staticPath.endsWith("bin"));
}
return staticPath;
}
@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);
}
public Session uploadFile(byte [] bytes,String filename,String appName,String dirName){
MultipartEntityBuilder multipartEntity= (MultipartEntityBuilder) this.getProviderService().provider();
ContentBody byteArrayBody = new ByteArrayBody(bytes, filename);
multipartEntity.addPart("file", byteArrayBody);
multipartEntity.addTextBody("dirName", dirName);
multipartEntity.addTextBody("filename", filename);
multipartEntity.addTextBody("appName",appName);
return this;
}
private void constructRequestBody() {
// we have work to do here only when using multipart body
if (requestBodyParts.size() > 0) {
try {
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
for (HttpBodyPart part : requestBodyParts) {
entityBuilder.addPart(part.getName(), part.constructContentBody());
}
requestBody = entityBuilder.build();
} catch (Exception e) {
throw new HttpException("Exception trying to create a multipart message.", e);
}
}
}
@Test
public void basicOTAForAllDevices() throws Exception {
HttpPost post = new HttpPost(httpsAdminServerUrl + "/ota/start");
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, after(500).never()).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());
}
}
private static HttpUriRequest getUploadSegmentMetadataFilesRequest(URI uri, Map<String, File> metadataFiles,
int segmentUploadRequestTimeoutMs) {
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create().
setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
for (Map.Entry<String, File> entry : metadataFiles.entrySet()) {
multipartEntityBuilder.addPart(entry.getKey(), getContentBody(entry.getKey(), entry.getValue()));
}
HttpEntity entity = multipartEntityBuilder.build();
// Build the POST request.
RequestBuilder requestBuilder =
RequestBuilder.create(HttpPost.METHOD_NAME).setVersion(HttpVersion.HTTP_1_1).setUri(uri).setEntity(entity);
setTimeout(requestBuilder, segmentUploadRequestTimeoutMs);
return requestBuilder.build();
}
private boolean uploadContent(String filePath, String url, String msg) throws IOException{
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(new File(filePath));
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart("archive", cbFile);
builder.addPart("subcategory", new StringBody("115", ContentType.MULTIPART_FORM_DATA));
builder.addPart("msg_commit", new StringBody(msg, 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());
int statusCode = resultPost.getKey();
switch (statusCode) {
case 200:
return !resultPost.getValue ().contains ("alert-box alert");
case 404:
log.debug("L'id cible du contenu ou le slug est incorrect. Donnez de meilleur informations");
return false;
case 403:
log.debug("Vous n'êtes pas autorisé à uploader ce contenu. Vérifiez que vous êtes connecté");
return false;
case 413:
log.debug("Le fichier que vous essayer d'envoyer est beaucoup trop lourd. Le serveur n'arrive pas à le supporter");
return false;
default:
log.debug("Problème d'upload du contenu. Le code http de retour est le suivant : "+statusCode);
return false;
}
}
private static HttpResponse sendData(
CloseableHttpClient client,
File reportFile,
String serverUrl,
String apiKey,
String project
) throws IOException{
if(client == null)
return null;
try {
HttpPost post = new HttpPost(serverUrl + "/api/projects/" + project + "/analysis");
post.setHeader("API-Key", apiKey);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart("file", new FileBody(reportFile));
HttpEntity entity = builder.build();
post.setEntity(entity);
HttpResponse response = client.execute(post);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
EntityUtils.consume(resEntity);
}
return response;
} finally {
client.close();
}
}
@Test
public void basicOTAForSingleUserAndNonExistingProject() throws Exception {
HttpPost post = new HttpPost(httpsAdminServerUrl + "/ota/start?user=" + getUserName() + "&project=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);
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, after(500).never()).channelRead(any(), eq(internal(7777, "ota " + responseUrl)));
TestHardClient newHardwareClient = new TestHardClient("localhost", properties.getHttpPort());
newHardwareClient.start();
newHardwareClient.login(clientPair.token);
verify(newHardwareClient.responseMock, timeout(1000)).channelRead(any(), eq(ok(1)));
newHardwareClient.reset();
newHardwareClient.send("internal " + b("ver 0.3.1 h-beat 10 buff-in 256 dev Arduino cpu ATmega328P con W5100 build 111"));
verify(newHardwareClient.responseMock, timeout(500)).channelRead(any(), eq(ok(1)));
verify(clientPair.hardwareClient.responseMock, never()).channelRead(any(), eq(internal(7777, "ota " + responseUrl)));
}
private String uploadCSARToWinery(final File file, final boolean overwrite) throws URISyntaxException, IOException {
final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
final ContentBody fileBody = new FileBody(file);
final ContentBody overwriteBody = new StringBody(String.valueOf(overwrite), ContentType.TEXT_PLAIN);
final FormBodyPart filePart = FormBodyPartBuilder.create("file", fileBody).build();
final FormBodyPart overwritePart = FormBodyPartBuilder.create("overwrite", overwriteBody).build();
builder.addPart(filePart);
builder.addPart(overwritePart);
final HttpEntity entity = builder.build();
final HttpPost wineryPost = new HttpPost();
wineryPost.setURI(new URI(this.wineryPath));
wineryPost.setEntity(entity);
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
final CloseableHttpResponse wineryResp = httpClient.execute(wineryPost);
String location = getHeaderValue(wineryResp, HttpHeaders.LOCATION);
wineryResp.close();
if (Objects.nonNull(location) && location.endsWith("/")) {
location = location.substring(0, location.length() - 1);
}
return location;
} catch (final IOException e) {
LOG.error("Exception while uploading CSAR to the Container Repository: ", e);
return "";
}
}
public static void addPartMethod01(File documentFile) throws Exception {
//String textFileName = "C:/tmp/AnalisiTraffico.xlsx";
//File file = new File(textFileName);
File file = documentFile;
//HttpPost post = new HttpPost("http://localhost:8080/jodapp/");
///jodapp/converted/document.pdf
HttpPost httppost = new HttpPost("http://localhost:8080/jodapp/converted/document.pdf");
FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY);
StringBody stringBody1 = new StringBody("pdf", ContentType.DEFAULT_TEXT);
//
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart("inputDocument", fileBody);
builder.addPart("outputFormat", stringBody1);
HttpEntity entity = builder.build();
//
httppost.setEntity(entity);
CloseableHttpClient httpclient = HttpClients.createDefault();
CloseableHttpResponse response = httpclient.execute(httppost);
try {
int responseStatus = response.getStatusLine().getStatusCode();
System.out.println("responseStatus: " + responseStatus);
HttpEntity rent = response.getEntity();
if (rent != null) {
/*String respoBody = EntityUtils.toString(rent, "UTF-8");
System.out.println(respoBody); */
System.out.println("ctype: " + rent.getContentType());
System.out.println("length: " + rent.getContentLength());
if (responseStatus == 200) {
// do something useful with the response body
// and ensure it is fully consumed
EntityUtils.consume(rent);
} else {
String respoBody = EntityUtils.toString(rent, "UTF-8");
System.err.println("responseStatus: " + responseStatus);
System.err.println(file.getName());
System.err.println(respoBody);
}
}
} finally {
response.close();
}
httpclient.close();
}