List of usage examples for org.apache.http.entity.mime MultipartEntity MultipartEntity
public MultipartEntity()
From source file:ch.tatool.app.export.ServerDataExporter.java
private HttpEntity getHttpEntity(Module module, int fromSessionIndex, String filename, File tmpFile) { // we use a multipart entity to send over the files MultipartEntity entity = new MultipartEntity(); // get tatool online information for module Map<String, String> moduleProperties = module.getModuleProperties(); String subjectCode = moduleProperties.get(Module.PROPERTY_MODULE_CODE); if (subjectCode == null || subjectCode.isEmpty()) { subjectCode = module.getUserAccount().getName(); }//w ww. j av a2 s . co m String moduleID = moduleProperties.get(Module.PROPERTY_MODULE_ID); // InputStreamBody does not provide a content length (-1), so the server complains about the request length not // being defined. FileBody does not allow setting the name (which is different from the temp file name // Easiest solution: subclass of FileBody that allows overwriting the filename with a new one FileBodyExt fileBody = new FileBodyExt(tmpFile); fileBody.setFilename(filename); entity.addPart("file", fileBody); // add some additional data try { Charset utf8CharSet = Charset.forName("UTF-8"); entity.addPart("fromSessionIndex", new StringBody(String.valueOf(fromSessionIndex), utf8CharSet)); entity.addPart("subjectCode", new StringBody(subjectCode, utf8CharSet)); entity.addPart("moduleID", new StringBody(moduleID, utf8CharSet)); } catch (UnsupportedEncodingException e) { // should not happen logger.error("Unable to set write form parts", e); } catch (IllegalArgumentException e) { // should not happen logger.error("Missing settings for tatool online", e); return null; } return entity; }
From source file:outfox.dict.contest.util.FileUtils.java
/** * ?NOSurl/*www . j ava 2 s . c o m*/ * tongkn * @param bytes * @return */ public static String uploadFile2Nos(byte[] bytes, String fileName) throws Exception { if (bytes == null) { return null; } HttpResponse response = null; String result = null; try { //web ?? String filedir = "tmpfile"; File dir = new File(filedir); if (!dir.exists()) { dir.mkdir(); } // FileBody bin = new FileBody(FileUtils.getFileFromBytes( // bytes, filedir +"/file-"+ System.currentTimeMillis()+"-"+fileName)); //ByteArrayBody ByteArrayBody bin = new ByteArrayBody(bytes, fileName); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("file", bin); reqEntity.addPart("video", new StringBody("false", 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); throw new Exception(); } finally { HttpToolKit.closeQuiet(response); } return result; }
From source file:com.ibm.watson.developer_cloud.document_conversion.v1.helpers.DocumentHelper.java
/** * Uploads the document to the store with the given media type * /*from ww w . j av a 2 s. co m*/ * POST /v1/documents. * * @param document the document to be uploaded * @param mediaType the Internet media type for the file * @return Document * @see DocumentConversion#uploadDocument(File, String) */ public Document uploadDocument(final File document, final String mediaType) { if (mediaType == null || mediaType.isEmpty()) throw new IllegalArgumentException("media type cannot be null or empty"); if (!ConversionUtils.isValidMediaType(mediaType)) throw new IllegalArgumentException("file with the given media type is not supported"); if (document == null || !document.exists()) throw new IllegalArgumentException("document cannot be null and must exist"); try { MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("file", new FileBody(document, mediaType)); HttpRequestBase request = Request.Post(ConfigConstants.DOCUMENTS_PATH).withEntity(reqEntity).build(); HttpResponse response = docConversionService.execute(request); String documentAsJson = ResponseUtil.getString(response); Document doc = GsonSingleton.getGson().fromJson(documentAsJson, Document.class); return doc; } catch (IOException e) { throw new RuntimeException(e); } }
From source file:com.ushahidi.android.app.net.ReportsHttpClient.java
/** * Upload files to server 0 - success, 1 - missing parameter, 2 - invalid * parameter, 3 - post failed, 5 - access denied, 6 - access limited, 7 - no * data, 8 - api disabled, 9 - no task found, 10 - json is wrong *//* ww w . j a v a2 s .co m*/ public boolean PostFileUpload(String URL, HashMap<String, String> params) throws IOException { log("PostFileUpload(): upload file to server."); apiUtils.updateDomain(); entity = new MultipartEntity(); // Dipo Fix try { // wrap try around because this constructor can throw Error final HttpPost httpost = new HttpPost(URL); if (params != null) { entity.addPart("task", new StringBody(params.get("task"))); entity.addPart("incident_title", new StringBody(params.get("incident_title"), Charset.forName("UTF-8"))); entity.addPart("incident_description", new StringBody(params.get("incident_description"), Charset.forName("UTF-8"))); entity.addPart("incident_date", new StringBody(params.get("incident_date"))); entity.addPart("incident_hour", new StringBody(params.get("incident_hour"))); entity.addPart("incident_minute", new StringBody(params.get("incident_minute"))); entity.addPart("incident_ampm", new StringBody(params.get("incident_ampm"))); entity.addPart("incident_category", new StringBody(params.get("incident_category"))); entity.addPart("latitude", new StringBody(params.get("latitude"))); entity.addPart("longitude", new StringBody(params.get("longitude"))); entity.addPart("location_name", new StringBody(params.get("location_name"), Charset.forName("UTF-8"))); entity.addPart("person_first", new StringBody(params.get("person_first"), Charset.forName("UTF-8"))); entity.addPart("person_last", new StringBody(params.get("person_last"), Charset.forName("UTF-8"))); entity.addPart("person_email", new StringBody(params.get("person_email"), Charset.forName("UTF-8"))); if (params.get("filename") != null) { if (!TextUtils.isEmpty(params.get("filename"))) { String filenames[] = params.get("filename").split(","); log("filenames " + ImageManager.getPhotoPath(context, filenames[0])); for (int i = 0; i < filenames.length; i++) { if (ImageManager.getPhotoPath(context, filenames[i]) != null) { File file = new File(ImageManager.getPhotoPath(context, filenames[i])); if (file.exists()) { entity.addPart("incident_photo[]", new FileBody(file)); } } } } } // NEED THIS NOW TO FIX ERROR 417 httpost.getParams().setBooleanParameter("http.protocol.expect-continue", false); httpost.setEntity(entity); HttpResponse response = httpClient.execute(httpost); Preferences.httpRunning = false; HttpEntity respEntity = response.getEntity(); if (respEntity != null) { InputStream serverInput = respEntity.getContent(); int status = ApiUtils.extractPayloadJSON(GetText(serverInput)); if (status == 0) { return true; } return false; } } } catch (MalformedURLException ex) { log("PostFileUpload(): MalformedURLException", ex); return false; // fall through and return false } catch (IllegalArgumentException ex) { log("IllegalArgumentException", ex); // invalid URI return false; } catch (ConnectTimeoutException ex) { //connection timeout log("ConnectionTimeoutException"); return false; } catch (IOException e) { log("IOException", e); // timeout return false; } return false; }
From source file:bluej.collect.DataCollectorImpl.java
/** * Submits an event and adds a source location. This should be used if it is not * known whether the class is in the project, or whether it might be from a library * (e.g. java.io.*) or wherever./* ww w . j av a 2 s . c o m*/ * * @param project * @param eventName * @param mpe You can pass null if you have no other data to give * @param classSourceName * @param lineNumber */ private static void submitDebuggerEventWithLocation(Project project, EventName eventName, MultipartEntity mpe, SourceLocation[] stack) { if (mpe == null) { mpe = new MultipartEntity(); } DataCollectorImpl.addStackTrace(mpe, "event[stack]", stack); submitEvent(project, null, eventName, new PlainEvent(mpe)); }
From source file:foam.littlej.android.app.net.ReportsHttpClient.java
/** * Upload files to server 0 - success, 1 - missing parameter, 2 - invalid * parameter, 3 - post failed, 5 - access denied, 6 - access limited, 7 - no * data, 8 - api disabled, 9 - no task found, 10 - json is wrong */// w ww . j a va2 s . c o m public boolean PostFileUpload(String URL, HashMap<String, String> params) throws IOException { log("PostFileUpload(): upload file to server."); apiUtils.updateDomain(); entity = new MultipartEntity(); // Dipo Fix try { // wrap try around because this constructor can throw Error final HttpPost httpost = new HttpPost(URL); if (params != null) { for (Entry<String, String> en : params.entrySet()) { String key = en.getKey(); if (key == null || "".equals(key)) { continue; } String val = en.getValue(); if (!"filename".equals(key)) { entity.addPart(key, new StringBody(val, Charset.forName("UTF-8"))); continue; } if (!TextUtils.isEmpty(val)) { String filenames[] = val.split(","); log("filenames " + ImageManager.getPhotoPath(context, filenames[0])); for (int i = 0; i < filenames.length; i++) { if (ImageManager.getPhotoPath(context, filenames[i]) != null) { File file = new File(ImageManager.getPhotoPath(context, filenames[i])); if (file.exists()) { entity.addPart("incident_photo[]", new FileBody(file)); } } } } } // NEED THIS NOW TO FIX ERROR 417 httpost.getParams().setBooleanParameter("http.protocol.expect-continue", false); httpost.setEntity(entity); HttpResponse response = httpClient.execute(httpost); Preferences.httpRunning = false; HttpEntity respEntity = response.getEntity(); if (respEntity != null) { UshahidiApiResponse resp = GsonHelper.fromStream(respEntity.getContent(), UshahidiApiResponse.class); return resp.getErrorCode() == 0; } } } catch (MalformedURLException ex) { log("PostFileUpload(): MalformedURLException", ex); return false; // fall through and return false } catch (IllegalArgumentException ex) { log("IllegalArgumentException", ex); // invalid URI return false; } catch (ConnectTimeoutException ex) { //connection timeout log("ConnectionTimeoutException"); return false; } catch (SocketTimeoutException ex) { log("SocketTimeoutException"); } catch (IOException e) { log("IOException", e); // timeout return false; } return false; }
From source file:com.ushahidi.android.app.net.CheckinHttpClient.java
/** * Upload files to server 0 - success, 1 - missing parameter, 2 - invalid * parameter, 3 - post failed, 5 - access denied, 6 - access limited, 7 - no * data, 8 - api disabled, 9 - no task found, 10 - json is wrong *//*from ww w. j av a2 s. c o m*/ public boolean PostFileUpload(String URL, HashMap<String, String> params) throws IOException { log("PostFileUpload(): upload file to server."); apiUtils.updateDomain(); entity = new MultipartEntity(); // Dipo Fix try { // wrap try around because this constructor can throw Error final HttpPost httpost = new HttpPost(URL); if (params != null) { entity.addPart("task", new StringBody(params.get("task"))); entity.addPart("action", new StringBody(params.get("action"))); entity.addPart("mobileid", new StringBody(params.get("mobileid"))); entity.addPart("message", new StringBody(params.get("message"), Charset.forName("UTF-8"))); entity.addPart("lat", new StringBody(params.get("lat"))); entity.addPart("lon", new StringBody(params.get("lon"))); entity.addPart("firstname", new StringBody(params.get("firstname"), Charset.forName("UTF-8"))); entity.addPart("lastname", new StringBody(params.get("lastname"), Charset.forName("UTF-8"))); entity.addPart("email", new StringBody(params.get("email"), Charset.forName("UTF-8"))); if (params.get("filename") != null) { if (!TextUtils.isEmpty(params.get("filename"))) { File file = new File(ImageManager.getPhotoPath(context, params.get("filename"))); if (file != null) { if (file.exists()) { entity.addPart("photo", new FileBody(file)); } } } } // NEED THIS NOW TO FIX ERROR 417 httpost.getParams().setBooleanParameter("http.protocol.expect-continue", false); httpost.setEntity(entity); HttpResponse response = httpClient.execute(httpost); Preferences.httpRunning = false; HttpEntity respEntity = response.getEntity(); if (respEntity != null) { InputStream serverInput = respEntity.getContent(); if (serverInput != null) { //TODO:: get the status confirmation code to work //int status = ApiUtils //.extractPayloadJSON(GetText(serverInput)); return true; } return false; } } } catch (MalformedURLException ex) { log("PostFileUpload(): MalformedURLException", ex); return false; // fall through and return false } catch (IllegalArgumentException ex) { log("IllegalArgumentException", ex); // invalid URI return false; } catch (IOException e) { log("IOException", e); // timeout return false; } return false; }
From source file:dk.i2m.drupal.resource.FileResource.java
private MultipartEntity getMultipartEntity(File file, String fileName) throws MimeTypeException, IOException { TikaConfig tikaConfig = TikaConfig.getDefaultConfig(); MimeTypes mimeTypes = tikaConfig.getMimeRepository(); byte[] buf = IOUtils.toByteArray(new FileInputStream(file)); InputStream in = new ByteArrayInputStream(buf); MediaType mediaType = mimeTypes.detect(in, new Metadata()); MimeType mimeType = mimeTypes.forName(mediaType.toString()); MultipartEntity multipartEntity = new MultipartEntity(); int x = 0;/* w ww . j a va 2 s. c o m*/ FileBody fb = new FileBody(file, fileName + mimeType.getExtension(), mimeType.getName(), Consts.UTF_8.name()); multipartEntity.addPart("files[" + x + "]", fb); return multipartEntity; }
From source file:com.networkmanagerapp.SettingBackgroundUploader.java
/** * Performs the file upload in the background * @throws FileNotFoundException, IOException, both caught internally. * @param arg0 The intent to run in the background. *//*from w w w .ja v a 2 s . c o m*/ @Override protected void onHandleIntent(Intent arg0) { configFilePath = arg0.getStringExtra("CONFIG_FILE_PATH"); key = arg0.getStringExtra("KEY"); value = arg0.getStringExtra("VALUE"); mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); showNotification(); try { fos = NetworkManagerMainActivity.getInstance().openFileOutput(this.configFilePath, Context.MODE_PRIVATE); String nameLine = "Name" + " = " + "\"" + this.key + "\"\n"; String valueLine = "Value" + " = " + "\"" + this.value + "\""; fos.write(nameLine.getBytes()); fos.write(valueLine.getBytes()); fos.close(); String password = PreferenceManager.getDefaultSharedPreferences(this).getString("password_preference", ""); File f = new File(NetworkManagerMainActivity.getInstance().getFilesDir() + "/" + this.configFilePath); HttpHost targetHost = new HttpHost( PreferenceManager.getDefaultSharedPreferences(this).getString("ip_preference", "192.168.1.1"), 1080, "http"); DefaultHttpClient client = new DefaultHttpClient(); client.getCredentialsProvider().setCredentials( new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials("root", password)); HttpPost httpPost = new HttpPost("http://" + PreferenceManager.getDefaultSharedPreferences(NetworkManagerMainActivity.getInstance()) .getString("ip_preference", "192.168.1.1") + ":1080/cgi-bin/upload.php"); MultipartEntity entity = new MultipartEntity(); entity.addPart("file", new FileBody(f)); httpPost.setEntity(entity); HttpResponse response = client.execute(httpPost); Log.d("upload", response.getStatusLine().toString()); } catch (FileNotFoundException e) { Log.e("NETWORK_MANAGER_XU_FNFE", e.getLocalizedMessage()); } catch (IOException e) { Log.e("NETWORK_MANAGER_XU_IOE", e.getLocalizedMessage()); } finally { mNM.cancel(R.string.upload_service_started); stopSelf(); } }
From source file:com.ibm.watson.developer_cloud.document_conversion.v1.helpers.ConvertDocumentHelper.java
/** * Synchronously converts a new document without persistence * POST /v1/convert_document./* w w w . j a v a2s .c o m*/ * * @param document The file to convert * @param mediaType Internet media type for the file * @param conversionTarget The conversion target to use * @return Converted document in the specified format * @see DocumentConversion#convertDocument(File, String, ConversionTarget) */ public InputStream convertDocument(final File document, String mediaType, final ConversionTarget conversionTarget) { if (mediaType == null || mediaType.isEmpty()) throw new IllegalArgumentException("media type cannot be null or empty"); if (!ConversionUtils.isValidMediaType(mediaType)) throw new IllegalArgumentException("file with the given media type is not supported"); if (document == null || !document.exists()) throw new IllegalArgumentException("document can not be null and must exist"); if (conversionTarget == null) throw new IllegalArgumentException("conversion target can not be null"); try { MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("file", new FileBody(document, mediaType)); JsonObject configRequestJson = new JsonObject(); configRequestJson.addProperty("conversion_target", conversionTarget.toString()); String json = configRequestJson.toString(); reqEntity.addPart("config", new StringBody(json, MediaType.APPLICATION_JSON, Charset.forName("UTF-8"))); HttpRequestBase request = Request.Post(ConfigConstants.CONVERT_DOCUMENT_PATH).withEntity(reqEntity) .build(); HttpResponse response = docConversionService.execute(request); InputStream is = ResponseUtil.getInputStream(response); return is; } catch (IOException e) { throw new RuntimeException(e); } }