List of usage examples for org.apache.http.entity.mime MultipartEntity addPart
public void addPart(final String name, final ContentBody contentBody)
From source file:uk.co.tfd.sm.proxy.ProxyClientServiceImpl.java
private void addPart(MultipartEntity multipart, String key, Object value) throws UnsupportedEncodingException { if (value instanceof String[]) { String[] v = (String[]) value; for (String s : v) { multipart.addPart(key, new StringBody(s, Charset.forName("UTF-8"))); }/* ww w .j a v a 2 s. c om*/ } else { multipart.addPart(key, new StringBody((String) value, Charset.forName("UTF-8"))); } }
From source file:com.glasshack.checkmymath.CheckMyMath.java
public String post(String url, List<NameValuePair> nameValuePairs) { HttpClient httpClient = new DefaultHttpClient(); HttpContext localContext = new BasicHttpContext(); HttpPost httpPost = new HttpPost(url); String readableResponse = null; try {//from w w w .j av a 2 s .c om MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); for (int index = 0; index < nameValuePairs.size(); index++) { if (nameValuePairs.get(index).getName().equalsIgnoreCase("file")) { // If the key equals to "file", we use FileBody to transfer the data entity.addPart("file", new FileBody(new File(nameValuePairs.get(index).getValue()), "image/jpeg")); } else { // Normal string data entity.addPart(nameValuePairs.get(index).getName(), new StringBody(nameValuePairs.get(index).getValue())); } } httpPost.setEntity(entity); HttpResponse response = httpClient.execute(httpPost, localContext); readableResponse = EntityUtils.toString(response.getEntity(), "UTF-8"); Log.e("response", readableResponse); } catch (IOException e) { e.printStackTrace(); } return readableResponse; }
From source file:com.mutu.gpstracker.breadcrumbs.UploadBreadcrumbsTrackTask.java
/** * Retrieve the OAuth Request Token and present a browser to the user to * authorize the token.//from w w w. ja v a2s .co m */ @Override protected Uri doInBackground(Void... params) { // Leave room in the progressbar for uploading determineProgressGoal(); mProgressAdmin.setUpload(true); // Build GPX file Uri gpxFile = exportGpx(); if (isCancelled()) { String text = mContext.getString(R.string.ticker_failed) + " \"http://api.gobreadcrumbs.com/v1/tracks\" " + mContext.getString(R.string.error_buildxml); handleError(mContext.getString(R.string.taskerror_breadcrumbs_upload), new IOException("Fail to execute request due to canceling"), text); } // Collect GPX Import option params mActivityId = null; mBundleId = null; mDescription = null; mIsPublic = null; Uri metadataUri = Uri.withAppendedPath(mTrackUri, "metadata"); Cursor cursor = null; try { cursor = mContext.getContentResolver().query(metadataUri, new String[] { MetaData.KEY, MetaData.VALUE }, null, null, null); if (cursor.moveToFirst()) { do { String key = cursor.getString(0); if (BreadcrumbsTracks.ACTIVITY_ID.equals(key)) { mActivityId = cursor.getString(1); } else if (BreadcrumbsTracks.BUNDLE_ID.equals(key)) { mBundleId = cursor.getString(1); } else if (BreadcrumbsTracks.DESCRIPTION.equals(key)) { mDescription = cursor.getString(1); } else if (BreadcrumbsTracks.ISPUBLIC.equals(key)) { mIsPublic = cursor.getString(1); } } while (cursor.moveToNext()); } } finally { if (cursor != null) { cursor.close(); } } if ("-1".equals(mActivityId)) { String text = "Unable to upload without a activity id stored in meta-data table"; IllegalStateException e = new IllegalStateException(text); handleError(mContext.getString(R.string.taskerror_breadcrumbs_upload), e, text); } int statusCode = 0; String responseText = null; Uri trackUri = null; HttpEntity responseEntity = null; try { if ("-1".equals(mBundleId)) { mBundleDescription = "";//mContext.getString(R.string.breadcrumbs_bundledescription); mBundleName = mContext.getString(R.string.app_name); mBundleId = createOpenGpsTrackerBundle(); } String gpxString = XmlCreator .convertStreamToString(mContext.getContentResolver().openInputStream(gpxFile)); HttpPost method = new HttpPost("http://api.gobreadcrumbs.com:80/v1/tracks"); if (isCancelled()) { throw new IOException("Fail to execute request due to canceling"); } // Build the multipart body with the upload data MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); entity.addPart("import_type", new StringBody("GPX")); //entity.addPart("gpx", new FileBody(gpxFile)); entity.addPart("gpx", new StringBody(gpxString)); entity.addPart("bundle_id", new StringBody(mBundleId)); entity.addPart("activity_id", new StringBody(mActivityId)); entity.addPart("description", new StringBody(mDescription)); // entity.addPart("difficulty", new StringBody("3")); // entity.addPart("rating", new StringBody("4")); entity.addPart("public", new StringBody(mIsPublic)); method.setEntity(entity); // Execute the POST to OpenStreetMap mConsumer.sign(method); if (BreadcrumbsAdapter.DEBUG) { Log.d(TAG, "HTTP Method " + method.getMethod()); Log.d(TAG, "URI scheme " + method.getURI().getScheme()); Log.d(TAG, "Host name " + method.getURI().getHost()); Log.d(TAG, "Port " + method.getURI().getPort()); Log.d(TAG, "Request path " + method.getURI().getPath()); Log.d(TAG, "Consumer Key: " + mConsumer.getConsumerKey()); Log.d(TAG, "Consumer Secret: " + mConsumer.getConsumerSecret()); Log.d(TAG, "Token: " + mConsumer.getToken()); Log.d(TAG, "Token Secret: " + mConsumer.getTokenSecret()); Log.d(TAG, "Execute request: " + method.getURI()); for (Header header : method.getAllHeaders()) { Log.d(TAG, " with header: " + header.toString()); } } HttpResponse response = mHttpClient.execute(method); mProgressAdmin.addUploadProgress(); statusCode = response.getStatusLine().getStatusCode(); responseEntity = response.getEntity(); InputStream stream = responseEntity.getContent(); responseText = XmlCreator.convertStreamToString(stream); if (BreadcrumbsAdapter.DEBUG) { Log.d(TAG, "Upload Response: " + responseText); } Pattern p = Pattern.compile(">([0-9]+)</id>"); Matcher m = p.matcher(responseText); if (m.find()) { Integer trackId = Integer.valueOf(m.group(1)); trackUri = Uri.parse("http://api.gobreadcrumbs.com/v1/tracks/" + trackId + "/placemarks.gpx"); for (File photo : mPhotoUploadQueue) { uploadPhoto(photo, trackId); } } } catch (OAuthMessageSignerException e) { mService.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_upload), e, "Failed to sign the request with authentication signature"); } catch (OAuthExpectationFailedException e) { mService.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_upload), e, "The request did not authenticate"); } catch (OAuthCommunicationException e) { mService.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_upload), e, "The authentication communication failed"); } catch (IOException e) { handleError(mContext.getString(R.string.taskerror_breadcrumbs_upload), e, "A problem during communication"); } finally { if (responseEntity != null) { try { //EntityUtils.consume(responseEntity); responseEntity.consumeContent(); } catch (IOException e) { Log.e(TAG, "Failed to close the content stream", e); } } } if (statusCode == 200 || statusCode == 201) { if (trackUri == null) { handleError(mContext.getString(R.string.taskerror_breadcrumbs_upload), new IOException("Unable to retrieve URI from response"), responseText); } } else { //mAdapter.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_upload), new IOException("Status code: " + statusCode), responseText); } return trackUri; }
From source file:com.klinker.android.twitter.utils.api_helper.TwitterMultipleImageHelper.java
public boolean uploadPics(File[] pics, String text, Twitter twitter) { JSONObject jsonresponse = new JSONObject(); final String ids_string = getMediaIds(pics, twitter); if (ids_string == null) { return false; }/*from w ww. j av a 2 s . co m*/ try { AccessToken token = twitter.getOAuthAccessToken(); String oauth_token = token.getToken(); String oauth_token_secret = token.getTokenSecret(); // generate authorization header String get_or_post = "POST"; String oauth_signature_method = "HMAC-SHA1"; String uuid_string = UUID.randomUUID().toString(); uuid_string = uuid_string.replaceAll("-", ""); String oauth_nonce = uuid_string; // any relatively random alphanumeric string will work here // get the timestamp Calendar tempcal = Calendar.getInstance(); long ts = tempcal.getTimeInMillis();// get current time in milliseconds String oauth_timestamp = (new Long(ts / 1000)).toString(); // then divide by 1000 to get seconds // the parameter string must be in alphabetical order, "text" parameter added at end String parameter_string = "oauth_consumer_key=" + AppSettings.TWITTER_CONSUMER_KEY + "&oauth_nonce=" + oauth_nonce + "&oauth_signature_method=" + oauth_signature_method + "&oauth_timestamp=" + oauth_timestamp + "&oauth_token=" + encode(oauth_token) + "&oauth_version=1.0"; System.out.println("Twitter.updateStatusWithMedia(): parameter_string=" + parameter_string); String twitter_endpoint = "https://api.twitter.com/1.1/statuses/update.json"; String twitter_endpoint_host = "api.twitter.com"; String twitter_endpoint_path = "/1.1/statuses/update.json"; String signature_base_string = get_or_post + "&" + encode(twitter_endpoint) + "&" + encode(parameter_string); String oauth_signature = computeSignature(signature_base_string, AppSettings.TWITTER_CONSUMER_SECRET + "&" + encode(oauth_token_secret)); String authorization_header_string = "OAuth oauth_consumer_key=\"" + AppSettings.TWITTER_CONSUMER_KEY + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"" + oauth_timestamp + "\",oauth_nonce=\"" + oauth_nonce + "\",oauth_version=\"1.0\",oauth_signature=\"" + encode(oauth_signature) + "\",oauth_token=\"" + encode(oauth_token) + "\""; HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "UTF-8"); HttpProtocolParams.setUserAgent(params, "HttpCore/1.1"); HttpProtocolParams.setUseExpectContinue(params, false); HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { // Required protocol interceptors new RequestContent(), new RequestTargetHost(), // Recommended protocol interceptors new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() }); HttpRequestExecutor httpexecutor = new HttpRequestExecutor(); HttpContext context = new BasicHttpContext(null); HttpHost host = new HttpHost(twitter_endpoint_host, 443); DefaultHttpClientConnection conn = new DefaultHttpClientConnection(); context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host); try { try { SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(null, null, null); SSLSocketFactory ssf = sslcontext.getSocketFactory(); Socket socket = ssf.createSocket(); socket.connect(new InetSocketAddress(host.getHostName(), host.getPort()), 0); conn.bind(socket, params); BasicHttpEntityEnclosingRequest request2 = new BasicHttpEntityEnclosingRequest("POST", twitter_endpoint_path); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("media_ids", new StringBody(ids_string)); reqEntity.addPart("status", new StringBody(text)); reqEntity.addPart("trim_user", new StringBody("1")); request2.setEntity(reqEntity); request2.setParams(params); request2.addHeader("Authorization", authorization_header_string); httpexecutor.preProcess(request2, httpproc, context); HttpResponse response2 = httpexecutor.execute(request2, conn, context); response2.setParams(params); httpexecutor.postProcess(response2, httpproc, context); String responseBody = EntityUtils.toString(response2.getEntity()); System.out.println("response=" + responseBody); // error checking here. Otherwise, status should be updated. jsonresponse = new JSONObject(responseBody); conn.close(); } catch (HttpException he) { System.out.println(he.getMessage()); jsonresponse.put("response_status", "error"); jsonresponse.put("message", "updateStatus HttpException message=" + he.getMessage()); } catch (NoSuchAlgorithmException nsae) { System.out.println(nsae.getMessage()); jsonresponse.put("response_status", "error"); jsonresponse.put("message", "updateStatus NoSuchAlgorithmException message=" + nsae.getMessage()); } catch (KeyManagementException kme) { System.out.println(kme.getMessage()); jsonresponse.put("response_status", "error"); jsonresponse.put("message", "updateStatus KeyManagementException message=" + kme.getMessage()); } finally { conn.close(); } } catch (JSONException jsone) { jsone.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } } catch (Exception e) { } return true; }
From source file:net.ccghe.emocha.async.UploadOneFile.java
public UploadOneFile(String path, String serverURL, FileTransmitter transmitter, MultipartEntity postData) { // configure connection HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, 20 * Constants.ONE_SECOND); HttpConnectionParams.setSoTimeout(params, 20 * Constants.ONE_SECOND); HttpClientParams.setRedirecting(params, false); // setup client DefaultHttpClient client = new DefaultHttpClient(params); HttpPost post = new HttpPost(serverURL); int id = 0;/*from ww w.jav a2 s .c o m*/ postData.addPart("file" + id, new FileBody(new File(path))); try { postData.addPart("path" + id, new StringBody(path)); } catch (UnsupportedEncodingException e1) { Log.e(Constants.LOG_TAG, "Encoding error while uploading file."); } // prepare response and return uploaded try { post.setEntity(postData); HttpResponse response = client.execute(post); HttpEntity entity = response.getEntity(); InputStream stream = entity.getContent(); String jsonResponse = Server.convertStreamToString(stream); stream.close(); if (postData != null) { postData.consumeContent(); } JSONObject jObject = new JSONObject(jsonResponse); Long ok = jObject.getLong("ok"); if (ok > 0) { DBAdapter.markAsUploaded(path); Log.i(Constants.LOG_TAG, "Mark as uploaded: " + path); } else { Log.e(Constants.LOG_TAG, "Error uploading: " + path + " (json response not ok)"); } } catch (ClientProtocolException e) { Log.e("EMOCHA", "ClientProtocolException ERR. " + e.getMessage()); } catch (IOException e) { Log.e("EMOCHA", "IOException ERR. " + e.getMessage()); } catch (Exception e) { Log.e("EMOCHA", "Exception ERR. " + e.getMessage()); } /* // check response. // TODO: This isn't handled correctly. String serverLocation = null; Header[] h = response.getHeaders("Location"); if (h != null && h.length > 0) { serverLocation = h[0].getValue(); } else { // something should be done here... Log.e(Constants.LOG_TAG, "Location header was absent"); } int responseCode = response.getStatusLine().getStatusCode(); Log.e(Constants.LOG_TAG, "Response code:" + responseCode); // verify that your response came from a known server if (serverLocation != null && serverURL.contains(serverLocation) && responseCode == 201) { DBAdapter.markAsUploaded(path); } */ transmitter.transmitComplete(); }
From source file:com.auditmark.jscrambler.client.JScrambler.java
private Object httpRequest(String requestMethod, String resourcePath, Map params) throws IOException, Exception { String signedData = null, urlQueryPart = null; if (requestMethod.toUpperCase().equals("POST") && params.isEmpty()) { throw new IllegalArgumentException("Parameters missing for POST request."); }/* w w w . j a va 2 s . com*/ String[] files = null; if (params == null) { params = new TreeMap(); } else { if (params.get("files") instanceof String) { files = new String[] { (String) params.get("files") }; params.put("files", files); } else if (params.get("files") instanceof String[]) { files = (String[]) params.get("files"); } params = new TreeMap(params); } if (requestMethod.toUpperCase().equals("POST")) { signedData = signedQuery(requestMethod, resourcePath, params, null); } else { urlQueryPart = "?" + signedQuery(requestMethod, resourcePath, params, null); } // http client HttpClient httpclient = new DefaultHttpClient(); HttpResponse response = null; try { if (signedData != null && requestMethod.toUpperCase().equals("POST")) { HttpPost httppost = new HttpPost( apiURL() + resourcePath + (urlQueryPart != null ? urlQueryPart : "")); MultipartEntity reqEntity = new MultipartEntity(); if (files != null) { int n = 0; for (String filename : files) { FileBody fb = new FileBody(new File(filename)); reqEntity.addPart("file_" + n++, fb); } } for (String param : (Set<String>) params.keySet()) { if (param.equals("files") || param.startsWith("file_")) { continue; } if (params.get(param) instanceof String) { reqEntity.addPart(param, new StringBody((String) params.get(param))); } } httppost.setEntity(reqEntity); response = httpclient.execute(httppost); } else if (requestMethod.toUpperCase().equals("GET")) { HttpGet request = new HttpGet(apiURL() + resourcePath + (urlQueryPart != null ? urlQueryPart : "")); response = httpclient.execute(request); } else if (requestMethod.toUpperCase().equals("DELETE")) { HttpDelete request = new HttpDelete( apiURL() + resourcePath + (urlQueryPart != null ? urlQueryPart : "")); response = httpclient.execute(request); } else { throw new Exception("Invalid request method."); } HttpEntity httpEntity = response.getEntity(); // if GET Zip archive if (requestMethod.toUpperCase().equals("GET") && resourcePath.toLowerCase().endsWith(".zip") && response.getStatusLine().getStatusCode() == 200) { // Return inputstream return httpEntity.getContent(); } // Otherwise return string return EntityUtils.toString(httpEntity, "UTF-8"); } catch (IOException e) { throw e; } catch (Exception e) { throw e; } }
From source file:com.k42b3.neodym.oauth.Oauth.java
@SuppressWarnings("unused") private HttpEntity httpRequest(String method, String url, Map<String, String> header, String body) throws Exception { // build request HttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, 6000); DefaultHttpClient httpClient = new DefaultHttpClient(httpParams); HttpRequestBase request;// w w w. jav a2 s. c o m if (method.equals("GET")) { request = new HttpGet(url); } else if (method.equals("POST")) { MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); entity.addPart("text", new StringBody(body)); request = new HttpPost(url); ((HttpPost) request).setEntity(entity); } else { throw new Exception("Invalid request method"); } // header Set<String> keys = header.keySet(); for (String key : keys) { request.setHeader(key, header.get(key)); } // execute HTTP Get Request logger.info("Request: " + request.getRequestLine()); HttpResponse httpResponse = httpClient.execute(request); HttpEntity entity = httpResponse.getEntity(); String responseContent = EntityUtils.toString(entity); // log traffic if (trafficListener != null) { TrafficItem trafficItem = new TrafficItem(); trafficItem.setRequest(request); trafficItem.setResponse(httpResponse); trafficItem.setResponseContent(responseContent); trafficListener.handleRequest(trafficItem); } // check status code int statusCode = httpResponse.getStatusLine().getStatusCode(); if (!(statusCode >= 200 && statusCode < 300)) { JOptionPane.showMessageDialog(null, responseContent); throw new Exception("No successful status code"); } return entity; }
From source file:palamarchuk.smartlife.app.RegisterActivity.java
private MultipartEntity collectData() throws UnsupportedEncodingException { MultipartEntity entity = new MultipartEntity(); entity.addPart("email", new StringBody(email.getText().toString())); entity.addPart("password", new StringBody(password.getText().toString())); entity.addPart("first_name", new StringBody(name.getText().toString())); entity.addPart("birthdate", new StringBody(birthDateToServer)); entity.addPart("gender", new StringBody(String.valueOf(gender))); entity.addPart("phone", new StringBody(phone.getText().toString())); entity.addPart("last_name", new StringBody(lastName.getText().toString())); entity.addPart("city_id", new StringBody(cities.getCityId())); entity.addPart("secret", new StringBody(registerActivitySecret.getText().toString())); entity.addPart("card_number", new StringBody(cardNumber)); entity.addPart("pin", new StringBody(cardPinCode)); return entity; }
From source file:com.glodon.paas.document.api.PerformanceRestAPITest.java
/** * multipart/* ww w . java 2 s. c om*/ */ @Test public void testUploadFileForMultiPart() throws IOException { File parentFile = createFile("testUpload"); java.io.File file = new java.io.File("src/test/resources/file/testupload.file"); if (!file.exists()) { file = new java.io.File(tempUploadFile); } String uploadUrl = "/file/" + file.getName() + "?upload&position=0&type=path"; HttpPost post = createPost(uploadUrl); FileBody fileBody = new FileBody(file); StringBody sbId = new StringBody(parentFile.getId()); StringBody sbSize = new StringBody(String.valueOf(file.length())); StringBody sbName = new StringBody(file.getName()); StringBody sbPosition = new StringBody("0"); MultipartEntity entity = new MultipartEntity(); entity.addPart("fileId", sbId); entity.addPart("size", sbSize); entity.addPart("fileName", sbName); entity.addPart("position", sbPosition); entity.addPart("file", fileBody); post.setEntity(entity); String response = simpleCall(post); assertNotNull(response); File resultFile = convertString2Obj(response, new TypeReference<File>() { }); assertEquals(file.getName(), resultFile.getFullName()); assertTrue(file.length() == resultFile.getSize()); }
From source file:org.megam.deccanplato.provider.box.handler.FileImpl.java
/** * @return// w ww. j av a 2s. co m */ private Map<String, String> upload() { Map<String, String> outMap = new HashMap<>(); final String BOX_UPLOAD = "/files/content"; Map<String, String> headerMap = new HashMap<String, String>(); headerMap.put("Authorization", "BoxAuth api_key=" + args.get(API_KEY) + "&auth_token=" + args.get(TOKEN)); MultipartEntity entity = new MultipartEntity(); FileBody filename = new FileBody(new File(args.get(FILE_NAME))); FileBody filename1 = new FileBody(new File("/home/pandiyaraja/Documents/AMIs")); StringBody parent_id = null; try { parent_id = new StringBody(args.get(FOLDER_ID)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } entity.addPart("filename", filename); entity.addPart("parent_id", parent_id); TransportTools tools = new TransportTools(BOX_URI + BOX_UPLOAD, null, headerMap); tools.setFileEntity(entity); String responseBody = null; TransportResponse response = null; try { response = TransportMachinery.post(tools); responseBody = response.entityToString(); System.out.println("OUTPUT:" + responseBody); } catch (ClientProtocolException ce) { ce.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } outMap.put(OUTPUT, responseBody); return outMap; }