List of usage examples for org.apache.http.entity.mime MultipartEntityBuilder addPart
public MultipartEntityBuilder addPart(final String name, final ContentBody contentBody)
From source file:co.aurasphere.botmill.fb.internal.util.network.NetworkUtils.java
/** * POSTs a message as a JSON string to Facebook. * * @param recipient// ww w . j a v a 2 s .c o m * the recipient * @param type * the type * @param file * the file */ public static void postFormDataMessage(String recipient, AttachmentType type, File file) { String pageToken = FbBotMillContext.getInstance().getPageToken(); // If the page token is invalid, returns. if (!validatePageToken(pageToken)) { return; } // TODO: add checks for valid attachmentTypes (FILE, AUDIO or VIDEO) HttpPost post = new HttpPost(FbBotMillNetworkConstants.FACEBOOK_BASE_URL + FbBotMillNetworkConstants.FACEBOOK_MESSAGES_URL + pageToken); FileBody filedata = new FileBody(file); StringBody recipientPart = new StringBody("{\"id\":\"" + recipient + "\"}", ContentType.MULTIPART_FORM_DATA); StringBody messagePart = new StringBody( "{\"attachment\":{\"type\":\"" + type.name().toLowerCase() + "\", \"payload\":{}}}", ContentType.MULTIPART_FORM_DATA); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.STRICT); builder.addPart("recipient", recipientPart); builder.addPart("message", messagePart); // builder.addPart("filedata", filedata); builder.addBinaryBody("filedata", file); builder.setContentType(ContentType.MULTIPART_FORM_DATA); // builder.setBoundary("----WebKitFormBoundary7MA4YWxkTrZu0gW"); HttpEntity entity = builder.build(); post.setEntity(entity); // Logs the raw JSON for debug purposes. BufferedReader br; // post.addHeader("Content-Type", "multipart/form-data"); try { // br = new BufferedReader(new InputStreamReader( // ()))); Header[] allHeaders = post.getAllHeaders(); for (Header h : allHeaders) { logger.debug("Header {} -> {}", h.getName(), h.getValue()); } // String output = br.readLine(); } catch (Exception e) { e.printStackTrace(); } send(post); }
From source file:su.fmi.photoshareclient.remote.ImageHandler.java
public static void uploadImage(File img) { try {/*from w ww .jav a 2 s. c om*/ HttpClient httpclient = HttpClientBuilder.create().build(); ProjectProperties props = new ProjectProperties(); String endpoint = "http://" + props.get("socket") + props.get("restEndpoint") + "/image/create"; HttpPost httppost = new HttpPost(endpoint); MultipartEntityBuilder mpEntity = MultipartEntityBuilder.create(); ContentBody cbFile = new FileBody(img, ContentType.MULTIPART_FORM_DATA, img.getName()); mpEntity.addTextBody("fileName", img.getName()); mpEntity.addTextBody("description", "File uploaded via Photoshare Desktop Cliend on " + new SimpleDateFormat("HH:mm dd/MM/yyyy").format(Calendar.getInstance().getTime())); mpEntity.addPart("fileUpload", cbFile); httppost.setHeader("Authorization", "Basic " + LoginHandler.getAuthStringEncripted()); httppost.setEntity(mpEntity.build()); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); if (resEntity != null) { System.out.println(EntityUtils.toString(resEntity)); } if (resEntity != null) { EntityUtils.consume(resEntity); } httppost.releaseConnection(); } catch (IOException ex) { Logger.getLogger(ImageHandler.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.huawei.ais.demo.TokenDemo.java
/** * Base64???Token???/* ww w . j a v a 2 s . co m*/ * @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(); } }
From source file:com.game.simple.Game3.java
public static void uploadAvatar(final String token) { //---timer---// //StartReConnect(); //-----------// self.runOnUiThread(new Runnable() { public void run() { if (cropedImagePath == null) { Toast.makeText(self.getApplicationContext(), "Cha chn nh !", Toast.LENGTH_SHORT).show(); return; }//ww w . j a va 2s . c o m if (cropedImagePath.compareTo(" ") == 0) { Toast.makeText(self.getApplicationContext(), "Cha chn nh !", Toast.LENGTH_SHORT).show(); return; } else { HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPostRequest = new HttpPost(url); try { File file = new File(cropedImagePath); FileBody bin = new FileBody(file); StringBody tok = new StringBody(token); StringBody imageType = new StringBody("jpg"); MultipartEntityBuilder multiPartEntityBuilder = MultipartEntityBuilder.create(); multiPartEntityBuilder.addPart("token", tok); multiPartEntityBuilder.addPart("imageType", imageType); multiPartEntityBuilder.addPart("media", bin); httpPostRequest.setEntity(multiPartEntityBuilder.build()); // Execute POST request to the given URL HttpResponse httpResponse = null; httpResponse = httpClient.execute(httpPostRequest); // receive response as inputStream InputStream inputStream = null; inputStream = httpResponse.getEntity().getContent(); Log.e("--upload", "Upload complete"); Toast.makeText(self.getApplicationContext(), "Upload thnh cng!", Toast.LENGTH_SHORT) .show(); String result = ""; if (inputStream != null) result = convertInputStreamToString(inputStream); else result = " "; Log.e("upload", result); setlinkAvata(result); cropedImagePath = " "; } catch (Exception e) { Log.e("--Upload--", "ko the upload "); Toast.makeText(self.getApplicationContext(), "C li trong qu trnh upload!", Toast.LENGTH_SHORT).show(); } } //else } }); //---timer---// stopTimer(); //-----------// }
From source file:de.vanita5.twittnuker.util.net.TwidereHttpClientImpl.java
private static HttpEntity getAsEntity(final HttpParameter[] params) throws UnsupportedEncodingException { if (params == null) return null; if (!HttpParameter.containsFile(params)) return new HttpParameterFormEntity(params); final MultipartEntityBuilder me = MultipartEntityBuilder.create(); for (final HttpParameter param : params) { if (param.isFile()) { final ContentType contentType = ContentType.create(param.getContentType()); final ContentBody body; if (param.getFile() != null) { body = new FileBody(param.getFile(), ContentType.create(param.getContentType())); } else { body = new InputStreamBody(param.getFileBody(), contentType, param.getFileName()); }//from w w w. ja v a 2s.com me.addPart(param.getName(), body); } else { final ContentType contentType = ContentType.TEXT_PLAIN.withCharset(Consts.UTF_8); final ContentBody body = new StringBody(param.getValue(), contentType); me.addPart(param.getName(), body); } } return me.build(); }
From source file:com.liferay.mobile.android.http.file.UploadUtil.java
protected static HttpEntity getMultipartEntity(HttpPostHC4 request, JSONObject parameters) throws Exception { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); ContentType contentType = ContentType.create("text/plain", Consts.UTF_8); Iterator<String> it = parameters.keys(); while (it.hasNext()) { String key = it.next();/* w w w .java 2s. co m*/ Object value = parameters.get(key); ContentBody contentBody; if (value instanceof UploadData) { UploadData wrapper = (UploadData) value; wrapper.setRequest(request); contentBody = wrapper; } else { contentBody = new StringBody(value.toString(), contentType); } builder.addPart(key, contentBody); } return builder.build(); }
From source file:com.mywork.framework.util.RemoteHttpUtil.java
/** * ?MultipartHttp??????ContentBody map/*from w w w . j av a 2 s. co m*/ */ public static String fetchMultipartHttpResponse(String contentUrl, Map<String, String> headerMap, Map<String, ContentBody> bodyMap) throws IOException { try { HttpPost httpPost = new HttpPost(contentUrl); MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); if (headerMap != null && !headerMap.isEmpty()) { for (Map.Entry<String, String> m : headerMap.entrySet()) { httpPost.addHeader(m.getKey(), m.getValue()); } } if (bodyMap != null && !bodyMap.isEmpty()) { for (Map.Entry<String, ContentBody> m : bodyMap.entrySet()) { multipartEntityBuilder.addPart(m.getKey(), m.getValue()); } } HttpEntity reqEntity = multipartEntityBuilder.build(); httpPost.setEntity(reqEntity); CloseableHttpResponse response = httpClient.execute(httpPost); try { HttpEntity resEntity = response.getEntity(); String resStr = IOUtils.toString(resEntity.getContent()); return resStr; } catch (Exception e) { // TODO: handle exception } finally { response.close(); } } finally { httpClient.close(); } return null; }
From source file:org.sahli.asciidoc.confluence.publisher.client.http.HttpRequestFactory.java
private static HttpEntity multipartEntity(String attachmentFileName, InputStream attachmentContent) { MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); multipartEntityBuilder.setCharset(Charset.forName("UTF-8")); InputStreamBody inputStreamBody;/*from w w w.j av a 2 s. c o m*/ if (isNotBlank(attachmentFileName)) { inputStreamBody = new InputStreamBody(attachmentContent, APPLICATION_OCTET_STREAM, attachmentFileName); } else { inputStreamBody = new InputStreamBody(attachmentContent, APPLICATION_OCTET_STREAM); } multipartEntityBuilder.addPart("file", inputStreamBody); return multipartEntityBuilder.build(); }
From source file:securitytools.veracode.http.request.UploadFileRequest.java
public UploadFileRequest(String applicationId, File file, String sandboxId) { super("/api/4.0/uploadfile.do"); if (applicationId == null) { throw new IllegalArgumentException("Application id cannot be null."); }//from w w w . jav a2s .c om if (!file.canRead()) { throw new IllegalArgumentException("Cannot read file."); } MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); entityBuilder.addPart("app_id", new StringBody(applicationId, ContentType.TEXT_PLAIN)); if (sandboxId != null) { entityBuilder.addPart("sandbox_id", new StringBody(sandboxId, ContentType.TEXT_PLAIN)); } entityBuilder.addPart("file", new FileBody(file)); setEntity(entityBuilder.build()); }
From source file:com.codota.uploader.Uploader.java
private void uploadFile(File file, String uploadUrl) throws IOException { HttpPut putRequest = new HttpPut(uploadUrl); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart("code", new FileBody(file)); final HttpEntity entity = builder.build(); putRequest.setEntity(entity);//from w w w . j a va 2 s. com putRequest.setHeader("enctype", "multipart/form-data"); putRequest.setHeader("authorization", "bearer " + token); httpClient.execute(putRequest, new UploadResponseHandler()); }