List of usage examples for java.net HttpURLConnection HTTP_OK
int HTTP_OK
To view the source code for java.net HttpURLConnection HTTP_OK.
Click Source Link
From source file:com.box.androidlib.BoxFileDownload.java
/** * Execute a file download.//w ww.j ava 2s. co m * * @param fileId * The file_id of the file to be downloaded * @param destinationOutputStreams * OutputStreams to which the data should be written to as it is downloaded. * @param versionId * The version_id of the version of the file to download. Set to null to download the latest version of the file. * @return a response handler * @throws IOException * Can be thrown if there was a connection error, or if destination file could not be written. */ public DefaultResponseParser execute(final long fileId, final OutputStream[] destinationOutputStreams, final Long versionId) throws IOException { final DefaultResponseParser handler = new DefaultResponseParser(); final Uri.Builder builder = new Uri.Builder(); builder.scheme(BoxConfig.getInstance().getDownloadUrlScheme()); builder.encodedAuthority(BoxConfig.getInstance().getDownloadUrlAuthority()); builder.path(BoxConfig.getInstance().getDownloadUrlPath()); builder.appendPath(mAuthToken); builder.appendPath(String.valueOf(fileId)); if (versionId != null) { builder.appendPath(String.valueOf(versionId)); } List<BasicNameValuePair> customQueryParams = BoxConfig.getInstance().getCustomQueryParameters(); if (customQueryParams != null && customQueryParams.size() > 0) { for (BasicNameValuePair param : customQueryParams) { builder.appendQueryParameter(param.getName(), param.getValue()); } } // We normally prefer to use HttpUrlConnection, however that appears to fail for certain types of files. For downloads, it appears DefaultHttpClient // works more reliably. final DefaultHttpClient httpclient = new DefaultHttpClient(); HttpProtocolParams.setUserAgent(httpclient.getParams(), BoxConfig.getInstance().getUserAgent()); HttpGet httpGet; String theUri = builder.build().toString(); if (BoxConfig.getInstance().getHttpLoggingEnabled()) { //DevUtils.logcat("User-Agent : " + HttpProtocolParams.getUserAgent(httpclient.getParams())); DevUtils.logcat("Box Request: " + theUri); } try { httpGet = new HttpGet(new URI(theUri)); } catch (URISyntaxException e) { throw new IOException("Invalid Download URL"); } httpGet.setHeader("Connection", "close"); httpGet.setHeader("Accept-Language", BoxConfig.getInstance().getAcceptLanguage()); HttpResponse httpResponse = httpclient.execute(httpGet); int responseCode = httpResponse.getStatusLine().getStatusCode(); if (BoxConfig.getInstance().getHttpLoggingEnabled()) { DevUtils.logcat("Box Response: " + responseCode); // Header[] headers = httpResponse.getAllHeaders(); // for (Header header : headers) { // DevUtils.logcat("Response Header: " + header.toString()); // } } // Server returned a 503 Service Unavailable. Usually means a temporary unavailability. if (responseCode == HttpStatus.SC_SERVICE_UNAVAILABLE) { // if (BoxConfig.getInstance().getHttpLoggingEnabled()) { // DevUtils.logcat("HTTP Response Code: " + HttpStatus.SC_SERVICE_UNAVAILABLE); // } handler.setStatus(ResponseListener.STATUS_SERVICE_UNAVAILABLE); return handler; } InputStream is = httpResponse.getEntity().getContent(); if (responseCode == HttpURLConnection.HTTP_OK) { // Grab the first 100 bytes and check for an error string. // Not a good way for the server to respond with errors but that's the way it is for now. final byte[] errorCheckBuffer = new byte[FILE_ERROR_SIZE]; // Three cases here: error, no error && file size == 0, no error && file size > 0. // The first case will be handled by parsing the error check buffer. The second case will result in mBytesTransferred == 0, // no real bytes will be transferred but we still treat as success case. The third case is normal success case. mBytesTransferred = Math.max(0, is.read(errorCheckBuffer)); final String str = new String(errorCheckBuffer).trim(); if (str.equals(FileDownloadListener.STATUS_DOWNLOAD_WRONG_AUTH_TOKEN)) { handler.setStatus(FileDownloadListener.STATUS_DOWNLOAD_WRONG_AUTH_TOKEN); } else if (str.equals(FileDownloadListener.STATUS_DOWNLOAD_RESTRICTED)) { handler.setStatus(FileDownloadListener.STATUS_DOWNLOAD_RESTRICTED); } // No error detected else { // Copy the file to destination if > 0 bytes of file transferred. if (mBytesTransferred > 0) { for (int i = 0; i < destinationOutputStreams.length; i++) { destinationOutputStreams[i].write(errorCheckBuffer, 0, (int) mBytesTransferred); // Make sure we don't lose that first 100 bytes. } // Read the rest of the stream and write to the destination OutputStream. final byte[] buffer = new byte[DOWNLOAD_BUFFER_SIZE]; int bufferLength = 0; long lastOnProgressPost = 0; while (!Thread.currentThread().isInterrupted() && (bufferLength = is.read(buffer)) > 0) { for (int i = 0; i < destinationOutputStreams.length; i++) { destinationOutputStreams[i].write(buffer, 0, bufferLength); } mBytesTransferred += bufferLength; long currTime = SystemClock.uptimeMillis(); if (mListener != null && mHandler != null && currTime - lastOnProgressPost > ON_PROGRESS_UPDATE_THRESHOLD) { lastOnProgressPost = currTime; mHandler.post(mOnProgressRunnable); } } mHandler.post(mOnProgressRunnable); } for (int i = 0; i < destinationOutputStreams.length; i++) { destinationOutputStreams[i].close(); } handler.setStatus(FileDownloadListener.STATUS_DOWNLOAD_OK); // If download thread was interrupted, set to // STATUS_DOWNLOAD_CANCELED if (Thread.currentThread().isInterrupted()) { httpGet.abort(); handler.setStatus(FileDownloadListener.STATUS_DOWNLOAD_CANCELLED); } } } else if (responseCode == HttpURLConnection.HTTP_FORBIDDEN) { handler.setStatus(FileDownloadListener.STATUS_DOWNLOAD_PERMISSIONS_ERROR); } else { handler.setStatus(FileDownloadListener.STATUS_DOWNLOAD_FAIL); } httpResponse.getEntity().consumeContent(); if (httpclient != null && httpclient.getConnectionManager() != null) { httpclient.getConnectionManager().closeIdleConnections(500, TimeUnit.MILLISECONDS); } is.close(); return handler; }
From source file:com.upnext.blekit.util.http.HttpClient.java
public <T> Response<T> fetchResponse(Class<T> clazz, String path, Map<String, String> params, String httpMethod, String payload, String payloadContentType) { try {//w w w. ja v a 2s . c o m String fullUrl = urlWithParams(path != null ? url + path : url, params); L.d("[" + httpMethod + "] " + fullUrl); final URLConnection connection = new URL(fullUrl).openConnection(); if (connection instanceof HttpURLConnection) { final HttpURLConnection httpConnection = (HttpURLConnection) connection; httpConnection.setDoInput(true); if (httpMethod != null) { httpConnection.setRequestMethod(httpMethod); if (httpMethod.equals("POST")) { connection.setDoOutput(true); // Triggers POST. connection.setRequestProperty("Accept-Charset", "UTF-8"); connection.setRequestProperty("Content-Type", payloadContentType); } } else { httpConnection.setRequestMethod(params != null ? "POST" : "GET"); } httpConnection.addRequestProperty("Accept", "application/json"); httpConnection.connect(); if (payload != null) { OutputStream outputStream = httpConnection.getOutputStream(); try { if (LOG_RESPONSE) { L.d("[payload] " + payload); } OutputStreamWriter writer = new OutputStreamWriter(outputStream, "UTF-8"); writer.write(payload); writer.close(); } finally { outputStream.close(); } } InputStream input = null; try { input = connection.getInputStream(); } catch (IOException e) { // workaround for Android HttpURLConnection ( IOException is thrown for 40x error codes ). final int statusCode = httpConnection.getResponseCode(); if (statusCode == -1) throw e; return new Response<T>(Error.httpError(httpConnection.getResponseCode())); } final int statusCode = httpConnection.getResponseCode(); L.d("statusCode " + statusCode); if (statusCode == HttpURLConnection.HTTP_OK || statusCode == HttpURLConnection.HTTP_CREATED) { try { T value = null; if (clazz != Void.class) { if (LOG_RESPONSE || clazz == String.class) { StringBuilder sb = new StringBuilder(); BufferedReader br = new BufferedReader(new InputStreamReader(input)); String read = br.readLine(); while (read != null) { sb.append(read); read = br.readLine(); } String response = sb.toString(); if (LOG_RESPONSE) { L.d("response " + response); } if (clazz == String.class) { value = (T) response; } else { value = (T) objectMapper.readValue(response, clazz); } } else { value = (T) objectMapper.readValue(input, clazz); } } return new Response<T>(value); } catch (JsonMappingException e) { return new Response<T>(Error.serlizerError(e)); } catch (JsonParseException e) { return new Response<T>(Error.serlizerError(e)); } } else if (statusCode == HttpURLConnection.HTTP_NO_CONTENT) { try { T def = clazz.newInstance(); if (LOG_RESPONSE) { L.d("statusCode == HttpURLConnection.HTTP_NO_CONTENT"); } return new Response<T>(def); } catch (InstantiationException e) { return new Response<T>(Error.ioError(e)); } catch (IllegalAccessException e) { return new Response<T>(Error.ioError(e)); } } else { if (LOG_RESPONSE) { L.d("error, statusCode " + statusCode); } return new Response<T>(Error.httpError(statusCode)); } } return new Response<T>(Error.ioError(new Exception("Url is not a http link"))); } catch (IOException e) { if (LOG_RESPONSE) { L.d("error, ioError " + e); } return new Response<T>(Error.ioError(e)); } }
From source file:bluevia.InitService.java
void doPolling() { Thread threadPoller = ThreadManager.createBackgroundThread(new Runnable() { public void run() { String consumer_key = Util.BlueViaOAuth.consumer_key; String consumer_secret = Util.BlueViaOAuth.consumer_secret; BufferedReader br = null; int countryIndex = 0; String[] countryURIs = { MO_URI_UK, MO_URI_SP, MO_URI_GE, MO_URI_BR, MO_URI_MX, MO_URI_AR, MO_URI_CH, MO_URI_CO }; while (true) { try { com.google.appengine.api.urlfetch.FetchOptions.Builder.doNotValidateCertificate(); OAuthConsumer consumer = (OAuthConsumer) new DefaultOAuthConsumer(consumer_key, consumer_secret); consumer.setMessageSigner(new HmacSha1MessageSigner()); URL apiURI = new URL(countryURIs[countryIndex]); countryIndex = (countryIndex + 1) % countryURIs.length; int rc = 0; HttpURLConnection request = (HttpURLConnection) apiURI.openConnection(); request.setRequestMethod("GET"); consumer.sign(request); rc = request.getResponseCode(); if (rc == HttpURLConnection.HTTP_OK) { br = new BufferedReader(new InputStreamReader(request.getInputStream())); StringBuffer doc = new StringBuffer(); String line; do { line = br.readLine(); if (line != null) doc.append(line); } while (line != null); DatastoreService datastore = Util.getDatastoreServiceInstance(); Transaction txn = datastore.beginTransaction(); try { JSONObject apiResponse; JSONObject smsPool; JSONArray smsInfo; apiResponse = new JSONObject(doc.toString()); if (apiResponse.getString("receivedSMS") != null) { String szMessage; String szOrigin; String szDate; smsPool = apiResponse.getJSONObject("receivedSMS"); smsInfo = smsPool.optJSONArray("receivedSMS"); if (smsInfo != null) { for (int i = 0; i < smsInfo.length(); i++) { szMessage = smsInfo.getJSONObject(i).getString("message"); szOrigin = smsInfo.getJSONObject(i).getJSONObject("originAddress") .getString("phoneNumber"); szDate = smsInfo.getJSONObject(i).getString("dateTime"); StringTokenizer msgParser = new StringTokenizer(szMessage); // Removing app id msgParser.nextToken(); String userAlias = msgParser.nextToken(); String msg = ""; while (msgParser.hasMoreTokens()) msg += " " + msgParser.nextToken(); String userEmail = (String) Util.getUserWithAlias(userAlias) .getProperty("mail"); if (userEmail != null) { Util.addUserMessage(userEmail, szOrigin, msg, szDate); SendSMS.setTwitterStatus(userEmail, msg); SendSMS.setFacebookWallPost(userEmail, msg); } }//from ww w .j av a 2s.c o m } else { JSONObject sms = smsPool.getJSONObject("receivedSMS"); szMessage = sms.getString("message"); szOrigin = sms.getJSONObject("originAddress").getString("phoneNumber"); szDate = sms.getString("dateTime"); StringTokenizer msgParser = new StringTokenizer(szMessage); // Removing app id msgParser.nextToken(); String userAlias = msgParser.nextToken(); String msg = ""; while (msgParser.hasMoreTokens()) msg += " " + msgParser.nextToken(); Util.addUserMessage(userAlias, szOrigin, msg, szDate); } } else { logger.warning("No messages"); if (txn.isActive()) txn.rollback(); } } catch (JSONException e) { logger.severe(e.getMessage()); } catch (Exception e) { logger.severe(e.getMessage()); } finally { if (txn.isActive()) txn.rollback(); } } else if (rc == HttpURLConnection.HTTP_NO_CONTENT) { //log.warning(String.format("No content from: %s", apiURI.getPath())); } else logger.severe(String.format("%d: %s", rc, request.getResponseMessage())); } catch (Exception e) { logger.severe(e.getMessage()); } Thread.currentThread(); try { Thread.sleep(150000); } catch (InterruptedException e) { e.printStackTrace(); logger.severe(String.format("%s", e.getMessage())); } } } }); threadPoller.start(); }
From source file:mobi.jenkinsci.alm.assembla.client.AssemblaClient.java
public void loginRefresh() throws IOException { if (accessToken == null) { login();/*from w w w . j a v a 2s .c o m*/ } else { accessToken.access_token = ""; final HttpPost authPost = new HttpPost(String.format(ASSEMBLA_SITE_APP_AUTH, appId, appSecret) + String.format(TOKEN_REFRESH, accessToken.refresh_token)); final HttpResponse response = httpClient.execute(authPost); try { if (response.getStatusLine().getStatusCode() != HttpURLConnection.HTTP_OK) { throw new IOException( "Post " + authPost.getURI() + " for Token refresh failed: " + response.getStatusLine()); } final AssemblaAccessToken refreshToken = gson.fromJson( new JsonReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8")), AssemblaAccessToken.class); accessToken.renew(refreshToken); } finally { authPost.releaseConnection(); } } }
From source file:com.mobile.natal.natalchart.NetworkUtilities.java
/** * Sends a string via POST to a given url. * * @param context the context to use. * @param urlStr the url to which to send to. * @param string the string to send as post body. * @param user the user or <code>null</code>. * @param password the password or <code>null</code>. * @param readResponse if <code>true</code>, the response from the server is read and parsed as return message. * @return the response./*from ww w .j a va2 s . c om*/ * @throws Exception if something goes wrong. */ public static String sendPost(Context context, String urlStr, String string, String user, String password, boolean readResponse) throws Exception { BufferedOutputStream wr = null; HttpURLConnection conn = null; try { conn = makeNewConnection(urlStr); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true); // conn.setChunkedStreamingMode(0); conn.setUseCaches(false); if (user != null && password != null && user.trim().length() > 0 && password.trim().length() > 0) { conn.setRequestProperty("Authorization", getB64Auth(user, password)); } conn.connect(); // Make server believe we are form data... wr = new BufferedOutputStream(conn.getOutputStream()); byte[] bytes = string.getBytes(); wr.write(bytes); wr.flush(); int responseCode = conn.getResponseCode(); if (readResponse) { StringBuilder returnMessageBuilder = new StringBuilder(); if (responseCode == HttpURLConnection.HTTP_OK) { BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8")); while (true) { String line = br.readLine(); if (line == null) break; returnMessageBuilder.append(line + "\n"); } br.close(); } return returnMessageBuilder.toString(); } else { return getMessageForCode(context, responseCode, context.getResources().getString(R.string.post_completed_properly)); } } catch (Exception e) { throw e; } finally { if (conn != null) conn.disconnect(); } }
From source file:com.mobile.godot.core.controller.CoreController.java
public synchronized void findCarByDriver(String username) { String servlet = "FindCarByDriver"; List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>(); params.add(new BasicNameValuePair("username", username)); SparseIntArray mMessageMap = new SparseIntArray(); mMessageMap.append(HttpURLConnection.HTTP_OK, GodotMessage.Entity.CAR_BY_DRIVER_FOUND); mMessageMap.append(HttpURLConnection.HTTP_NOT_FOUND, GodotMessage.Error.NOT_FOUND); GodotAction action = new GodotAction(servlet, params, mMessageMap, mHandler); Thread tAction = new Thread(action); tAction.start();/* w w w . ja va 2s . com*/ }
From source file:com.microsoft.azuretools.utils.WebAppUtils.java
public static boolean isUrlAccessible(String url) throws IOException { HttpURLConnection.setFollowRedirects(false); HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection(); con.setRequestMethod("HEAD"); con.setReadTimeout(Constants.connection_read_timeout_ms); try {/*from ww w . ja v a 2 s .c om*/ if (con.getResponseCode() != HttpURLConnection.HTTP_OK) { return false; } } catch (IOException ex) { return false; } return true; }
From source file:net.sbbi.upnp.messages.StateVariableMessage.java
/** * Executes the state variable query and retuns the UPNP device response, according to the UPNP specs, * this method could take up to 30 secs to process ( time allowed for a device to respond to a request ) * @return a state variable response object containing the variable value * @throws IOException if some IOException occurs during message send and reception process * @throws UPNPResponseException if an UPNP error message is returned from the server * or if some parsing exception occurs ( detailErrorCode = 899, detailErrorDescription = SAXException message ) */// w ww .j a v a 2 s . c o m public StateVariableResponse service() throws IOException, UPNPResponseException { StateVariableResponse rtrVal = null; UPNPResponseException upnpEx = null; IOException ioEx = null; StringBuffer body = new StringBuffer(256); body.append("<?xml version=\"1.0\"?>\r\n"); body.append("<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\""); body.append(" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"); body.append("<s:Body>"); body.append("<u:QueryStateVariable xmlns:u=\"urn:schemas-upnp-org:control-1-0\">"); body.append("<u:varName>").append(serviceStateVar.getName()).append("</u:varName>"); body.append("</u:QueryStateVariable>"); body.append("</s:Body>"); body.append("</s:Envelope>"); if (log.isDebugEnabled()) log.debug("POST prepared for URL " + service.getControlURL()); URL url = new URL(service.getControlURL().toString()); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); HttpURLConnection.setFollowRedirects(false); //conn.setConnectTimeout( 30000 ); conn.setRequestProperty("HOST", url.getHost() + ":" + url.getPort()); conn.setRequestProperty("SOAPACTION", "\"urn:schemas-upnp-org:control-1-0#QueryStateVariable\""); conn.setRequestProperty("CONTENT-TYPE", "text/xml; charset=\"utf-8\""); conn.setRequestProperty("CONTENT-LENGTH", Integer.toString(body.length())); OutputStream out = conn.getOutputStream(); out.write(body.toString().getBytes()); out.flush(); conn.connect(); InputStream input = null; if (log.isDebugEnabled()) log.debug("executing query :\n" + body); try { input = conn.getInputStream(); } catch (IOException ex) { // java can throw an exception if he error code is 500 or 404 or something else than 200 // but the device sends 500 error message with content that is required // this content is accessible with the getErrorStream input = conn.getErrorStream(); } if (input != null) { int response = conn.getResponseCode(); String responseBody = getResponseBody(input); if (log.isDebugEnabled()) log.debug("received response :\n" + responseBody); SAXParserFactory saxParFact = SAXParserFactory.newInstance(); saxParFact.setValidating(false); saxParFact.setNamespaceAware(true); StateVariableResponseParser msgParser = new StateVariableResponseParser(serviceStateVar); StringReader stringReader = new StringReader(responseBody); InputSource src = new InputSource(stringReader); try { SAXParser parser = saxParFact.newSAXParser(); parser.parse(src, msgParser); } catch (ParserConfigurationException confEx) { // should never happen // we throw a runtimeException to notify the env problem throw new RuntimeException( "ParserConfigurationException during SAX parser creation, please check your env settings:" + confEx.getMessage()); } catch (SAXException saxEx) { // kind of tricky but better than nothing.. upnpEx = new UPNPResponseException(899, saxEx.getMessage()); } finally { try { input.close(); } catch (IOException ex) { // ignoring } } if (upnpEx == null) { if (response == HttpURLConnection.HTTP_OK) { rtrVal = msgParser.getStateVariableResponse(); } else if (response == HttpURLConnection.HTTP_INTERNAL_ERROR) { upnpEx = msgParser.getUPNPResponseException(); } else { ioEx = new IOException("Unexpected server HTTP response:" + response); } } } try { out.close(); } catch (IOException ex) { // ignore } conn.disconnect(); if (upnpEx != null) { throw upnpEx; } if (rtrVal == null && ioEx == null) { ioEx = new IOException("Unable to receive a response from the UPNP device"); } if (ioEx != null) { throw ioEx; } return rtrVal; }
From source file:org.eclipse.hono.deviceregistry.FileBasedTenantService.java
TenantResult<JsonObject> getTenantResult(final String tenantId) { final TenantObject tenant = tenants.get(tenantId); if (tenant == null) { return TenantResult.from(HttpURLConnection.HTTP_NOT_FOUND); } else {//w w w . j a v a2s . c o m return TenantResult.from(HttpURLConnection.HTTP_OK, JsonObject.mapFrom(tenant), CacheDirective.maxAgeDirective(MAX_AGE_GET_TENANT)); } }
From source file:com.freshplanet.ane.GoogleCloudStorageUpload.tasks.UploadToGoogleCloudStorageAsyncTask.java
@Override protected String doInBackground(String... urls) { Log.d(TAG, "[UploadToGoogleCloudStorageAsyncTask] Entering doInBackground()"); byte[] result = null; HttpPost post = new HttpPost(urls[0]); try {/*from ww w . j a v a 2s .co m*/ Log.d(TAG, "[UploadToGoogleCloudStorageAsyncTask] ~~~ DBG: Prepare for httpPostData"); // prepare for httpPost data String boundary = "b0undaryFP"; Log.d(TAG, "[UploadToGoogleCloudStorageAsyncTask] ~~~ DBG: build the data"); // build the data byte[] bytes = null; byte[] imageBytes = null; if (isImage) { // Get the byte[] of the media we want to upload imageBytes = getImageByteArray(mediaPath); imageBytes = resizeImage(imageBytes, maxWidth, maxHeight); } //all the stuff that comes before the media bytes ByteArrayOutputStream preMedia = new ByteArrayOutputStream(); for (@SuppressWarnings("unchecked") Iterator<String> keys = uploadParams.keys(); keys.hasNext();) { String key = keys.next(); String value = uploadParams.getString(key); preMedia.write(("\r\n--%@\r\n".replace("%@", boundary)).getBytes()); preMedia.write(("Content-Disposition: form-data; name=\"%@\"\r\n\r\n%@".replaceFirst("%@", key) .replaceFirst("%@", value)).getBytes()); } preMedia.write(("\r\n--%@\r\n".replace("%@", boundary)).getBytes()); preMedia.write(("Content-Disposition: form-data; name=\"file\"; filename=\"file\"\r\n\r\n").getBytes()); //all the stuff that comes after the media bytes ByteArrayOutputStream postMedia = new ByteArrayOutputStream(); postMedia.write(("\r\n--%@\r\n".replace("%@", boundary)).getBytes()); Log.d(TAG, "[UploadToGoogleCloudStorageAsyncTask] ~~~ DBG: Set content-type and content of http post"); // Set content-type and content of http post post.setHeader("Content-Type", "multipart/form-data; boundary=" + boundary); if (isImage && imageBytes != null) bytes = createHeaderByteArrayImage(preMedia.toByteArray(), postMedia.toByteArray(), imageBytes); else bytes = createHeaderByteArrayFile(preMedia.toByteArray(), postMedia.toByteArray(), mediaPath); preMedia.close(); postMedia.close(); if (isVideo) { if (bytes.length > maxDuration * 1000 * 1000) { status = "FILE_TOO_BIG"; return null; } } if (bytes == null) { status = "ERROR_CREATING_HEADER"; return null; } ByteArrayEntity entity = new ByteArrayEntity(bytes) { @Override public void writeTo(final OutputStream outstream) throws IOException { if (outstream == null) { throw new IllegalArgumentException("Output stream may not be null"); } InputStream instream = new ByteArrayInputStream(this.content); try { byte[] tmp = new byte[512]; int total = (int) this.content.length; int progress = 0; int increment = 0; int l; int percent; while ((l = instream.read(tmp)) != -1) { progress = progress + l; percent = Math.round(((float) progress / (float) total) * 100); if (percent > increment) { increment += 10; // update percentage here !! } double percentage = (double) percent / 100.0; GoogleCloudStorageUploadExtension.context .dispatchStatusEventAsync("FILE_UPLOAD_PROGRESS", "" + percentage); outstream.write(tmp, 0, l); } outstream.flush(); } catch (Exception e) { e.printStackTrace(); } finally { instream.close(); } } }; post.setEntity(entity); Log.d(TAG, "[UploadToGoogleCloudStorageAsyncTask] ~~~ DBG: execute post."); // execute post. HttpResponse httpResponse = client.execute(post); StatusLine statusResponse = httpResponse.getStatusLine(); if (statusResponse.getStatusCode() == HttpURLConnection.HTTP_OK) { result = EntityUtils.toByteArray(httpResponse.getEntity()); response = new String(result, "UTF-8"); Log.d(TAG, "[UploadToGoogleCloudStorageAsyncTask] ~~~ DBG: got a response: " + response); status = "FILE_UPLOAD_DONE"; } else { status = "FILE_UPLOAD_ERROR"; Log.d(TAG, "[UploadToGoogleCloudStorageAsyncTask] ~~~ ERR: status code: " + statusResponse.toString()); } } catch (JSONException e) { e.printStackTrace(); status = "FILE_UPLOAD_ERROR"; } catch (ClientProtocolException e) { e.printStackTrace(); status = "FILE_UPLOAD_ERROR"; } catch (IOException e) { e.printStackTrace(); status = "FILE_UPLOAD_ERROR"; } catch (Exception e) { e.printStackTrace(); status = "UNKNOWN_ERROR"; } Log.d(TAG, "[UploadToGoogleCloudStorageAsyncTask] Exiting doInBackground()"); return response; }