List of usage examples for org.apache.http.entity.mime MultipartEntity addPart
public void addPart(final String name, final ContentBody contentBody)
From source file:nl.sogeti.android.gpstracker.actions.ShareTrack.java
/** * POST a (GPX) file to the 0.6 API of the OpenStreetMap.org website publishing * this track to the public./* www . java2s . com*/ * * @param fileUri * @param contentType */ private void sendToOsm(Uri fileUri, Uri trackUri, String contentType) { String username = PreferenceManager.getDefaultSharedPreferences(this).getString(Constants.OSM_USERNAME, ""); String password = PreferenceManager.getDefaultSharedPreferences(this).getString(Constants.OSM_PASSWORD, ""); String visibility = PreferenceManager.getDefaultSharedPreferences(this).getString(Constants.OSM_VISIBILITY, "trackable"); File gpxFile = new File(fileUri.getEncodedPath()); String hostname = getString(R.string.osm_post_host); Integer port = new Integer(getString(R.string.osm_post_port)); HttpHost targetHost = new HttpHost(hostname, port, "http"); DefaultHttpClient httpclient = new DefaultHttpClient(); HttpResponse response = null; String responseText = ""; int statusCode = 0; Cursor metaData = null; String sources = null; try { metaData = this.getContentResolver().query(Uri.withAppendedPath(trackUri, "metadata"), new String[] { MetaData.VALUE }, MetaData.KEY + " = ? ", new String[] { Constants.DATASOURCES_KEY }, null); if (metaData.moveToFirst()) { sources = metaData.getString(0); } if (sources != null && sources.contains(LoggerMap.GOOGLE_PROVIDER)) { throw new IOException("Unable to upload track with materials derived from Google Maps."); } // The POST to the create node HttpPost method = new HttpPost(getString(R.string.osm_post_context)); // Preemptive basic auth on the first request method.addHeader( new BasicScheme().authenticate(new UsernamePasswordCredentials(username, password), method)); // Build the multipart body with the upload data MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); entity.addPart("file", new FileBody(gpxFile)); entity.addPart("description", new StringBody(queryForTrackName())); entity.addPart("tags", new StringBody(queryForNotes())); entity.addPart("visibility", new StringBody(visibility)); method.setEntity(entity); // Execute the POST to OpenStreetMap response = httpclient.execute(targetHost, method); // Read the response statusCode = response.getStatusLine().getStatusCode(); InputStream stream = response.getEntity().getContent(); responseText = convertStreamToString(stream); } catch (IOException e) { Log.e(TAG, "Failed to upload to " + targetHost.getHostName() + "Response: " + responseText, e); responseText = getString(R.string.osm_failed) + e.getLocalizedMessage(); Toast toast = Toast.makeText(this, responseText, Toast.LENGTH_LONG); toast.show(); } catch (AuthenticationException e) { Log.e(TAG, "Failed to upload to " + targetHost.getHostName() + "Response: " + responseText, e); responseText = getString(R.string.osm_failed) + e.getLocalizedMessage(); Toast toast = Toast.makeText(this, responseText, Toast.LENGTH_LONG); toast.show(); } finally { if (metaData != null) { metaData.close(); } } if (statusCode == 200) { Log.i(TAG, responseText); CharSequence text = getString(R.string.osm_success) + responseText; Toast toast = Toast.makeText(this, text, Toast.LENGTH_LONG); toast.show(); } else { Log.e(TAG, "Failed to upload to error code " + statusCode + " " + responseText); CharSequence text = getString(R.string.osm_failed) + responseText; Toast toast = Toast.makeText(this, text, Toast.LENGTH_LONG); toast.show(); } }
From source file:com.globalsight.everest.tda.TdaHelper.java
public void leverageTDA(TDATM tda, File needLeverageXliffFile, String storePath, String fileName, String sourceLocal, String targetLocal) { int timeoutConnection = 15000; HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters); String loginUrl = new String(); if (tda.getHostName().indexOf("http://") < 0) { loginUrl = "http://" + tda.getHostName(); } else {/*from w w w . j a va 2s . c o m*/ loginUrl = tda.getHostName(); } if (tda.getHostName().lastIndexOf("/") < (tda.getHostName().length() - 1)) { loginUrl = loginUrl + "/"; } try { // Judge if the TDA server has the source and target language HttpGet lanGet = new HttpGet(loginUrl + "lang/" + sourceLocal.toLowerCase() + ".json?auth_username=" + tda.getUserName() + "&auth_password=" + tda.getPassword() + "&auth_app_key=" + appKey); HttpResponse lanRes = httpclient.execute(lanGet); StatusLine stl = lanRes.getStatusLine(); if (stl.getStatusCode() != 200) { loggerTDAInfo(stl, sourceLocal.toString()); return; } lanGet.abort(); HttpGet lanGet2 = new HttpGet(loginUrl + "lang/" + targetLocal.toLowerCase() + ".json?auth_username=" + tda.getUserName() + "&auth_password=" + tda.getPassword() + "&auth_app_key=" + appKey); HttpResponse lanRes2 = httpclient.execute(lanGet2); stl = lanRes2.getStatusLine(); if (stl.getStatusCode() != 200) { loggerTDAInfo(stl, targetLocal.toString()); return; } lanGet2.abort(); HttpPost httpPost = new HttpPost(loginUrl + "leverage.json?action=create"); FileBody fileBody = new FileBody(needLeverageXliffFile); StringBody nameBody = new StringBody(tda.getUserName()); StringBody passwordBody = new StringBody(tda.getPassword()); StringBody appKeyBody = new StringBody(appKey); StringBody srcBody = new StringBody(sourceLocal.toLowerCase()); StringBody trBody = new StringBody(targetLocal.toLowerCase()); StringBody confirmBody = new StringBody("true"); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("file", fileBody); reqEntity.addPart("auth_username", nameBody); reqEntity.addPart("auth_password", passwordBody); reqEntity.addPart("auth_app_key", appKeyBody); reqEntity.addPart("source_lang", srcBody); reqEntity.addPart("target_lang", trBody); reqEntity.addPart("confirm", confirmBody); httpPost.setEntity(reqEntity); HttpResponse response = httpclient.execute(httpPost); HttpEntity entity = response.getEntity(); StatusLine sl = response.getStatusLine(); if (sl.getStatusCode() != 201) { loggerTDAInfo(stl, null); return; } JSONObject jso = new JSONObject(EntityUtils.toString(entity)); JSONArray lev = jso.getJSONArray("leverage"); httpPost.abort(); if (lev.length() > 0) { JSONObject obj = lev.getJSONObject(0); String states = obj.getString("state"); // waiting the "not ready" state becoming "ready" state Thread.sleep(3 * 1000); int i = 0; if (!states.equals("ready")) { boolean flag = true; while (flag) { if (i > 40) { s_logger.info("Get TDA job status overtime. TDA job id:" + obj.getInt("id")); s_logger.info("TDA leveraging waited time:" + (40 * 3) + " seconds!"); return; } i++; HttpGet httpget = new HttpGet(loginUrl + "leverage/" + obj.getInt("id") + ".json?auth_username=" + tda.getUserName() + "&auth_password=" + tda.getPassword() + "&auth_app_key=" + appKey); response = httpclient.execute(httpget); StatusLine status = response.getStatusLine(); if (status.getStatusCode() != 200) { s_logger.info( "Get TDA job status error, please confirm the TDA url is correct or not! TDA job id:" + obj.getInt("id")); return; } entity = response.getEntity(); JSONObject getObj = new JSONObject(EntityUtils.toString(entity)); if (getObj.getJSONObject("leverage").getString("state").equals("ready")) { s_logger.info("TDA leveraging waited time:" + (i * 3) + " seconds!"); flag = false; } else { Thread.sleep(3 * 1000); } httpget.abort(); } } HttpPost httpPost2 = new HttpPost(loginUrl + "leverage/" + obj.getInt("id") + ".json?action=approve&auth_username=" + tda.getUserName() + "&auth_password=" + tda.getPassword() + "&auth_app_key=" + appKey); response = httpclient.execute(httpPost2); entity = response.getEntity(); httpPost2.abort(); HttpGet httpGet = new HttpGet(loginUrl + "leverage/" + obj.getString("id") + "/result.xlf.zip?auth_username=" + tda.getUserName() + "&auth_password=" + tda.getPassword() + "&auth_app_key=" + appKey); HttpResponse response2 = httpclient.execute(httpGet); entity = response2.getEntity(); ZipInputStream fs = new ZipInputStream(entity.getContent()); int BUFFER = 2048; byte data[] = new byte[BUFFER]; int count; while (fs.getNextEntry() != null) { FileOutputStream fos = new FileOutputStream(storePath + File.separator + fileName); BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER); while ((count = fs.read(data, 0, BUFFER)) != -1) { dest.write(data, 0, count); } dest.flush(); dest.close(); } httpGet.abort(); s_logger.info("Leverage TDA TM success, TDA id:" + obj.getString("id")); } } catch (Exception e) { s_logger.error("TDA leverage process error:" + e.getMessage()); } }
From source file:org.bungeni.ext.integration.bungeniportal.BungeniAppConnector.java
/** * Login to Bungeni via the OAuth route// www. ja v a 2 s.com * @param oauthForwardURL * @param oauthCameFromURL * @return * @throws UnsupportedEncodingException * @throws IOException */ private String oauthAuthenticate(String oauthForwardURL, String oauthCameFromURL) throws UnsupportedEncodingException, IOException { final HttpPost post = new HttpPost(oauthForwardURL); final HashMap<String, ContentBody> nameValuePairs = new HashMap<String, ContentBody>(); nameValuePairs.put("login", new StringBody(this.getUser())); nameValuePairs.put("password", new StringBody(this.getPassword())); nameValuePairs.put("camefrom", new StringBody(oauthCameFromURL)); nameValuePairs.put("actions.login", new StringBody("login")); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); Set<String> fields = nameValuePairs.keySet(); for (String fieldName : fields) { entity.addPart(fieldName, nameValuePairs.get(fieldName)); } HttpContext context = new BasicHttpContext(); post.setEntity(entity); HttpResponse oauthResponse = client.execute(post, context); // if the OAuth page retrieval failed throw an exception if (oauthResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new IOException(oauthResponse.getStatusLine().toString()); } String currentUrl = getRequestEndContextURL(context); // consume the response ResponseHandler<String> responseHandler = new BasicResponseHandler(); String sBody = responseHandler.handleResponse(oauthResponse); consumeContent(oauthResponse.getEntity()); return currentUrl; }
From source file:code.google.restclient.client.HitterClient.java
private MultipartEntity getMultipartEntity(ViewRequest req) throws RCException { MultipartEntity reqEntity = new MultipartEntity(); Map<String, String> params = req.getParams(); String paramValue = null;// ww w . j a va 2 s .c om StringBody stringBody = null; try { for (String paramName : params.keySet()) { paramValue = params.get(paramName); stringBody = new StringBody(paramValue, Charset.forName(RCConstants.DEFAULT_CHARSET)); reqEntity.addPart(paramName, stringBody); } String fileParamName = req.getFileParamName(); File selectedFile = new File(req.getFilePath()); if (selectedFile.exists() && !RCUtil.isEmpty(fileParamName)) { String mimeType = MimeTypeUtil.getMimeType(req.getFilePath()); FileBody fileBody = new FileBody(selectedFile, mimeType); reqEntity.addPart(fileParamName, fileBody); } } catch (UnsupportedEncodingException e) { throw new RCException( "getMultipartEntity(): Could not prepare multipart entity due to unsupported encoding", e); } return reqEntity; }
From source file:androhashcheck.MainFrame.java
/** * Upolads file on server for given path as a String. * * @param fileName// w w w .ja va 2s. co m */ public void upoloadFile(String fileName) { try { String url = ConfigClass.serverURL + "/api/upload_task"; URL obj = new URL(url); HttpURLConnection connection = (HttpURLConnection) obj.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); FileBody fileBody = new FileBody(new File(fileName)); MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.STRICT); multipartEntity.addPart("file", fileBody); connection.setRequestProperty("Content-Type", multipartEntity.getContentType().getValue()); connection.setRequestProperty("token", ConfigClass.token); try (OutputStream out = connection.getOutputStream()) { multipartEntity.writeTo(out); } int status = connection.getResponseCode(); System.out.println(status); System.out.println(connection.getResponseMessage()); StringBuilder response; try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { String inputLine; response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } } updateStatus(fileName + " done uploading, server response: " + response); if (status == 200) { shouldCheckTasks = true; String taskId = response.toString().replace("}", "").split(":")[1].trim(); TaskObject newTask = new TaskObject(); newTask.setFileName(fileName); newTask.setTaskId(taskId); taskList.add(newTask); } } catch (Exception ex) { updateStatus("error with uploading " + fileName); Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:eu.trentorise.opendata.jackan.test.ckan.ExperimentalCkanClient.java
/** * Uploads a file using file storage api, which I think is deprecated. As of * Aug 2015, coesn't work neither with demo.ckan.org nor dati.trentino * * Adapted from/*from www . java2 s . co m*/ * https://github.com/Ontodia/openrefine-ckan-storage-extension/blob/c99de78fd605c4754197668c9396cffd1f9a0267/src/org/deri/orefine/ckan/StorageApiProxy.java#L34 */ public String uploadFile(String fileContent, String fileLabel) { HttpResponse formFields = null; try { String filekey = null; HttpClient client = new DefaultHttpClient(); // get the form fields required from ckan storage // notice if you put '3/' it gives not found :-/ String formUrl = getCatalogUrl() + "/api/storage/auth/form/file/" + fileLabel; HttpGet getFormFields = new HttpGet(formUrl); getFormFields.setHeader("Authorization", getCkanToken()); formFields = client.execute(getFormFields); HttpEntity entity = formFields.getEntity(); if (entity != null) { ByteArrayOutputStream os = new ByteArrayOutputStream(); entity.writeTo(os); //now parse JSON //JSONObject obj = new JSONObject(os.toString()); JsonNode obj = new ObjectMapper().readTree(os.toString()); //post the file now String uploadFileUrl = getCatalogUrl() + obj.get("action").asText(); HttpPost postFile = new HttpPost(uploadFileUrl); postFile.setHeader("Authorization", getCkanToken()); MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.STRICT); //JSONArray fields = obj.getJSONArray("fields"); Iterator<JsonNode> fields = obj.get("fields").elements(); while (fields.hasNext()) { JsonNode fieldObj = fields.next(); //JSONObject fieldObj = fields.getJSONObject(i); String fieldName = fieldObj.get("name").asText(); String fieldValue = fieldObj.get("value").asText(); if (fieldName.equals("key")) { filekey = fieldValue; } mpEntity.addPart(fieldName, new StringBody(fieldValue, "multipart/form-data", Charset.forName("UTF-8"))); } /* for (int i = 0; i < fields.length(); i++) { //JSONObject fieldObj = fields.getJSONObject(i); JSONObject fieldObj = fields.getJSONObject(i); String fieldName = fieldObj.getString("name"); String fieldValue = fieldObj.getString("value"); if (fieldName.equals("key")) { filekey = fieldValue; } mpEntity.addPart(fieldName, new StringBody(fieldValue, "multipart/form-data", Charset.forName("UTF-8"))); } */ // assure that we got the file key if (filekey == null) { throw new RuntimeException( "failed to get the file key from CKAN storage form API. the response from " + formUrl + " was: " + os.toString()); } //the file should be the last part //hack... StringBody didn't work with large files mpEntity.addPart("file", new ByteArrayBody(fileContent.getBytes(Charset.forName("UTF-8")), "multipart/form-data", fileLabel)); postFile.setEntity(mpEntity); HttpResponse fileUploadResponse = client.execute(postFile); //check if the response status code was in the 200 range if (fileUploadResponse.getStatusLine().getStatusCode() < 200 || fileUploadResponse.getStatusLine().getStatusCode() >= 300) { throw new RuntimeException("failed to add the file to CKAN storage. response status line from " + uploadFileUrl + " was: " + fileUploadResponse.getStatusLine()); } return getCatalogUrl() + "/storage/f/" + filekey; //return CKAN_STORAGE_FILES_BASE_URI + filekey; } throw new RuntimeException("failed to get form details from CKAN storage. response line was: " + formFields.getStatusLine()); } catch (IOException ioe) { throw new RuntimeException("failed to upload file to CKAN Storage ", ioe); } }
From source file:com.sat.sonata.MenuActivity.java
@Override public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection. switch (item.getItemId()) { case R.id.stop: Log.d("SITTING", "Inside stop case"); //stopService(new Intent(this, SonataService.class)); return true; case R.id.recognise: String imagePath = getIntent().getStringExtra("image"); getIntent().removeExtra("image"); Log.d("SITTING", imagePath); HttpPost postRequest = new HttpPost("http://129.31.195.224:8080/picUpload"); MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); try {// w w w. j av a2 s . c o m ByteArrayOutputStream bos = new ByteArrayOutputStream(); Bitmap bitmap; BitmapFactory.Options options = new BitmapFactory.Options(); options.inPreferredConfig = Bitmap.Config.ARGB_8888; bitmap = BitmapFactory.decodeFile(imagePath, options); bitmap.compress(Bitmap.CompressFormat.JPEG, 75, bos); byte[] data = bos.toByteArray(); ByteArrayBody bab = new ByteArrayBody(data, "music.jpg"); reqEntity.addPart("music", bab); postRequest.setEntity(reqEntity); HttpPost[] posts = new HttpPost[1]; posts[0] = postRequest; GetImageTask getImageTask = new GetImageTask(); getImageTask.execute(posts); } catch (Exception e) { Log.v("Exception in Image", "" + e); // reqEntity.addPart("picture", new StringBody("")); } default: return super.onOptionsItemSelected(item); } }
From source file:com.globalsight.everest.tda.TdaHelper.java
public String loginCheck(String hostName, String userName, String password) { int timeoutConnection = 8000; HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters); String loginUrl = new String(); String errorInfo = new String(); hostName = hostName.trim();// w w w . j a v a2 s . c om userName = userName.trim(); if (hostName.indexOf("http://") < 0) { loginUrl = "http://" + hostName; } else { loginUrl = hostName; } if (hostName.lastIndexOf("/") == (hostName.length() - 1)) { loginUrl = loginUrl + "auth_key.json?action=login"; } else { loginUrl = loginUrl + "/auth_key.json?action=login"; } try { HttpPost httpost = new HttpPost(loginUrl); MultipartEntity reqEntity = new MultipartEntity(); StringBody nameBody = new StringBody(userName); StringBody passwordBody = new StringBody(password); StringBody appKeyBody = new StringBody(appKey); reqEntity.addPart("auth_username", nameBody); reqEntity.addPart("auth_password", passwordBody); reqEntity.addPart("auth_app_key", appKeyBody); httpost.setEntity(reqEntity); HttpResponse response = httpclient.execute(httpost); StatusLine sl = response.getStatusLine(); if (sl.getStatusCode() == 404) { errorInfo = "The TDA URL is not correct."; } else if (sl.getStatusCode() == 401) { errorInfo = "The username and password given are not a valid TDA login."; } else if (sl.getStatusCode() == 201) { errorInfo = "ture"; } else { errorInfo = "The TDA configuration is not correct!"; } } catch (Exception e) { s_logger.info("Can not connect TDA server:" + e.getMessage()); errorInfo = "Can not connect TDA server."; } return errorInfo; }
From source file:ecblast.test.EcblastTest.java
public String atomAtomMappingSMI(String query, String type) throws FileNotFoundException, UnsupportedEncodingException, IOException { ClientConfig cc = new DefaultClientConfig(); cc.getClasses().add(MultiPartWriter.class); Client client = Client.create(cc);/*from www . j av a 2 s.com*/ String urlString = "http://localhost:8080/ecblast-rest/aam"; WebResource webResource = client.resource("http://localhost:8080/ecblast-rest/aam"); //String smi = "[O:9]=[C:8]([OH:10])[CH2:7][CH:5]([O:4][C:2](=[O:3])[CH2:1][CH:11]([OH:13])[CH3:12])[CH3:6].[H:30][OH:14]>>[H:30][O:4][C:2](=[O:3])[CH2:1][CH:11]([OH:13])[CH3:12].[O:9]=[C:8]([OH:10])[CH2:7][CH:5]([OH:14])[CH3:6]"; FormDataMultiPart form = new FormDataMultiPart(); switch (type) { case "SMI": form.field("q", query); form.field("Q", "SMI"); break; case "RXN": /*MultivaluedMapImpl values = new MultivaluedMapImpl(); values.add("q", new File(query)); values.add("Q", "RXN"); ClientResponse response = webResource.type(MediaType.).post(ClientResponse.class, values); return response.toString(); File attachment = new File(query); FileInputStream fis = null; fis = new FileInputStream(attachment); ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; try { for (int readNum; (readNum = fis.read(buf)) != -1;) { bos.write(buf, 0, readNum); //no doubt here is 0 } fis.close(); bos.close(); } catch (IOException ex) { try { fis.close(); bos.close(); } catch (IOException e) { return "ERROR"; } return "ERROR"; } byte[] bytes = bos.toByteArray(); FormDataBodyPart bodyPart = new FormDataBodyPart("q", new ByteArrayInputStream(bytes), MediaType.APPLICATION_OCTET_STREAM_TYPE); form.bodyPart(bodyPart); //form.field("q", bodyPart); //form.field* form.field("Q", "RXN", MediaType.MULTIPART_FORM_DATA_TYPE);*/ DefaultHttpClient client1; client1 = new DefaultHttpClient(); HttpPost postRequest = new HttpPost(urlString); MultipartEntity multiPartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); // FileBody queryFileBody = new FileBody(queryFile); multiPartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); //multiPartEntity.addPart("fileDescription", new StringBody(fileDescription != null ? fileDescription : "")); //multiPartEntity.addPart("fileName", new StringBody(fileName != null ? fileName : file.getName())); File file = new File(query); FileBody fileBody = new FileBody(file); //Prepare payload multiPartEntity.addPart("q", fileBody); multiPartEntity.addPart("Q", new StringBody("RXN", "text/plain", Charset.forName("UTF-8"))); //Set to request body postRequest.setEntity(multiPartEntity); //Send request HttpResponse response = client1.execute(postRequest); return response.toString(); } form.setMediaType(MediaType.MULTIPART_FORM_DATA_TYPE); ClientResponse responseJson = webResource.type(MediaType.MULTIPART_FORM_DATA).post(ClientResponse.class, form); return responseJson.toString(); }