List of usage examples for org.apache.http.entity.mime MultipartEntity addPart
public void addPart(final String name, final ContentBody contentBody)
From source file:org.linkdroid.PostJob.java
/** * Posts the data to our webhook.// w w w . j a va 2 s . c o m * * The HMAC field calculation notes: * <ol> * <li>The Extras.HMAC field is calculated from all the non Extras.STREAM * fields; this includes all the original bundle extra fields, plus the * linkdroid fields (e.g Extras.STREAM_MIME_TYPE, and including * Extras.STREAM_HMAC); the NONCE is NOT prepended to the input since it will * be somewhere in the data bundle.</li> * <li>The Extras.STREAM_HMAC field is calculated by digesting the concat of * the NONCE (first) and the actual binary data obtained from the * EXTRAS_STREAM uri; this STREAM_HMAC field (along with the other * Extras.STREAM_* fields) are added to the data bundle, which will also be * hmac'd.</li> * <li>If no hmac secret is set, then the NONCEs will not be set in the upload * </li> * </ol> * * @param contentResolver * @param webhook * @param data * @throws UnsupportedEncodingException * @throws IOException * @throws InvalidKeyException * @throws NoSuchAlgorithmException */ public static void execute(ContentResolver contentResolver, Bundle webhook, Bundle data) throws UnsupportedEncodingException, IOException, InvalidKeyException, NoSuchAlgorithmException { // Set constants that may be used in this method. final String secret = webhook.getString(WebhookColumns.SECRET); // This is the multipart form object that will contain all the data bundle // extras; it also will include the data of the extra stream and any other // extra linkdroid specific field required. MultipartEntity entity = new MultipartEntity(); // Do the calculations to create our nonce string, if necessary. String nonce = obtainNonce(webhook); // Add the nonce to the data bundle if we have it. if (nonce != null) { data.putString(Extras.NONCE, nonce); } // We have a stream of data, so we need to add that to the multipart form // upload with a possible HMAC. if (data.containsKey(Intent.EXTRA_STREAM)) { Uri mediaUri = (Uri) data.get(Intent.EXTRA_STREAM); // Open our mediaUri, base 64 encode it and add it to our multipart upload // entity. ByteArrayOutputStream baos = new ByteArrayOutputStream(); Base64OutputStream b64os = new Base64OutputStream(baos); InputStream is = contentResolver.openInputStream(mediaUri); byte[] bytes = new byte[1024]; int count; while ((count = is.read(bytes)) != -1) { b64os.write(bytes, 0, count); } is.close(); baos.close(); b64os.close(); final String base64EncodedString = new String(baos.toByteArray(), UTF8); entity.addPart(Extras.STREAM, new StringBody(base64EncodedString, UTF8_CHARSET)); // Add the mimetype of the stream to the data bundle. final String mimeType = contentResolver.getType(mediaUri); if (mimeType != null) { data.putString(Extras.STREAM_MIME_TYPE, mimeType); } // Do the hmac calculation of the stream and add it to the data bundle. // NOTE: This hmac string will be included as part of the input to the // other Extras hmac. if (shouldDoHmac(webhook)) { InputStream inputStream = contentResolver.openInputStream(mediaUri); final String streamHmac = hmacSha1(inputStream, secret, nonce); inputStream.close(); data.putString(Extras.STREAM_HMAC, streamHmac); Log.d(TAG, "STREAM_HMAC: " + streamHmac); } } // Calculate the Hmac for all the items by iterating over the data bundle // keys in order. if (shouldDoHmac(webhook)) { final String dataHmac = calculateBundleExtrasHmac(data, secret); data.putString(Extras.HMAC, dataHmac); Log.d(TAG, "HMAC: " + dataHmac); } // Dump all the data bundle keys into the form. for (String k : data.keySet()) { Object value = data.get(k); // If the value is null, the key will still be in the form, but with // an empty string as its value. if (value != null) { entity.addPart(k, new StringBody(value.toString(), UTF8_CHARSET)); } else { entity.addPart(k, new StringBody("", UTF8_CHARSET)); } } // Create the client and request, then populate it with our multipart form // upload entity as part of the POST request; finally post the form. final String webhookUri = webhook.getString(WebhookColumns.URI); final HttpClient client = new DefaultHttpClient(); client.getParams().setParameter(USER_AGENT_KEY, USER_AGENT); final HttpPost request = new HttpPost(webhookUri); request.setEntity(entity); HttpResponse response = client.execute(request); switch (response.getStatusLine().getStatusCode()) { case HttpStatus.SC_OK: case HttpStatus.SC_CREATED: case HttpStatus.SC_ACCEPTED: break; default: throw new RuntimeException(response.getStatusLine().toString()); } }
From source file:org.openurp.thesis.service.impl.CnkiThesisCheckServiceImpl.java
/** * //from w w w .j a v a 2 s . c o m * * @param author * @param article * @param file * @return * @throws Exception * @see http://pmlc.cnki.net/school/SwfUpload/handlers.js#uploadSuccess */ public boolean upload(String author, String article, File file) { Charset utf8 = Charset.forName("UTF-8"); MultipartEntity reqEntity = new MultipartEntity(); String content = null; try { reqEntity.addPart("JJ", new StringBody("", utf8)); reqEntity.addPart("DW", new StringBody("", utf8)); reqEntity.addPart("FL", new StringBody("", utf8)); reqEntity.addPart("PM", new StringBody(article, utf8)); reqEntity.addPart("ZZ", new StringBody(author, utf8)); reqEntity.addPart("FD", new StringBody(foldId, utf8)); reqEntity.addPart("ASPSESSID", new StringBody(sessionId, utf8)); reqEntity.addPart("Filedata", new FileBody(file)); HttpPost httpost = new HttpPost(uploadUrl); httpost.setEntity(reqEntity); HttpResponse response = httpclient.execute(httpost); HttpEntity entity = response.getEntity(); content = EntityUtils.toString(entity); EntityUtils.consume(entity); } catch (Exception e) { throw new UnhandledException(e); } logger.debug("upload " + file.getName() + " response is " + content); /* ?200??handlers.jsuploadSuccess */ return StringUtils.trim(content).equals("200"); }
From source file:cl.nic.dte.net.ConexionSii.java
private RECEPCIONDTEDocument uploadEnvio(String rutEnvia, String rutCompania, File archivoEnviarSII, String token, String urlEnvio, String hostEnvio) throws ClientProtocolException, IOException, org.apache.http.ParseException, XmlException { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(urlEnvio); MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); reqEntity.addPart("rutSender", new StringBody(rutEnvia.substring(0, rutEnvia.length() - 2))); reqEntity.addPart("dvSender", new StringBody(rutEnvia.substring(rutEnvia.length() - 1, rutEnvia.length()))); reqEntity.addPart("rutCompany", new StringBody(rutCompania.substring(0, (rutCompania).length() - 2))); reqEntity.addPart("dvCompany", new StringBody(rutCompania.substring(rutCompania.length() - 1, rutCompania.length()))); FileBody bin = new FileBody(archivoEnviarSII); reqEntity.addPart("archivo", bin); httppost.setEntity(reqEntity);//from w w w. j a v a2 s. c om BasicClientCookie cookie = new BasicClientCookie("TOKEN", token); cookie.setPath("/"); cookie.setDomain(hostEnvio); cookie.setSecure(true); cookie.setVersion(1); CookieStore cookieStore = new BasicCookieStore(); cookieStore.addCookie(cookie); httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109); httppost.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); HttpContext localContext = new BasicHttpContext(); localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); httppost.addHeader(new BasicHeader("User-Agent", Utilities.netLabels.getString("UPLOAD_SII_HEADER_VALUE"))); HttpResponse response = httpclient.execute(httppost, localContext); HttpEntity resEntity = response.getEntity(); RECEPCIONDTEDocument resp = null; HashMap<String, String> namespaces = new HashMap<String, String>(); namespaces.put("", "http://www.sii.cl/SiiDte"); XmlOptions opts = new XmlOptions(); opts.setLoadSubstituteNamespaces(namespaces); resp = RECEPCIONDTEDocument.Factory.parse(EntityUtils.toString(resEntity), opts); return resp; }
From source file:org.opencastproject.workingfilerepository.remote.WorkingFileRepositoryRemoteImpl.java
/** * {@inheritDoc}//from w w w. ja v a 2s. c om * * @see org.opencastproject.workingfilerepository.api.WorkingFileRepository#putInCollection(java.lang.String, * java.lang.String, java.io.InputStream) */ @Override public URI putInCollection(String collectionId, String fileName, InputStream in) { String url = UrlSupport.concat(new String[] { COLLECTION_PATH_PREFIX, collectionId }); HttpPost post = new HttpPost(url); MultipartEntity entity = new MultipartEntity(); ContentBody body = new InputStreamBody(in, fileName); entity.addPart("file", body); post.setEntity(entity); HttpResponse response = getResponse(post); try { if (response != null) { String content = EntityUtils.toString(response.getEntity()); return new URI(content); } } catch (Exception e) { throw new RuntimeException(e); } finally { closeConnection(response); } throw new RuntimeException("Unable to put file in collection"); }
From source file:org.opencastproject.workingfilerepository.remote.WorkingFileRepositoryRemoteImpl.java
/** * {@inheritDoc}//from w w w .ja va2s . co m * * @see org.opencastproject.workingfilerepository.api.WorkingFileRepository#put(java.lang.String, java.lang.String, * java.lang.String, java.io.InputStream) */ @Override public URI put(String mediaPackageID, String mediaPackageElementID, String filename, InputStream in) { String url = UrlSupport .concat(new String[] { MEDIAPACKAGE_PATH_PREFIX, mediaPackageID, mediaPackageElementID }); HttpPost post = new HttpPost(url); MultipartEntity entity = new MultipartEntity(); ContentBody body = new InputStreamBody(in, filename); entity.addPart("file", body); post.setEntity(entity); HttpResponse response = getResponse(post); try { if (response != null) { String content = EntityUtils.toString(response.getEntity()); return new URI(content); } } catch (Exception e) { throw new RuntimeException(e); } finally { closeConnection(response); } throw new RuntimeException("Unable to put file"); }
From source file:nl.phanos.liteliveresultsclient.LoginHandler.java
public void submitResults(ArrayList<ParFile> files) throws Exception { String url = "https://www.atletiek.nu/feeder.php?page=resultateninvoer&do=uploadresultaat&event_id=" + nuid + ""; System.out.println(url);//from ww w . j a v a2s . co m for (int i = 0; i < files.size(); i++) { HttpPost post = new HttpPost(url); post.setHeader("User-Agent", USER_AGENT); post.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); post.setHeader("Accept-Language", "en-US,en;q=0.5"); post.setHeader("Cookie", getCookies()); MultipartEntity mpEntity = new MultipartEntity(); System.out.println("files:" + files.size()); File file = files.get(i).resultFile; ContentBody cbFile = new FileBody(file, "text/plain"); mpEntity.addPart("files", cbFile); System.out.println("added file to upload"); post.setEntity(mpEntity); HttpResponse response = client.execute(post); int responseCode = response.getStatusLine().getStatusCode(); System.out.println("Response Code submit: " + responseCode); HttpEntity responseEntity = response.getEntity(); String responseString = ""; if (responseEntity != null) { responseString = EntityUtils.toString(responseEntity); } JSONObject obj = null; try { obj = new JSONObject(responseString); System.out.println("succes:" + responseString); } catch (Exception e) { System.out.println("error:" + responseString); } if (obj != null) { for (Object FileObj : (JSONArray) obj.get("files")) { JSONObject JSONFile = (JSONObject) FileObj; files.get(i).uploadDate = Calendar.getInstance().getTimeInMillis(); files.get(i).UploadedAtleten = "" + (Integer) JSONFile.get("totaalverwerkt"); AtletiekNuPanel.panel.addText("Uploaded " + JSONFile.get("name") + " met " + JSONFile.get("totaalverwerkt") + " atleten"); } } // set cookies setCookies(response.getFirstHeader("Set-Cookie") == null ? "" : response.getFirstHeader("Set-Cookie").toString()); post.releaseConnection(); } //getZip(nuid); }
From source file:org.hlc.http.resetfull.network.HttpExecutor.java
/** * Do post./* w w w. ja v a 2s .c om*/ * * @param <E> the element type * @param url the url * @param paramter the paramter * @param files the files * @param readTimeout the read timeout * @param result the result * @return the e */ public <E> E doPost(String url, Map<String, Object> paramter, Map<String, File> files, int readTimeout, MessageResolve<E> result) { MultipartEntity multipartEntity = new MultipartEntity(); try { if (paramter != null) { for (String name : paramter.keySet()) { multipartEntity.addPart(name, new StringBody(String.valueOf(paramter.get(name)), Charset.forName(HTTP.UTF_8))); } } if (files != null) { for (String name : files.keySet()) { multipartEntity.addPart(name, new FileBody(files.get(name))); } } } catch (Exception e) { Log.debug(e.getMessage()); result.error(NETWORK_ERROR, DEFUALT_MESSAGE_TYPE, e.getMessage()); return null; } HttpPost httpPost = new HttpPost(url); httpPost.setEntity(multipartEntity); return doExecute(httpPost, readTimeout, result); }
From source file:com.cellbots.eyes.EyesActivity.java
private void appEngineUploadImage(byte[] imageData) { Log.e("app engine remote eyes", "called"); try {/* w w w . j a v a2s . co m*/ YuvImage yuvImage = new YuvImage(imageData, previewFormat, previewWidth, previewHeight, null); yuvImage.compressToJpeg(r, 20, out); // Tweak the quality here - 20 // seems pretty decent for // quality + size. Log.e("app engine remote eyes", "upload starting"); HttpPost httpPost = new HttpPost(postUrl); Log.e("app engine perf", "0"); MultipartEntity entity = new MultipartEntity(); Log.e("app engine perf", "1"); entity.addPart("img", new InputStreamBody(new ByteArrayInputStream(out.toByteArray()), "video.jpg")); Log.e("app engine perf", "2"); httpPost.setEntity(entity); Log.e("app engine perf", "3"); HttpResponse response = httpclient.execute(httpPost); Log.e("app engine remote eyes", "result: " + response.getStatusLine()); Log.e("app engine remote eyes", "upload complete"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalStateException e) { e.printStackTrace(); resetAppEngineConnection(); } catch (ClientProtocolException e) { e.printStackTrace(); resetAppEngineConnection(); } catch (IOException e) { e.printStackTrace(); resetAppEngineConnection(); } finally { out.reset(); if (mCamera != null) { mCamera.addCallbackBuffer(mCallbackBuffer); } isUploading = false; Log.e("app engine remote eyes", "finished"); } }
From source file:fm.smart.r1.activity.CreateSoundActivity.java
public CreateSoundResult createSound(File file, String media_entity, String author, String author_url, String attribution_license_id, String id) { String http_response = ""; int status_code = 0; HttpClient client = null;//ww w . j a va2 s.co m String type = "sentence"; String location = ""; try { client = new DefaultHttpClient(); if (sound_type.equals(Integer.toString(R.id.cue_sound))) { type = "item"; } HttpPost post = new HttpPost("http://api.smart.fm/" + type + "s/" + id + "/sounds"); String auth = Main.username(this) + ":" + Main.password(this); byte[] bytes = auth.getBytes(); post.setHeader("Authorization", "Basic " + new String(Base64.encodeBase64(bytes))); post.setHeader("Host", "api.smart.fm"); FileBody bin = new FileBody(file, "audio/amr"); StringBody media_entity_part = new StringBody(media_entity); StringBody author_part = new StringBody(author); StringBody author_url_part = new StringBody(author_url); StringBody attribution_license_id_part = new StringBody(attribution_license_id); StringBody id_part = new StringBody(id); StringBody api_key_part = new StringBody(Main.API_KEY); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("sound[file]", bin); reqEntity.addPart("media_entity", media_entity_part); reqEntity.addPart("author", author_part); reqEntity.addPart("author_url", author_url_part); reqEntity.addPart("attribution_license_id", attribution_license_id_part); reqEntity.addPart(type + "_id", id_part); reqEntity.addPart("api_key", api_key_part); post.setEntity(reqEntity); Header[] array = post.getAllHeaders(); for (int i = 0; i < array.length; i++) { Log.d("DEBUG", array[i].toString()); } Log.d("CreateSoundActivity", "executing request " + post.getRequestLine()); HttpResponse response = client.execute(post); status_code = response.getStatusLine().getStatusCode(); HttpEntity resEntity = response.getEntity(); Log.d("CreateSoundActivity", "----------------------------------------"); Log.d("CreateSoundActivity", response.getStatusLine().toString()); array = response.getAllHeaders(); String header; for (int i = 0; i < array.length; i++) { header = array[i].toString(); if (header.equals("Location")) { location = header; } Log.d("CreateSoundActivity", header); } if (resEntity != null) { Log.d("CreateSoundActivity", "Response content length: " + resEntity.getContentLength()); Log.d("CreateSoundActivity", "Chunked?: " + resEntity.isChunked()); } long length = response.getEntity().getContentLength(); byte[] response_bytes = new byte[(int) length]; response.getEntity().getContent().read(response_bytes); Log.d("CreateSoundActivity", new String(response_bytes)); http_response = new String(response_bytes); if (resEntity != null) { resEntity.consumeContent(); } // HttpEntity entity = response1.getEntity(); } catch (IOException e) { /* Reset to Default image on any error. */ e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return new CreateSoundResult(status_code, http_response, location); }