本文整理汇总了Java中org.apache.http.entity.mime.MultipartEntityBuilder.setMode方法的典型用法代码示例。如果您正苦于以下问题:Java MultipartEntityBuilder.setMode方法的具体用法?Java MultipartEntityBuilder.setMode怎么用?Java MultipartEntityBuilder.setMode使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类org.apache.http.entity.mime.MultipartEntityBuilder
的用法示例。
在下文中一共展示了MultipartEntityBuilder.setMode方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: addStreamToEntity
import org.apache.http.entity.mime.MultipartEntityBuilder; //导入方法依赖的package包/类
/**
* Adds a stream to an HTTP entity
*
* @param someStream Input stream to be added to an HTTP entity
* @param fieldName A description of the entity content
* @param fileName Name of the file attached as an entity
* @return HTTP entity
* @throws IOException Signals a failure while reading the input stream
*/
HttpEntity addStreamToEntity(InputStream someStream, String fieldName, String fileName) throws IOException {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int bytesRead;
byte[] bytes = new byte[1024];
while ((bytesRead = someStream.read(bytes)) > 0) {
byteArrayOutputStream.write(bytes, 0, bytesRead);
}
byte[] data = byteArrayOutputStream.toByteArray();
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.setStrictMode();
builder.addBinaryBody(fieldName, data, ContentType.MULTIPART_FORM_DATA, fileName);
return builder.build();
}
示例2: postForm
import org.apache.http.entity.mime.MultipartEntityBuilder; //导入方法依赖的package包/类
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;
}
示例3: 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;
}
示例4: main
import org.apache.http.entity.mime.MultipartEntityBuilder; //导入方法依赖的package包/类
public static void main(String args[]){
HttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://localhost:8080/sso-web/upload");
httpPost.addHeader("Range","bytes=10000-");
final MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
multipartEntity.setCharset(Consts.UTF_8);
multipartEntity.setMode(HttpMultipartMode.STRICT);
multipartEntity.addBinaryBody("file", new File("/Users/huanghuanlai/Desktop/test.java"));
httpPost.setEntity(multipartEntity.build());
try {
HttpResponse response = httpClient.execute(httpPost);
} catch (IOException e) {
e.printStackTrace();
}
}
示例5: ClientConnection
import org.apache.http.entity.mime.MultipartEntityBuilder; //导入方法依赖的package包/类
/**
* POST request
* @param urlstring
* @param map
* @param useAuthentication
* @throws ClientProtocolException
* @throws IOException
*/
public ClientConnection(String urlstring, Map<String, byte[]> map, boolean useAuthentication) throws ClientProtocolException, IOException {
this.request = new HttpPost(urlstring);
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
for (Map.Entry<String, byte[]> entry: map.entrySet()) {
entityBuilder.addBinaryBody(entry.getKey(), entry.getValue());
}
((HttpPost) this.request).setEntity(entityBuilder.build());
this.request.setHeader("User-Agent", ClientIdentification.getAgent(ClientIdentification.yacyInternetCrawlerAgentName).userAgent);
this.init();
}
示例6: 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;
}
}
示例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: sendFile
import org.apache.http.entity.mime.MultipartEntityBuilder; //导入方法依赖的package包/类
private String sendFile(String chat_id, File file, 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 FileBody(file, ContentType.DEFAULT_BINARY));
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();
}
示例10: 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://";
}
示例11: 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;
}
}
示例12: 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);
}
示例13: sendData
import org.apache.http.entity.mime.MultipartEntityBuilder; //导入方法依赖的package包/类
private HttpResponse sendData(File data, String urlStr) throws IOException{
CloseableHttpClient client = burpExtender.getHttpClient();
if(client == null)
return null;
HttpPost post = new HttpPost(urlStr);
post.setHeader("API-Key", burpExtender.getApiKey());
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart("file", new FileBody(data));
HttpEntity entity = builder.build();
post.setEntity(entity);
HttpResponse response = client.execute(post);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
EntityUtils.consume(resEntity);
}
client.close();
return response;
}
示例14: postFile
import org.apache.http.entity.mime.MultipartEntityBuilder; //导入方法依赖的package包/类
private Result postFile(String url, List<String[]> datas, File file) {
if (!file.exists()) {
throw new JapiException(file.getAbsolutePath() + " file not exist.");
}
HttpPost httpPost = new HttpPost(url);
Integer tryCount = 0;
while (reties > tryCount) {
try {
final MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
multipartEntity.setCharset(Charset.forName("utf-8"));
multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
for (String[] nameValue : datas) {
multipartEntity.addPart(nameValue[0], new StringBody(nameValue[1], ContentType.APPLICATION_JSON));
}
multipartEntity.addBinaryBody("file", file);
httpPost.setEntity(multipartEntity.build());
httpPost.setHeader("token", token);
String result = EntityUtils.toString(HTTP_CLIENT.execute(httpPost).getEntity());
Result result1 = JSON.parseObject(result, ResultImpl.class);
if (result1.getCode() != 0) {
throw new JapiException(result1.getMsg());
}
return result1;
} catch (IOException e) {
if (e instanceof HttpHostConnectException) {
tryCount++;
LOGGER.warn("try connect server " + tryCount + " count.");
try {
TimeUnit.SECONDS.sleep(tryTime);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
}
if (tryCount <= reties) {
LOGGER.error("server connect failed.");
}
return null;
}
示例15: 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();
}
}