List of usage examples for org.apache.http.entity.mime MultipartEntity addPart
public void addPart(final String name, final ContentBody contentBody)
From source file:com.openkm.applet.Util.java
/** * Upload scanned document to OpenKM/*ww w. j a v a2 s . c o m*/ * */ public static String createDocument(String token, String path, String fileName, String fileType, String url, List<BufferedImage> images) throws MalformedURLException, IOException { log.info("createDocument(" + token + ", " + path + ", " + fileName + ", " + fileType + ", " + url + ", " + images + ")"); File tmpDir = createTempDir(); File tmpFile = new File(tmpDir, fileName + "." + fileType); ImageOutputStream ios = ImageIO.createImageOutputStream(tmpFile); String response = ""; try { if ("pdf".equals(fileType)) { ImageUtils.writePdf(images, ios); } else if ("tif".equals(fileType)) { ImageUtils.writeTiff(images, ios); } else { if (!ImageIO.write(images.get(0), fileType, ios)) { throw new IOException("Not appropiated writer found!"); } } ios.flush(); ios.close(); if (token != null) { // Send image HttpClient client = new DefaultHttpClient(); MultipartEntity form = new MultipartEntity(); form.addPart("file", new FileBody(tmpFile)); form.addPart("path", new StringBody(path, Charset.forName("UTF-8"))); form.addPart("action", new StringBody("0")); // FancyFileUpload.ACTION_INSERT HttpPost post = new HttpPost(url + "/frontend/FileUpload;jsessionid=" + token); post.setHeader("Cookie", "jsessionid=" + token); post.setEntity(form); ResponseHandler<String> responseHandler = new BasicResponseHandler(); response = client.execute(post, responseHandler); } else { // Store in disk String home = System.getProperty("user.home"); File dst = new File(home, tmpFile.getName()); copyFile(tmpFile, dst); response = "Image copied to " + dst.getPath(); } } finally { FileUtils.deleteQuietly(tmpDir); } log.info("createDocument: " + response); return response; }
From source file:com.lambdasoup.panda.PandaHttp.java
static String postFile(String url, Map<String, String> params, Properties properties, File file) { Map<String, String> sParams = signedParams("POST", url, params, properties); String flattenParams = canonicalQueryString(sParams); String requestUrl = "http://" + properties.getProperty("api-host") + ":80/v2" + url + "?" + flattenParams; HttpPost httpPost = new HttpPost(requestUrl); String stringResponse = null; FileBody bin = new FileBody(file, "application/octet-stream"); try {//from w w w.jav a 2 s.c om MultipartEntity entity = new MultipartEntity(); entity.addPart("file", bin); httpPost.setEntity(entity); DefaultHttpClient httpclient = new DefaultHttpClient(); HttpResponse response = httpclient.execute(httpPost); stringResponse = EntityUtils.toString(response.getEntity()); } catch (UnsupportedEncodingException ex) { ex.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return stringResponse; }
From source file:org.apache.hadoop.hdfs.qjournal.server.TestJournalNodeImageUpload.java
static HttpPost createRequest(String httpAddress, ContentBody cb) { HttpPost postRequest = new HttpPost(httpAddress + "/uploadImage"); MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); reqEntity.addPart("file", cb); postRequest.setEntity(reqEntity);//w w w . j a v a 2 s .co m return postRequest; }
From source file:de.vanita5.twittnuker.util.shortener.TweetShortenerUtils.java
/** * Shorten long tweets with hotot.in/*from w w w . j ava 2 s .c om*/ * @param context * @param text * @param accounts * @return shortened tweet */ public static String shortWithHototin(final Context context, final String text, final Account[] accounts) { String screen_name = null; String avatar_url = null; if (accounts != null && accounts.length > 0) { screen_name = getAccountScreenName(context, accounts[0].account_id); avatar_url = getAccountProfileImage(context, accounts[0].account_id); avatar_url = avatar_url != null && !avatar_url.isEmpty() ? avatar_url : DEFAULT_AVATAR_URL; } try { HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(HOTOTIN_URL); MultipartEntity requestEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); requestEntity.addPart(HOTOTIN_ENTITY_NAME, new StringBody(screen_name)); requestEntity.addPart(HOTOTIN_ENTITY_AVATAR, new StringBody(avatar_url)); requestEntity.addPart(HOTOTIN_ENTITY_TEXT, new StringBody(text, Charset.forName("UTF-8"))); httpPost.setEntity(requestEntity); InputStream responseStream; BufferedReader br; HttpResponse response = httpClient.execute(httpPost); HttpEntity responseEntity = response.getEntity(); responseStream = responseEntity.getContent(); br = new BufferedReader(new InputStreamReader(responseStream)); String responseLine = br.readLine(); String tmpResponse = ""; while (responseLine != null) { tmpResponse += responseLine + System.getProperty("line.separator"); responseLine = br.readLine(); } br.close(); JSONObject jsonObject = new JSONObject(tmpResponse); String result = jsonObject.getString("text"); return result; } catch (UnsupportedEncodingException e) { if (Utils.isDebugBuild()) Log.e(LOG_TAG, e.getMessage()); e.printStackTrace(); } catch (ClientProtocolException e) { if (Utils.isDebugBuild()) Log.e(LOG_TAG, e.getMessage()); e.printStackTrace(); } catch (IOException e) { if (Utils.isDebugBuild()) Log.e(LOG_TAG, e.getMessage()); e.printStackTrace(); } catch (JSONException e) { if (Utils.isDebugBuild()) Log.e(LOG_TAG, e.getMessage()); e.printStackTrace(); } return null; }
From source file:com.hoiio.api.FaxAPI.java
/*** * Sends a fax specified by the method parameters * @see <a href="http://developer.hoiio.com/docs/fax_send.html">http://developer.hoiio.com/docs/fax_send.html</a> * @param auth The user authorization object for the request * @param sender The sender number or caller id to be displayed * @param dest The destination to send the fax to. Phone numbers should start with a "+" and country code (E.164 format), e.g. +6511111111. * @param filepath The path of the fax to be sent * @param filename The file name of the fax desired * @return A unique reference ID for this fax transaction. This parameter will not be present if the request was not successful. * @throws HttpPostConnectionException if there is a connection failure * @throws HoiioRestException if there were problems using this REST API */// w ww .j a v a 2s . co m public static String sendFax(HoiioAuth auth, String sender, String dest, String filepath, String filename) throws HttpPostConnectionException, HoiioRestException { try { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpPost method = new HttpPost(APIUrls.SEND_FAX); MultipartEntity entity = new MultipartEntity(); entity.addPart("app_id", new StringBody(auth.getAppId(), Charset.forName("UTF-8"))); entity.addPart("access_token", new StringBody(auth.getToken(), Charset.forName("UTF-8"))); entity.addPart("dest", new StringBody(dest, Charset.forName("UTF-8"))); entity.addPart("tag", new StringBody(filename, Charset.forName("UTF-8"))); entity.addPart("filename", new StringBody(filename, Charset.forName("UTF-8"))); if (sender != null && sender.length() > 0) { entity.addPart("caller_id", new StringBody(sender, Charset.forName("UTF-8"))); } FileBody fileBody = new FileBody(new File(filepath)); entity.addPart("file", fileBody); method.setEntity(entity); log.info("executing request " + method.getRequestLine()); HttpResponse httpResponse = httpclient.execute(method); String responseBody = IOUtils.toString(httpResponse.getEntity().getContent(), "UTF-8"); final APIResponse response = new APIResponse(responseBody); if (response.getStatus() == APIStatus.success_ok) { return response.getResponseMap().getString("txn_ref"); } else { log.error("Error with request: " + method.getRequestLine()); log.error(response.getResponseString()); throw new HoiioRestException(new APIRequest(APIUrls.SEND_FAX, method.getRequestLine().toString()), response); } } catch (IOException ex) { throw new HttpPostConnectionException(ex); } }
From source file:org.factpub.ui.gui.network.PostFile.java
public static List<String> uploadToFactpub(File file) throws Exception { List<String> status = new ArrayList<String>(); int i = 0;/*from w w w . ja va 2 s. c o m*/ HttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); String postUrl = FEConstants.SERVER_POST_HANDLER + "?id=" + AuthMediaWikiIdHTTP.authorisedUser + "&ps=" + AuthMediaWikiIdHTTP.userPassword; HttpPost httppost = new HttpPost(postUrl); System.out.println(postUrl); MultipartEntity mpEntity = new MultipartEntity(); ContentBody cbFile = new FileBody(file, "json"); // name must be "uploadfile". this is same on the server side. mpEntity.addPart(FEConstants.SERVER_UPLOAD_FILE_NAME, cbFile); httppost.setEntity(mpEntity); System.out.println("executing request " + httppost.getRequestLine()); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); System.out.println(response.getStatusLine()); if (response.getStatusLine().toString().contains("502 Bad Gateway")) { status.add("Looks server is down."); } else { if (resEntity != null) { status.add(EntityUtils.toString(resEntity)); System.out.println(status.get(i)); i++; } if (resEntity != null) { resEntity.consumeContent(); } } httpclient.getConnectionManager().shutdown(); //String status = "Upload Success!"; return status; }
From source file:outfox.dict.contest.util.FileUtils.java
/** * ?NOSurl//from w ww . jav a 2 s. c o m * @param bytes * @return */ public static String uploadFile2Nos(byte[] bytes) { if (bytes == null) { return null; } HttpResponse response = null; String result = null; try { FileBody bin = new FileBody( FileUtils.getFileFromBytes(bytes, "tmpfile/file-" + System.currentTimeMillis())); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("file", bin); reqEntity.addPart("video", new StringBody("true", Charset.forName("UTF-8"))); // reqEntity.addPart("contentType", new StringBody("audio/mpeg", Charset.forName("UTF-8"))); response = HttpToolKit.getInstance().doPost(ContestConsts.NOS_UPLOAD_Interface, reqEntity); if (response != null) { String jsonString = EntityUtils.toString(response.getEntity()); JSONObject json = JSON.parseObject(jsonString); if ("success".equals(json.getString("msg"))) { return json.getString("url"); } } } catch (Exception e) { LOG.error("FileUtils.uploadFile2Nos(bytes) error...", e); } finally { HttpToolKit.closeQuiet(response); } return result; }
From source file:eu.prestoprime.p4gui.connection.AdminConnection.java
public static boolean restoreFromLTO(P4Service service, String from, String to) { try {//from ww w . j a v a 2 s .c o m String path = service.getURL() + "/admin/restore"; HttpRequestBase request = new HttpPost(path); MultipartEntity part = new MultipartEntity(); part.addPart("from", new StringBody(from)); part.addPart("to", new StringBody(to)); ((HttpPost) request).setEntity(part); P4HttpClient client = new P4HttpClient(service.getUserID()); HttpEntity entity = client.executeRequest(request).getEntity(); if (entity != null) { BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent())); String line; if ((line = reader.readLine()) != null) { if (line.equals("Error")) { return false; } else { return true; } } } } catch (Exception e) { e.printStackTrace(); } return false; }
From source file:fr.liglab.adele.cilia.workbench.restmonitoring.utils.http.HttpHelper.java
public static void post(PlatformID platformID, String path, String paramName, InputStream data) throws CiliaException { String url = getURL(platformID, path); HttpPost httppost = new HttpPost(url); MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); InputStreamBody bin = new InputStreamBody(data, paramName); reqEntity.addPart(paramName, bin); httppost.setEntity(reqEntity);/*w w w .ja va2 s. co m*/ // HTTP request HttpClient httpClient = getClient(); try { httpClient.execute(httppost, new BasicResponseHandler()); httpClient.getConnectionManager().shutdown(); } catch (Exception e) { httpClient.getConnectionManager().shutdown(); throw new CiliaException("can't perform HTTP PUT request", e); } }
From source file:org.cmuchimps.gort.modules.webinfoservice.AppEngineUpload.java
private static String uploadBlobstoreDataNoRetry(String url, String filename, String mime, byte[] data) { if (url == null || url.length() <= 0) { return null; }/*from w w w. j a va 2 s . co m*/ if (data == null || data.length <= 0) { return null; } HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); entity.addPart("data", new ByteArrayBody(data, mime, filename)); httpPost.setEntity(entity); try { HttpResponse response = httpClient.execute(httpPost); System.out.println("Blob upload status code: " + response.getStatusLine().getStatusCode()); /* //http://grinder.sourceforge.net/g3/script-javadoc/HTTPClient/HTTPResponse.html // 2xx - success if (response.getStatusLine().getStatusCode() / 100 != 2) { return null; } */ InputStreamReader isr = new InputStreamReader(response.getEntity().getContent()); BufferedReader br = new BufferedReader(isr); String blobKey = br.readLine(); blobKey = (blobKey != null) ? blobKey.trim() : null; br.close(); isr.close(); if (blobKey != null && blobKey.length() > 0) { return String.format("%s%s", MTURKSERVER_BLOB_DOWNLOAD_URL, blobKey); } else { return null; } } catch (ClientProtocolException e) { e.printStackTrace(); return null; } catch (IOException e) { e.printStackTrace(); return null; } }