List of usage examples for org.apache.http.entity.mime MultipartEntity getContentLength
public long getContentLength()
From source file:no.digipost.android.api.ApiAccess.java
public static void uploadFile(Context context, String uri, File file) throws DigipostClientException { try {//from w w w . j av a2s .c o m try { FileBody filebody = new FileBody(file, ApiConstants.CONTENT_OCTET_STREAM); MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, Charset.forName(ApiConstants.ENCODING)); multipartEntity.addPart("subject", new StringBody(FilenameUtils.removeExtension(file.getName()), ApiConstants.MIME, Charset.forName(ApiConstants.ENCODING))); multipartEntity.addPart("file", filebody); multipartEntity.addPart("token", new StringBody(TokenStore.getAccess())); URL url = new URL(uri); HttpsURLConnection httpsClient = (HttpsURLConnection) url.openConnection(); httpsClient.setRequestMethod("POST"); httpsClient.setDoOutput(true); if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { httpsClient.setFixedLengthStreamingMode(multipartEntity.getContentLength()); } else { httpsClient.setChunkedStreamingMode(0); } httpsClient.setRequestProperty("Connection", "Keep-Alive"); httpsClient.addRequestProperty("Content-length", multipartEntity.getContentLength() + ""); httpsClient.setRequestProperty(ApiConstants.AUTHORIZATION, ApiConstants.BEARER + TokenStore.getAccess()); httpsClient.addRequestProperty(multipartEntity.getContentType().getName(), multipartEntity.getContentType().getValue()); try { OutputStream outputStream = new BufferedOutputStream(httpsClient.getOutputStream()); multipartEntity.writeTo(outputStream); outputStream.flush(); NetworkUtilities.checkHttpStatusCode(context, httpsClient.getResponseCode()); } finally { httpsClient.disconnect(); } } catch (DigipostInvalidTokenException e) { OAuth.updateAccessTokenWithRefreshToken(context); uploadFile(context, uri, file); } } catch (Exception e) { e.printStackTrace(); Log.e(TAG, context.getString(R.string.error_your_network)); throw new DigipostClientException(context.getString(R.string.error_your_network)); } }
From source file:org.andrico.andjax.http.HttpClientService.java
/** * Put an http request on the queue to be executed. Upon completion of the * http request, a runnable will be called. Right now this is limited in * that you can only pass one value per key in the http post. (The Map is * the limiter).//from w w w .j a v a2 s . c o m * * @param url The url to access. * @param multipartEntity The POST parameters to pass to this request. * @param responseRunnable The runnable to execute upon http request * completion. * @throws URISyntaxException */ public void submit(String url, MultipartEntity multipartEntity, IHttpResponseRunnable responseRunnable) throws URISyntaxException { Log.d(TAG, "submitting multipartentity dodad"); HttpMessage httpMessage; httpMessage = this.mHttpMessageFactory.createFromParts(url, multipartEntity); Log.d(TAG, "Posting multipartEntity" + multipartEntity.toString()); Log.d(TAG, String.valueOf(multipartEntity.getContentLength())); Log.d(TAG, multipartEntity.toString()); this.submit(new HttpChainingRunnable(new HttpMessageCallable(httpMessage), responseRunnable)); }
From source file:org.fedoraproject.eclipse.packager.api.UploadSourceCommand.java
/** * Upload a missing file to the lookaside cache. * // w w w.j av a 2 s . c o m * Pre: upload file is missing as determined by * {@link UploadSourceCommand#checkSourceAvailable()}. * * @param subMonitor * @return The result of the upload. */ private UploadSourceResult upload(final IProgressMonitor subMonitor) throws UploadFailedException { HttpClient client = getClient(); try { String uploadUrl = projectRoot.getLookAsideCache().getUploadUrl().toString(); if (fedoraSslEnabled) { // user requested a Fedora SSL enabled client client = fedoraSslEnable(client); } else if (trustAllSSLEnabled) { // use an trust-all SSL enabled client client = trustAllSslEnable(client); } HttpPost post = new HttpPost(uploadUrl); FileBody uploadFileBody = new FileBody(fileToUpload); // For the actual upload we must not provide the // "filename" parameter (FILENAME_PARAM_NAME). Otherwise, // the file won't be stored in the lookaside cache. MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart(FILE_PARAM_NAME, uploadFileBody); reqEntity.addPart(PACKAGENAME_PARAM_NAME, new StringBody(projectRoot.getSpecfileModel().getName())); reqEntity.addPart(CHECKSUM_PARAM_NAME, new StringBody(SourcesFile.calculateChecksum(fileToUpload))); // Not sure why it's ~ content-length * 2, but that's what it is... final long totalsize = reqEntity.getContentLength() * 2; subMonitor.beginTask(NLS.bind(FedoraPackagerText.UploadSourceCommand_uploadingFileSubTaskName, fileToUpload.getName()), 100 /* use percentage */); subMonitor.worked(0); // Custom listener for progress reporting of the file upload IRequestProgressListener progL = new IRequestProgressListener() { private int count = 0; private int worked = 0; private int updatedWorked = 0; @Override public void transferred(final long bytesWritten) { count++; worked = updatedWorked; if (subMonitor.isCanceled()) { throw new OperationCanceledException(); } // Since this listener may be called *a lot*, don't // do the calculation to often. if ((count % 1024) == 0) { updatedWorked = // multiply by 85 (instead of 100) since upload // progress cannot be 100% accurate. (int) ((double) bytesWritten / totalsize * 85); if (updatedWorked > worked) { worked = updatedWorked; subMonitor.worked(updatedWorked); } } } }; // We need to wrap the entity which we want to upload in our // custom entity, which allows for progress listening. CoutingRequestEntity countingEntity = new CoutingRequestEntity(reqEntity, progL); post.setEntity(countingEntity); // TODO: This may throw some certificate exception. We should // handle this case and throw a specific exception in order to // report this to the user. I.e. advise to use use $ fedora-cert -n HttpResponse response = client.execute(post); subMonitor.done(); return new UploadSourceResult(response); } catch (IOException e) { throw new UploadFailedException(e.getMessage(), e); } catch (GeneralSecurityException e) { throw new UploadFailedException(e.getMessage(), e); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources client.getConnectionManager().shutdown(); } }
From source file:org.nasa.openspace.gc.geolocation.LocationActivity.java
public void executeMultipartPost() throws Exception { try {// w ww . ja v a 2 s . c o m HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost("http://192.168.14.102/index.php/photos/upload"); ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); Session.image.compress(Bitmap.CompressFormat.PNG, 100, byteStream); byte[] buffer = byteStream.toByteArray(); ByteArrayBody body = new ByteArrayBody(buffer, "profile_image"); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); entity.addPart("gambar", body); entity.addPart("nama", new StringBody(Session.name)); //POST nama entity.addPart("keterangan", new StringBody(Session.caption)); //POST keterangan entity.addPart("lat", new StringBody(lat)); //POST keterangan entity.addPart("lon", new StringBody(longt)); //POST keterangan post.setEntity(entity); System.out.println("post entity length " + entity.getContentLength()); ResponseHandler handler = new BasicResponseHandler(); String response = client.execute(post, handler); } catch (Exception e) { Log.e(e.getClass().getName(), e.getMessage()); } }
From source file:org.openbmap.soapclient.AsyncUploader.java
/** * Sends an authenticated http post request to upload file * @param file File to upload (full path) * @return true on response code 200, false otherwise */// w w w . j a v a 2 s. c om private UploadResult httpPostRequest(final String file) { // TODO check network state // @see http://developer.android.com/training/basics/network-ops/connecting.html // Adjust HttpClient parameters final HttpParams httpParameters = new BasicHttpParams(); // Set the timeout in milliseconds until a connection is established. // The default value is zero, that means the timeout is not used. // HttpConnectionParams.setConnectionTimeout(httpParameters, CONNECTION_TIMEOUT); // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. //HttpConnectionParams.setSoTimeout(httpParameters, SOCKET_TIMEOUT); final DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters); final HttpPost httppost = new HttpPost(mServer); try { final MultipartEntity entity = new MultipartEntity(); entity.addPart(FILE_FIELD, new FileBody(new File(file), "text/xml")); if ((mUser != null) && (mPassword != null)) { final String authorizationString = "Basic " + Base64.encodeToString((mUser + ":" + mPassword).getBytes(), Base64.NO_WRAP); httppost.setHeader("Authorization", authorizationString); } if (mToken != null) { entity.addPart(API_FIELD, new StringBody(mToken)); } httppost.setEntity(entity); final HttpResponse response = httpclient.execute(httppost); final int reply = response.getStatusLine().getStatusCode(); if (reply == 200) { // everything is ok if we receive HTTP 200 mSize = entity.getContentLength(); Log.i(TAG, "Uploaded " + file + ": Server reply " + reply); return UploadResult.OK; } else if (reply == 401) { Log.e(TAG, "Wrong username or password"); return UploadResult.WRONG_PASSWORD; } else { Log.w(TAG, "Error while uploading" + file + ": Server reply " + reply); return UploadResult.ERROR; } // TODO: redirects (301, 302) are NOT handled here // thus if something changes on the server side we're dead here } catch (final ClientProtocolException e) { Log.e(TAG, e.getMessage()); } catch (final IOException e) { Log.e(TAG, "I/O exception on file " + file); } return UploadResult.UNDEFINED; }
From source file:rapture.common.client.BaseHttpApi.java
protected String makeRequest(String fn, String request) throws ClientProtocolException, IOException { boolean notInError = true; log.trace("Entering makeRequest (" + fn + "," + request + ")"); while (notInError) { try {//w w w . j a v a2 s. c o m HttpPost httppost = new HttpPost(fullUrl); MultipartEntity entity = new MultipartEntity(); entity.addPart("FUNCTION", new StringBody(fn)); final byte[] compressedParams = getCompressedParams(request); if (compressedParams != null) { InputStreamBody isb = new InputStreamBody(new ByteArrayInputStream(compressedParams), "params.txt") { @Override public long getContentLength() { return compressedParams.length; } }; entity.addPart("PARAMS", isb); } else { entity.addPart("PARAMS", new StringBody(request)); } long length = entity.getContentLength(); // will force it to // recalculate length if (log.isDebugEnabled()) log.trace("Content Length is " + length); httppost.setEntity(entity); HttpResponse response = httpclient.execute(httppost); String responseObjectJson = inputStreamToString(response.getEntity().getContent()).toString(); return responseObjectJson; } catch (IOException e) { log.error(String.format("Got exception during makeRequest. Will try to recover.")); String oldUrl = currentUrl; stateManager.markURLBad(currentUrl); currentUrl = stateManager.getURL(); if (currentUrl == null) { String message = String.format( "Got exception accessing %s, and there are no available Rapture end points", oldUrl); throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR, message, e); } httpclient = null; setup(); } } return ""; }