本文整理汇总了Java中org.apache.http.entity.mime.MultipartEntityBuilder.addPart方法的典型用法代码示例。如果您正苦于以下问题:Java MultipartEntityBuilder.addPart方法的具体用法?Java MultipartEntityBuilder.addPart怎么用?Java MultipartEntityBuilder.addPart使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类org.apache.http.entity.mime.MultipartEntityBuilder
的用法示例。
在下文中一共展示了MultipartEntityBuilder.addPart方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: initRequest
import org.apache.http.entity.mime.MultipartEntityBuilder; //导入方法依赖的package包/类
public HttpPost initRequest(final FileUploadParameter parameter) {
final FileUploadAddress fileUploadAddress = getDependResult(FileUploadAddress.class);
final HttpPost request = new HttpPost("http://" + fileUploadAddress.getData().getUp() + CONST.URI_PATH);
final MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
multipartEntity.setCharset(Consts.UTF_8);
multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
multipartEntity.addPart(CONST.QID_NAME, new StringBody(getLoginInfo().getQid(), ContentType.DEFAULT_BINARY));
multipartEntity.addPart("ofmt", new StringBody("json", ContentType.DEFAULT_BINARY));
multipartEntity.addPart("method", new StringBody("Upload.web", ContentType.DEFAULT_BINARY));
multipartEntity.addPart("token", new StringBody(readCookieStoreValue("token"), ContentType.DEFAULT_BINARY));
multipartEntity.addPart("v", new StringBody("1.0.1", ContentType.DEFAULT_BINARY));
multipartEntity.addPart("tk", new StringBody(fileUploadAddress.getData().getTk(), ContentType.DEFAULT_BINARY));
multipartEntity.addPart("Upload", new StringBody("Submit Query", ContentType.DEFAULT_BINARY));
multipartEntity.addPart("devtype", new StringBody("web", ContentType.DEFAULT_BINARY));
multipartEntity.addPart("pid", new StringBody("ajax", ContentType.DEFAULT_BINARY));
multipartEntity.addPart("Filename",
new StringBody(parameter.getUploadFile().getName(), ContentType.APPLICATION_JSON));
multipartEntity.addPart("path", new StringBody(parameter.getPath(), ContentType.APPLICATION_JSON));// 解决中文不识别问题
multipartEntity.addBinaryBody("file", parameter.getUploadFile());
request.setEntity(multipartEntity.build());
return request;
}
示例2: uploadFile
import org.apache.http.entity.mime.MultipartEntityBuilder; //导入方法依赖的package包/类
public WebResponse uploadFile(String path, String fname, InputStream in,
String stoken) throws ClientProtocolException, IOException {
HttpPost post = new HttpPost(path);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
StringBody fn = new StringBody(fname, ContentType.MULTIPART_FORM_DATA);
builder.addPart("fname", fn);
builder.addBinaryBody("file", in, ContentType.APPLICATION_XML, fname);
BasicCookieStore cookieStore = new BasicCookieStore();
if (stoken != null) {
BasicClientCookie cookie = new BasicClientCookie(
Constants.SECURE_TOKEN_NAME, stoken);
cookie.setDomain(TestConstants.JETTY_HOST);
cookie.setPath("/");
cookieStore.addCookie(cookie);
}
TestConstants.LOG.debug("stoken=" + stoken);
HttpClient client = HttpClientBuilder.create().
setDefaultCookieStore(cookieStore).build();
HttpEntity entity = builder.build();
post.setEntity(entity);
HttpResponse response = client.execute(post);
String body;
ResponseHandler<String> handler = new BasicResponseHandler();
try {
body = handler.handleResponse(response);
} catch (HttpResponseException e) {
return new WebResponse(e.getStatusCode(), e.getMessage());
}
return new WebResponse(response.getStatusLine().getStatusCode(), body);
}
示例3: createFileEntity
import org.apache.http.entity.mime.MultipartEntityBuilder; //导入方法依赖的package包/类
@SuppressWarnings("unchecked")
private HttpEntity createFileEntity(Object files) {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
for (Entry<String, Object> entry : ((Map<String, Object>) files).entrySet()) {
if (new File(entry.getValue().toString()).exists()) {
builder.addPart(entry.getKey(),
new FileBody(new File(entry.getValue().toString()), ContentType.DEFAULT_BINARY));
} else {
builder.addPart(entry.getKey(), new StringBody(entry.getValue().toString(), ContentType.DEFAULT_TEXT));
}
}
return builder.build();
}
示例4: sendFormToDLMS
import org.apache.http.entity.mime.MultipartEntityBuilder; //导入方法依赖的package包/类
/**
* * Send POST request to DLMS back end with the result file
* @param bluemixToken - the Bluemix token
* @param contents - the result file
* @param jobUrl - the build url of the build job in Jenkins
* @param timestamp
* @return - response/error message from DLMS
*/
public String sendFormToDLMS(String bluemixToken, FilePath contents, String lifecycleStage, String jobUrl, String timestamp) throws IOException {
// create http client and post method
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost postMethod = new HttpPost(this.dlmsUrl);
postMethod = addProxyInformation(postMethod);
// build up multi-part forms
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
if (contents != null) {
File file = new File(root, contents.getName());
FileBody fileBody = new FileBody(file);
builder.addPart("contents", fileBody);
builder.addTextBody("test_artifact", file.getName());
if (this.isDeploy) {
builder.addTextBody("environment_name", environmentName);
}
//Todo check the value of lifecycleStage
builder.addTextBody("lifecycle_stage", lifecycleStage);
builder.addTextBody("url", jobUrl);
builder.addTextBody("timestamp", timestamp);
String fileExt = FilenameUtils.getExtension(contents.getName());
String contentType;
switch (fileExt) {
case "json":
contentType = CONTENT_TYPE_JSON;
break;
case "xml":
contentType = CONTENT_TYPE_XML;
break;
default:
return "Error: " + contents.getName() + " is an invalid result file type";
}
builder.addTextBody("contents_type", contentType);
HttpEntity entity = builder.build();
postMethod.setEntity(entity);
postMethod.setHeader("Authorization", bluemixToken);
} else {
return "Error: File is null";
}
CloseableHttpResponse response = null;
try {
response = httpClient.execute(postMethod);
// parse the response json body to display detailed info
String resStr = EntityUtils.toString(response.getEntity());
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(resStr);
if (!element.isJsonObject()) {
// 401 Forbidden
return "Error: Upload is Forbidden, please check your org name. Error message: " + element.toString();
} else {
JsonObject resJson = element.getAsJsonObject();
if (resJson != null && resJson.has("status")) {
return String.valueOf(response.getStatusLine()) + "\n" + resJson.get("status");
} else {
// other cases
return String.valueOf(response.getStatusLine());
}
}
} catch (IOException e) {
e.printStackTrace();
throw e;
}
}
示例5: constructRequestBody
import org.apache.http.entity.mime.MultipartEntityBuilder; //导入方法依赖的package包/类
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);
}
}
}
示例6: attachFileToTransaction
import org.apache.http.entity.mime.MultipartEntityBuilder; //导入方法依赖的package包/类
/**
* Retorna a lista de anexos de uma transação com ou sem filtro de tipo
* @param idTransacao: Código da transação à ser consultada
* @param arquivo: Arquivo à ser anexado (imagem [JPEG/PNG] ou documento [PDF])
* @param tipoAnexo: Tipo de anexo à ser enviado
* @return boolean
*/
public boolean attachFileToTransaction(String idTransacao, File arquivo, TipoAnexo tipoAnexo) throws IOException,
PJBankException {
Set<String> extensoesPermitidas = new HashSet<>();
extensoesPermitidas.add("pdf");
extensoesPermitidas.add("jpg");
extensoesPermitidas.add("jpeg");
extensoesPermitidas.add("png");
if (!extensoesPermitidas.contains(FilenameUtils.getExtension(arquivo.getName()))) {
throw new IllegalArgumentException("O arquivo a ser anexado em uma transação deve estar no formato PDF, JPG," +
" JPEG ou PNG, sendo assim um documento ou uma imagem.");
}
PJBankClient client = new PJBankClient(this.endPoint.concat("/transacoes/").concat(idTransacao).concat("/documentos"));
HttpPost httpPost = client.getHttpPostClient();
httpPost.addHeader("x-chave-conta", this.chave);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
//FileBody fileBody = new FileBody(arquivo);
StringBody stringBody = new StringBody(tipoAnexo.getName(), ContentType.TEXT_PLAIN);
//builder.addPart("arquivos", fileBody);
builder.addBinaryBody("arquivos", arquivo,
ContentType.APPLICATION_OCTET_STREAM, arquivo.getName());
builder.addPart("tipo", stringBody);
httpPost.setEntity(builder.build());
return client.doRequest(httpPost).getStatusLine().getStatusCode() == 201;
}
示例7: uploadFile
import org.apache.http.entity.mime.MultipartEntityBuilder; //导入方法依赖的package包/类
@Override
public String uploadFile(String systemName, String entityName, String apiUrl, List<File> fileList, String requestParamInputName) throws IllegalStateException {
HttpResponse response = null;
HttpPost httpPost = getHttpPost();
try {
List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
String[] urlAndParame = apiUrl.split("\\?");
String apiUrlNoParame = urlAndParame[0];
Map<String, String> parameMap = StrUtil.splitUrlToParameMap(apiUrl);
Iterator<String> parameIterator = parameMap.keySet().iterator();
httpPost.setURI(new URI(apiUrlNoParame));
MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
while (parameIterator.hasNext()) {
String parameName = parameIterator.next();
nvps.add(new BasicNameValuePair(parameName, parameMap.get(parameName)));
multipartEntity.addPart(parameName, new StringBody(parameMap.get(parameName), ContentType.create("text/plain", Consts.UTF_8)));
}
if (!StrUtil.isBlank(systemName)) {
multipartEntity.addPart("systemName", new StringBody(systemName, ContentType.create("text/plain", Consts.UTF_8)));
}
if (!StrUtil.isBlank(entityName)) {
multipartEntity.addPart("entityName", new StringBody(entityName, ContentType.create("text/plain", Consts.UTF_8)));
}
// 多文件上传 获取文件数组前台标签name值
if (!StrUtil.isBlank(requestParamInputName)) {
multipartEntity.addPart("filesName", new StringBody(requestParamInputName, ContentType.create("text/plain", Consts.UTF_8)));
}
if (fileList != null) {
for (int i = 0, size = fileList.size(); i < size; i++) {
File file = fileList.get(i);
multipartEntity.addBinaryBody(requestParamInputName, file, ContentType.DEFAULT_BINARY, file.getName());
}
}
HttpEntity entity = multipartEntity.build();
httpPost.setEntity(entity);
response = httpClient.execute(httpPost);
String statusCode = String.valueOf(response.getStatusLine().getStatusCode());
if (statusCode.indexOf("20") == 0) {
entity = response.getEntity();
// String contentType = entity.getContentType().getValue();//
// application/json;charset=ISO-8859-1
return StrUtil.readStream(entity.getContent(), responseContextEncode);
} else {
LOG.error("返回状态码:[" + statusCode + "]");
return "返回状态码:[" + statusCode + "]";
}
} catch (Exception e) {
e.printStackTrace();
} finally {
httpPost.releaseConnection();
}
return null;
}
示例8: uploadWelcomeMessage
import org.apache.http.entity.mime.MultipartEntityBuilder; //导入方法依赖的package包/类
public ApiResponse uploadWelcomeMessage(String filePath, int messageId, int selectedMessageId) {
File file = new File(filePath);
HttpPost uploadRequest = new HttpPost(WELCOME_MESSAGE_URI);
StringBody commandeBody = new StringBody("annonce_mess", ContentType.MULTIPART_FORM_DATA);
StringBody messageIdBody = new StringBody(String.valueOf(messageId), ContentType.MULTIPART_FORM_DATA);
StringBody maxFileSizeBody = new StringBody("5242880", ContentType.MULTIPART_FORM_DATA);
StringBody selectMessageBody = new StringBody(String.valueOf(selectedMessageId),
ContentType.MULTIPART_FORM_DATA);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addBinaryBody("FILE", file, ContentType.create("audio/mp3"), "message.mp3");
builder.addPart("commande", commandeBody);
builder.addPart("id_message", messageIdBody);
builder.addPart("id_message_select", selectMessageBody);
builder.addPart("MAX_FILE_SIZE", maxFileSizeBody);
HttpEntity entity = builder.build();
uploadRequest.setEntity(entity);
HttpResponse response = executeRequest(uploadRequest);
return new ApiResponse(HttpStatus.gethttpStatus(response.getStatusLine().getStatusCode()));
}
示例9: uploadFile
import org.apache.http.entity.mime.MultipartEntityBuilder; //导入方法依赖的package包/类
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();
}
}
示例10: sendFile
import org.apache.http.entity.mime.MultipartEntityBuilder; //导入方法依赖的package包/类
private String sendFile(String chat_id, String file_id, String type, String caption, boolean disable_notification,
int reply_to_message_id, ReplyMarkup reply_markup, int duration, String performer, String title, int width,
int height) throws IOException {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart("chat_id", new StringBody(chat_id, ContentType.DEFAULT_TEXT));
if (caption != null)
builder.addPart("caption", new StringBody(caption, ContentType.DEFAULT_TEXT));
if (disable_notification != false)
builder.addPart("disable_notification",
new StringBody(Boolean.toString(disable_notification), ContentType.DEFAULT_TEXT));
if (reply_to_message_id > 0)
builder.addPart("reply_to_message_id",
new StringBody(Integer.toString(reply_to_message_id), ContentType.DEFAULT_TEXT));
if (reply_markup != null)
builder.addPart("reply_markup",
new StringBody(URLEncoder.encode(reply_markup.toJSONString(), "utf-8"), ContentType.DEFAULT_TEXT));
if (duration > 0)
builder.addPart("duration", new StringBody(Integer.toString(duration), ContentType.DEFAULT_TEXT));
if (performer != null)
builder.addPart("performer", new StringBody(performer, ContentType.DEFAULT_TEXT));
if (title != null)
builder.addPart("title", new StringBody(title, ContentType.DEFAULT_TEXT));
if (width > 0)
builder.addPart("width", new StringBody(Integer.toString(width), ContentType.DEFAULT_TEXT));
if (height > 0)
builder.addPart("height", new StringBody(Integer.toString(height), ContentType.DEFAULT_TEXT));
builder.addPart(type, new StringBody(file_id, ContentType.DEFAULT_TEXT));
HttpEntity entity = builder.build();
HttpPost post = new HttpPost(url + "/send" + type);
post.setEntity(entity);
CloseableHttpClient httpclient = HttpClients.createMinimal();
HttpResponse response = httpclient.execute(post);
return response.toString();
}
示例11: postBodyAsMultipart
import org.apache.http.entity.mime.MultipartEntityBuilder; //导入方法依赖的package包/类
/**
* 发送body为multipart form
* sample
*/
public static String postBodyAsMultipart(String url,Map<String,ContentBody> contentBodies,String charset) throws Exception{
HttpPost httpPost = new HttpPost(url);
MultipartEntityBuilder mb = MultipartEntityBuilder.create();
mb.setCharset(Charset.forName(charset));
for(Map.Entry<String,ContentBody> entry : contentBodies.entrySet()) {
mb.addPart(entry.getKey(),entry.getValue());
}
httpPost.setEntity(mb.build());
CloseableHttpResponse response = httpClient.execute(httpPost);
try {
HttpEntity entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
httpPost.abort();
throw new RuntimeException("HttpClient,error status code :" + statusCode);
}
String result = null;
if (entity != null) {
result = EntityUtils.toString(entity, "utf-8");
}
EntityUtils.consume(entity);
return result;
} finally {
response.close();
}
}
示例12: put
import org.apache.http.entity.mime.MultipartEntityBuilder; //导入方法依赖的package包/类
@Override
public <T> T put(String uri, Collection<Header> headers, Class<T> type, Part... parts) throws IOException {
HttpPut request = newPut(uri, headers);
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
for (Part part : parts) {
entityBuilder.addPart(part.getName(), newContentBody(part));
}
request.setEntity(entityBuilder.build());
return execute(request, type);
}
示例13: post
import org.apache.http.entity.mime.MultipartEntityBuilder; //导入方法依赖的package包/类
@Override
public <T> T post(String uri, Collection<Header> headers, Class<T> type, Part... parts) throws IOException {
HttpPost request = newPost(uri, headers);
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
for (Part part : parts) {
entityBuilder.addPart(part.getName(), newContentBody(part));
}
request.setEntity(entityBuilder.build());
return execute(request, type);
}
示例14: importImage
import org.apache.http.entity.mime.MultipartEntityBuilder; //导入方法依赖的package包/类
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://";
}
示例15: uploadContent
import org.apache.http.entity.mime.MultipartEntityBuilder; //导入方法依赖的package包/类
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;
}
}