List of usage examples for org.apache.http.entity.mime.content FileBody FileBody
public FileBody(final File file)
From source file:com.mutu.gpstracker.breadcrumbs.UploadBreadcrumbsTrackTask.java
private void uploadPhoto(File photo, Integer trackId) throws IOException, OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException { HttpPost request = new HttpPost("http://api.gobreadcrumbs.com/v1/photos.xml"); if (isCancelled()) { throw new IOException("Fail to execute request due to canceling"); }/* ww w . j a va 2 s. co m*/ MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); entity.addPart("name", new StringBody(photo.getName())); entity.addPart("track_id", new StringBody(Integer.toString(trackId))); //entity.addPart("description", new StringBody("")); entity.addPart("file", new FileBody(photo)); request.setEntity(entity); mConsumer.sign(request); if (BreadcrumbsAdapter.DEBUG) { Log.d(TAG, "Execute request: " + request.getURI()); for (Header header : request.getAllHeaders()) { Log.d(TAG, " with header: " + header.toString()); } } HttpResponse response = mHttpClient.execute(request); HttpEntity responseEntity = response.getEntity(); InputStream stream = responseEntity.getContent(); String responseText = XmlCreator.convertStreamToString(stream); mProgressAdmin.addPhotoUploadProgress(photo.length()); Log.i(TAG, "Uploaded photo " + responseText); }
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; }/*from ww w .j a v a 2 s . co 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:com.shenit.commons.utils.HttpUtils.java
/** * Create a multipart form// w ww. jav a2s . c o m * * @param request * Request object * @param keyVals * Key and value pairs, the even(begins with 0) position params * are key and the odds are values * @return */ public static HttpUriRequest multipartForm(HttpPost request, Object... keyVals) { if (request == null || ValidationUtils.isEmpty(keyVals)) return request; MultipartEntityBuilder builder = MultipartEntityBuilder.create(); boolean hasVal = false; String key; for (int i = 0; i < keyVals.length; i += 2) { key = ShenStrings.str(keyVals[i]); hasVal = i + 1 < keyVals.length; if (!hasVal || keyVals[i + 1] == null) { builder.addTextBody(key, StringUtils.EMPTY, CONTENT_TYPE_PLAIN_TEXT); break; } if (keyVals[i + 1].getClass().isAssignableFrom(File.class)) { builder.addPart(key, new FileBody((File) keyVals[i + 1])); } else { builder.addTextBody(key, keyVals[i + 1].toString(), CONTENT_TYPE_PLAIN_TEXT); } } request.setEntity(builder.build()); return request; }
From source file:nl.sogeti.android.gpstracker.actions.ShareTrack.java
private void sendToJogmap(Uri fileUri, String contentType) { String authCode = PreferenceManager.getDefaultSharedPreferences(this).getString(Constants.JOGRUNNER_AUTH, "");/*w w w .j av a 2 s . c o m*/ File gpxFile = new File(fileUri.getEncodedPath()); HttpClient httpclient = new DefaultHttpClient(); HttpResponse response = null; URI jogmap = null; String jogmapResponseText = ""; int statusCode = 0; try { jogmap = new URI(getString(R.string.jogmap_post_url)); HttpPost method = new HttpPost(jogmap); MultipartEntity entity = new MultipartEntity(); entity.addPart("id", new StringBody(authCode)); entity.addPart("mFile", new FileBody(gpxFile)); method.setEntity(entity); response = httpclient.execute(method); statusCode = response.getStatusLine().getStatusCode(); InputStream stream = response.getEntity().getContent(); jogmapResponseText = convertStreamToString(stream); } catch (IOException e) { Log.e(TAG, "Failed to upload to " + jogmap.toString(), e); CharSequence text = getString(R.string.jogmap_failed) + e.getLocalizedMessage(); Toast toast = Toast.makeText(this, text, Toast.LENGTH_LONG); toast.show(); } catch (URISyntaxException e) { //Log.e(TAG, "Failed to use configured URI " + jogmap.toString(), e); CharSequence text = getString(R.string.jogmap_failed) + e.getLocalizedMessage(); Toast toast = Toast.makeText(this, text, Toast.LENGTH_LONG); toast.show(); } if (statusCode == 200) { CharSequence text = getString(R.string.jogmap_success) + jogmapResponseText; Toast toast = Toast.makeText(this, text, Toast.LENGTH_LONG); toast.show(); } else { Log.e(TAG, "Wrong status code " + statusCode); CharSequence text = getString(R.string.jogmap_failed) + jogmapResponseText; Toast toast = Toast.makeText(this, text, Toast.LENGTH_LONG); toast.show(); } }
From source file:au.com.infiniterecursion.vidiom.utils.PublishingUtils.java
public Thread videoUploadToVideoBin(final Activity activity, final Handler handler, final String video_absolutepath, final String title, final String description, final String emailAddress, final long sdrecord_id) { Log.d(TAG, "doPOSTtoVideoBin starting"); // Make the progress bar view visible. ((VidiomActivity) activity).startedUploading(PublishingUtils.TYPE_VB); final Resources res = activity.getResources(); Thread t = new Thread(new Runnable() { public void run() { // Do background task. boolean failed = false; HttpClient client = new DefaultHttpClient(); client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); URI url = null;/*from ww w.ja va2s . co m*/ try { url = new URI(res.getString(R.string.http_videobin_org_add)); } catch (URISyntaxException e) { // Ours is a fixed URL, so not likely to get here. mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_VB); e.printStackTrace(); return; } HttpPost post = new HttpPost(url); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); File file = new File(video_absolutepath); entity.addPart(res.getString(R.string.video_bin_API_videofile), new FileBody(file)); try { entity.addPart(res.getString(R.string.video_bin_API_api), new StringBody("1", "text/plain", Charset.forName("UTF-8"))); // title entity.addPart(res.getString(R.string.video_bin_API_title), new StringBody(title, "text/plain", Charset.forName("UTF-8"))); // description entity.addPart(res.getString(R.string.video_bin_API_description), new StringBody(description, "text/plain", Charset.forName("UTF-8"))); } catch (IllegalCharsetNameException e) { // error e.printStackTrace(); failed = true; } catch (UnsupportedCharsetException e) { // error e.printStackTrace(); return; } catch (UnsupportedEncodingException e) { // error e.printStackTrace(); failed = true; } post.setEntity(entity); // Here we go! String response = null; try { response = EntityUtils.toString(client.execute(post).getEntity(), "UTF-8"); } catch (ParseException e) { // error e.printStackTrace(); failed = true; } catch (ClientProtocolException e) { // error e.printStackTrace(); failed = true; } catch (IOException e) { // error e.printStackTrace(); failed = true; } client.getConnectionManager().shutdown(); // CHECK RESPONSE FOR SUCCESS!! if (!failed && response != null && response.matches(res.getString(R.string.video_bin_API_good_re))) { // We got back HTTP response with valid URL Log.d(TAG, " video bin got back URL " + response); } else { Log.d(TAG, " video bin got eror back:\n" + response); failed = true; } if (failed) { // Use the handler to execute a Runnable on the // main thread in order to have access to the // UI elements. mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_VB); handler.postDelayed(new Runnable() { public void run() { // Update UI // Indicate back to calling activity the result! // update uploadInProgress state also. ((VidiomActivity) activity).finishedUploading(false); ((VidiomActivity) activity) .createNotification(res.getString(R.string.upload_to_videobin_org_failed_)); } }, 0); return; } // XXX Convert to preference for auto-email on videobin post // XXX ADD EMAIL NOTIF to all other upload methods // stuck on YES here, if email is defined. if (emailAddress != null && response != null) { // EmailSender through IR controlled gmail system. SSLEmailSender sender = new SSLEmailSender( activity.getString(R.string.automatic_email_username), activity.getString(R.string.automatic_email_password)); // consider // this // public // knowledge. try { sender.sendMail(activity.getString(R.string.vidiom_automatic_email), // subject.getText().toString(), activity.getString(R.string.url_of_hosted_video_is_) + " " + response, // body.getText().toString(), activity.getString(R.string.automatic_email_from), // from.getText().toString(), emailAddress // to.getText().toString() ); } catch (Exception e) { Log.e(TAG, e.getMessage(), e); } } // Log record of this URL in POSTs table dbutils.creatHostDetailRecordwithNewVideoUploaded(sdrecord_id, res.getString(R.string.http_videobin_org_add), response, ""); mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_VB); // Use the handler to execute a Runnable on the // main thread in order to have access to the // UI elements. handler.postDelayed(new Runnable() { public void run() { // Update UI // Indicate back to calling activity the result! // update uploadInProgress state also. ((VidiomActivity) activity).finishedUploading(true); ((VidiomActivity) activity) .createNotification(res.getString(R.string.upload_to_videobin_org_succeeded_)); } }, 0); } }); t.start(); return t; }
From source file:com.poomoo.edao.activity.UploadPicsActivity.java
private void upload(File file) { HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(eDaoClientConfig.imageurl); // ?Post?,Post client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, eDaoClientConfig.timeout); client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, eDaoClientConfig.timeout); MultipartEntity entity = new MultipartEntity(); // , // List<File> list = new ArrayList<File>(); // // File/* www . j av a2 s .c om*/ // list.add(file1); // list.add(file2); // list.add(file3); // list.add(file4); // System.out.println("list.size():" + list.size()); // for (int i = 0; i < list.size(); i++) { // ContentBody body = new FileBody(list.get(i)); // entity.addPart("file", body); // ??? // } System.out.println( "upload" + "uploadCount" + ":" + uploadCount + "filelist.size" + ":" + filelist.size()); entity.addPart("file", new FileBody(file)); post.setEntity(entity); // ?Post? Message message = new Message(); try { entity.addPart("imageType", new StringBody(String.valueOf(uploadCount + 1), Charset.forName("utf-8"))); entity.addPart("userId", new StringBody(userId, Charset.forName("utf-8"))); HttpResponse response; response = client.execute(post); // Post if (response.getStatusLine().getStatusCode() == 200) { uploadCount++; message.what = 1; } else message.what = 2; // return EntityUtils.toString(response.getEntity(), "UTF-8"); // // ?? } catch (Exception e) { // TODO ? catch ? e.printStackTrace(); message.what = 2; System.out.println("IOException:" + e.getMessage()); } finally { client.getConnectionManager().shutdown(); // ? myHandler.sendMessage(message); } }
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 ww w. j a va 2 s .c o m*/ 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:com.cloverstudio.spika.couchdb.ConnectionHandler.java
public static String getIdFromFileUploader(String url, List<NameValuePair> params) throws ClientProtocolException, IOException, UnsupportedOperationException, SpikaException, JSONException {/* w ww .ja va 2 s . c o m*/ // Making HTTP request // defaultHttpClient HttpParams httpParams = new BasicHttpParams(); HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(httpParams, "UTF-8"); HttpClient httpClient = new DefaultHttpClient(httpParams); HttpPost httpPost = new HttpPost(url); httpPost.setHeader("database", Const.DATABASE); Charset charSet = Charset.forName("UTF-8"); // Setting up the // encoding MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); for (int index = 0; index < params.size(); index++) { if (params.get(index).getName().equalsIgnoreCase(Const.FILE)) { // If the key equals to "file", we use FileBody to // transfer the data entity.addPart(params.get(index).getName(), new FileBody(new File(params.get(index).getValue()))); } else { // Normal string data entity.addPart(params.get(index).getName(), new StringBody(params.get(index).getValue(), charSet)); } } httpPost.setEntity(entity); print(httpPost); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); InputStream is = httpEntity.getContent(); // if (httpResponse.getStatusLine().getStatusCode() > 400) // { // if (httpResponse.getStatusLine().getStatusCode() == 500) throw new SpikaException(ConnectionHandler.getError(entity.getContent())); // throw new IOException(httpResponse.getStatusLine().getReasonPhrase()); // } // BufferedReader reader = new BufferedReader(new // InputStreamReader(is, "iso-8859-1"), 8); BufferedReader reader = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line); } is.close(); String json = sb.toString(); Logger.debug("RESPONSE", json); return json; }
From source file:net.ymate.framework.commons.HttpClientHelper.java
public IHttpResponse upload(String url, String fieldName, File uploadFile, Header[] headers) throws Exception { return upload(url, fieldName, new FileBody(uploadFile), headers, null); }