Example usage for org.apache.http.client.methods HttpPost getMethod

List of usage examples for org.apache.http.client.methods HttpPost getMethod

Introduction

In this page you can find the example usage for org.apache.http.client.methods HttpPost getMethod.

Prototype

@Override
    public String getMethod() 

Source Link

Usage

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.//  w w w.  j  a v a 2 s.c  o  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.ibm.sbt.security.authentication.oauth.consumer.HMACOAuth1Handler.java

@Override
public void getAccessTokenFromServer() throws OAuthException {

    int responseCode = HttpStatus.SC_OK;
    String responseBody = null;//from ww w  . ja  va2 s . c  o  m
    try {
        HttpClient client = new DefaultHttpClient();
        if (getForceTrustSSLCertificate()) {
            client = SSLUtil.wrapHttpClient((DefaultHttpClient) client);
        }

        StringBuilder requestPostUrl = new StringBuilder(getAccessTokenURL());
        // adding the oauth_verifier to the request.
        requestPostUrl.append("?");
        requestPostUrl.append(Configuration.OAUTH_VERIFIER).append('=')
                .append(URLEncoder.encode(verifierCode, "UTF-8"));
        HttpPost method = new HttpPost(requestPostUrl.toString());
        // Collecting parameters for preparing the Signature
        String consumerKey = getConsumerKey();
        String requestToken = getRequestToken();
        String nonce = getNonce();
        String timeStamp = getTimestamp();
        /*
         * Generate a map of parameters which are required for creating signature. We are using a Linked
         * HashMap to preserver the order in which parameters are added to the Map, as the parameters need
         * to be sorted for Twitter Signature generation.
         */
        LinkedHashMap<String, String> signatureParamsMap = new LinkedHashMap<String, String>();
        signatureParamsMap.put(Configuration.CONSUMER_KEY, consumerKey);
        signatureParamsMap.put(Configuration.NONCE, nonce);
        signatureParamsMap.put(Configuration.OAUTH_TOKEN, requestToken);
        signatureParamsMap.put(Configuration.SIGNATURE_METHOD, getSignatureMethod());
        signatureParamsMap.put(Configuration.TIMESTAMP, timeStamp);
        signatureParamsMap.put(Configuration.VERSION, Configuration.OAUTH_VERSION1);

        String requestTokenSecret = getRequestTokenSecret();
        String consumerSecret = getConsumerSecret();
        String signature = HMACEncryptionUtility.generateHMACSignature(requestPostUrl.toString(),
                method.getMethod(), consumerSecret, requestTokenSecret, signatureParamsMap);

        // Preparing the Header for getting access token
        StringBuilder headerStr = new StringBuilder();

        headerStr.append("OAuth ").append(Configuration.CONSUMER_KEY).append("=\"").append(consumerKey)
                .append("\"");
        headerStr.append(",").append(Configuration.SIGNATURE_METHOD).append("=\"").append(getSignatureMethod())
                .append("\"");
        headerStr.append(",").append(Configuration.TIMESTAMP).append("=\"").append(timeStamp).append("\"");
        headerStr.append(",").append(Configuration.NONCE).append("=\"").append(nonce).append("\"");
        headerStr.append(",").append(Configuration.VERSION).append("=\"").append(Configuration.OAUTH_VERSION1)
                .append("\"");
        // This is the request token which is obtained from getRequestTokenFromServer() method.
        headerStr.append(",").append(Configuration.OAUTH_TOKEN).append("=\"").append(requestToken).append("\"");
        headerStr.append(",").append(Configuration.SIGNATURE).append("=\"")
                .append(URLEncoder.encode(signature, "UTF-8")).append("\"");
        method.setHeader("Authorization", headerStr.toString());

        method.setHeader("Authorization", headerStr.toString());

        HttpResponse httpResponse = client.execute(method);
        responseCode = httpResponse.getStatusLine().getStatusCode();
        InputStream content = httpResponse.getEntity().getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(content));
        try {
            responseBody = StreamUtil.readString(reader);
        } finally {
            StreamUtil.close(reader);
        }

    } catch (Exception e) {
        throw new OAuthException(e, "Internal error - getAccessToken failed Exception: ");
    }
    if (responseCode != HttpStatus.SC_OK) {
        String exceptionDetail = buildErrorMessage(responseCode, responseBody);
        if (exceptionDetail != null) {
            throw new OAuthException(null,
                    "HMACOAuth1Handler.java : getAccessTokenFromServer failed. " + exceptionDetail);
        }
    } else {
        /*
         * Response from twitter contains Access Token, Access Token Secret, User Id and Screen Name of
         * the Application.
         */
        setAccessToken(getTokenValue(responseBody, Configuration.OAUTH_TOKEN));
        setAccessTokenSecret(getTokenValue(responseBody, Configuration.OAUTH_TOKEN_SECRET));
    }
}

From source file:org.wso2.carbon.appfactory.jenkins.build.RestBasedJenkinsCIConnector.java

/**
 * When jenkins tenant is unloaded the requests cannot be fulfilled. So this
 * method will be used to resend the Post requests
 *
 * @param method       method to be retried
 * @param httpResponse http response of the previous request
 * @return httpStatusCode//from ww  w  .  j ava  2 s .co m
 */
private HttpResponse resendRequest(HttpPost method, HttpResponse httpResponse) throws AppFactoryException {

    int httpStatusCode;
    int retryCount = Integer.parseInt(AppFactoryUtil.getAppfactoryConfiguration()
            .getFirstProperty(JenkinsCIConstants.JENKINS_CLIENT_RETRY_COUNT));
    int retryDelay = Integer.parseInt(AppFactoryUtil.getAppfactoryConfiguration()
            .getFirstProperty(JenkinsCIConstants.JENKINS_CLIENT_RETRY_DELAY));
    log.info("Jenkins client retry count :" + retryCount + " and retry delay in seconds :" + retryDelay
            + " for " + method.getMethod());
    try {
        // retry retryCount times to process the request
        for (int i = 0; i < retryCount; i++) {
            Thread.sleep(MILLISECONDS_PER_SECOND * retryDelay); // sleep retryDelay seconds, giving jenkins
            // time to load the tenant
            if (log.isDebugEnabled()) {
                log.debug("Resending request(" + i + ") started for POST");
            }
            if (httpResponse != null) {
                EntityUtils.consume(httpResponse.getEntity());
            }
            HttpContext httpContext = getHttpContext();
            httpResponse = httpClient.execute(method, httpContext);
            httpStatusCode = httpResponse.getStatusLine().getStatusCode();
            // In the new jenkins release the response is always 201 or 302
            if (HttpStatus.SC_OK == httpStatusCode || HttpStatus.SC_CREATED == httpStatusCode
                    || HttpStatus.SC_MOVED_TEMPORARILY == httpStatusCode) {
                if (log.isDebugEnabled()) {
                    log.debug("Break resending since " + httpStatusCode);
                }
                break;
            }
            if (log.isDebugEnabled()) {
                log.debug("Resent POST request(" + i + ") failed with response code " + httpStatusCode);
            }
        }
    } catch (IOException e) {
        String msg = "Error while resending the request to URI : " + method.getURI();
        log.error(msg, e);
        throw new AppFactoryException(msg, e);
    } catch (InterruptedException e) {
        String msg = "Error while resending the request to URI : " + method.getURI();
        log.error(msg, e);
        throw new AppFactoryException(msg, e);
    }
    return httpResponse;
}

From source file:org.csp.everyaware.internet.StoreAndForwardService.java

/********************** SEND DATA TO SERVER *******************************************************/

//create an array of json objects containing records, compress it in gzip http compression format and send it to server
public int postData()
        throws IllegalArgumentException, ClientProtocolException, HttpHostConnectException, IOException {
    Log.d("StoreAndForwardService", "postData()");

    //get size of array of records to send and reference to the last record
    int size = mToSendRecords.size();
    if (size == 0)
        return -1;

    int sepIndex = 1; //default is '.' separator (see Constants.separators array)
    if ((Utils.report_country != null) && (Utils.report_country.equals("IT")))
        sepIndex = 0; //0 is for '-' separator (for italian CSP server)

    Record lastToSendRecord = mToSendRecords.get(size - 1);
    Log.d("StoreAndForwardService", "postData()--> # of records: " + size);

    //save timestamp
    long lastTimestamp = 0;
    if (lastToSendRecord.mSysTimestamp > 0)
        lastTimestamp = lastToSendRecord.mSysTimestamp;
    else/*  ww w . j a  v  a 2s  .  co  m*/
        lastTimestamp = lastToSendRecord.mBoxTimestamp;

    String lastTsFormatted = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss.SSSz", Locale.US)
            .format(new Date(lastTimestamp));

    //********* MAKING OF HTTP HEADER **************

    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(Utils.report_url);

    httpPost.setHeader("Content-Encoding", "gzip");
    httpPost.setHeader("Content-Type", "application/json");
    httpPost.setHeader("Accept", "application/json");
    httpPost.setHeader("User-Agent", "AirProbe" + Utils.appVer);

    //******** authorization bearer header ********

    //air probe can be used also anymously. If account activation state is true (--> AirProbe activated) add this header
    if (Utils.getAccountActivationState(getApplicationContext()))
        httpPost.setHeader("Authorization", "Bearer " + Utils.getAccessToken(getApplicationContext()));

    //******** meta header (for new version API V1)

    httpPost.setHeader("meta" + Constants.separators[sepIndex] + "timestampRecorded", lastTsFormatted);
    //httpPost.setHeader("meta"+Constants.separators[sepIndex]+"sessionId", lastToSendRecord.mSessionId); //deprecated from AP 1.4
    httpPost.setHeader("meta" + Constants.separators[sepIndex] + "deviceId", Utils.deviceID);
    httpPost.setHeader("meta" + Constants.separators[sepIndex] + "installId", Utils.installID);
    //httpPost.setHeader("meta"+Constants.separators[sepIndex]+"userFeedId", "");
    //httpPost.setHeader("meta"+Constants.separators[sepIndex]+"eventFeedId", "");
    httpPost.setHeader("meta" + Constants.separators[sepIndex] + "visibilityEvent",
            Constants.DATA_VISIBILITY[0]);
    httpPost.setHeader("meta" + Constants.separators[sepIndex] + "visibilityGlobal",
            Constants.DATA_VISIBILITY[0]); //set meta.visibilityGlobal=DETAILS for testing (to retrieve data after insertion)

    /* from AP 1.4 */
    if ((lastToSendRecord.mBoxMac != null) && (!lastToSendRecord.mBoxMac.equals(""))) {
        httpPost.setHeader("meta" + Constants.separators[sepIndex] + "sourceId", lastToSendRecord.mBoxMac);
    }

    httpPost.setHeader("meta" + Constants.separators[sepIndex] + "sourceSessionId"
            + Constants.separators[sepIndex] + "seed", lastToSendRecord.mSourceSessionSeed);
    httpPost.setHeader("meta" + Constants.separators[sepIndex] + "sourceSessionId"
            + Constants.separators[sepIndex] + "number", String.valueOf(lastToSendRecord.mSourceSessionNumber));
    httpPost.setHeader("meta" + Constants.separators[sepIndex] + "sourceSessionPointNumber",
            String.valueOf(lastToSendRecord.mSourcePointNumber));

    if ((lastToSendRecord.mSemanticSessionSeed != null)
            && (!lastToSendRecord.mSemanticSessionSeed.equals(""))) {
        httpPost.setHeader("meta" + Constants.separators[sepIndex] + "semanticSessionId"
                + Constants.separators[sepIndex] + "seed", lastToSendRecord.mSemanticSessionSeed);
        httpPost.setHeader("meta" + Constants.separators[sepIndex] + "semanticSessionId"
                + Constants.separators[sepIndex] + "number",
                String.valueOf(lastToSendRecord.mSemanticSessionNumber));
        httpPost.setHeader("meta" + Constants.separators[sepIndex] + "semanticSessionPointNumber",
                String.valueOf(lastToSendRecord.mSemanticPointNumber));
    }

    httpPost.setHeader("data" + Constants.separators[sepIndex] + "contentDetails"
            + Constants.separators[sepIndex] + "typeVersion", "30"); //update by increment this field on header changes

    /* end of from AP 1.4 */

    //******** data header (for new version API V1)

    httpPost.setHeader("data" + Constants.separators[sepIndex] + "contentDetails"
            + Constants.separators[sepIndex] + "type", "airprobe_report");
    httpPost.setHeader("data" + Constants.separators[sepIndex] + "contentDetails"
            + Constants.separators[sepIndex] + "format", "json");
    //httpPost.setHeader("data"+Constants.separators[sepIndex]+"contentDetails"+Constants.separators[sepIndex]+"specification", "a-3"); //deprecated from ap v1.4  
    if (size > 1)
        httpPost.setHeader("data" + Constants.separators[sepIndex] + "contentDetails"
                + Constants.separators[sepIndex] + "list", "true");
    else
        httpPost.setHeader("data" + Constants.separators[sepIndex] + "contentDetails"
                + Constants.separators[sepIndex] + "list", "false");
    httpPost.setHeader("data" + Constants.separators[sepIndex] + "contentDetails"
            + Constants.separators[sepIndex] + "listSize", String.valueOf(size));

    //******** geo header (for new version API V1)

    //add the right provider to header
    if (lastToSendRecord.mGpsProvider.equals(Constants.GPS_PROVIDERS[0])) //sensor box
    {
        httpPost.setHeader("geo" + Constants.separators[sepIndex] + "longitude",
                String.valueOf(lastToSendRecord.mBoxLon));
        httpPost.setHeader("geo" + Constants.separators[sepIndex] + "latitude",
                String.valueOf(lastToSendRecord.mBoxLat));
        if (lastToSendRecord.mBoxAcc != 0)
            httpPost.setHeader("geo" + Constants.separators[sepIndex] + "hdop",
                    String.valueOf(lastToSendRecord.mBoxAcc)); //from AP 1.4
        if (lastToSendRecord.mBoxAltitude != 0)
            httpPost.setHeader("geo" + Constants.separators[sepIndex] + "altitude",
                    String.valueOf(lastToSendRecord.mBoxAltitude)); //from AP 1.4
        if (lastToSendRecord.mBoxSpeed != 0)
            httpPost.setHeader("geo" + Constants.separators[sepIndex] + "speed",
                    String.valueOf(lastToSendRecord.mBoxSpeed)); //from AP 1.4
        if (lastToSendRecord.mBoxBear != 0)
            httpPost.setHeader("geo" + Constants.separators[sepIndex] + "bearing",
                    String.valueOf(lastToSendRecord.mBoxBear)); //from AP 1.4           
        httpPost.setHeader("geo" + Constants.separators[sepIndex] + "provider", lastToSendRecord.mGpsProvider);
        httpPost.setHeader("geo" + Constants.separators[sepIndex] + "timestamp", lastTsFormatted);
    } else if (lastToSendRecord.mGpsProvider.equals(Constants.GPS_PROVIDERS[1])) //phone
    {
        httpPost.setHeader("geo" + Constants.separators[sepIndex] + "longitude",
                String.valueOf(lastToSendRecord.mPhoneLon));
        httpPost.setHeader("geo" + Constants.separators[sepIndex] + "latitude",
                String.valueOf(lastToSendRecord.mPhoneLat));
        if (lastToSendRecord.mPhoneAcc != 0)
            httpPost.setHeader("geo" + Constants.separators[sepIndex] + "accuracy",
                    String.valueOf(lastToSendRecord.mPhoneAcc));
        if (lastToSendRecord.mPhoneAltitude != 0)
            httpPost.setHeader("geo" + Constants.separators[sepIndex] + "altitude",
                    String.valueOf(lastToSendRecord.mPhoneAltitude)); //from AP 1.4
        if (lastToSendRecord.mPhoneSpeed != 0)
            httpPost.setHeader("geo" + Constants.separators[sepIndex] + "speed",
                    String.valueOf(lastToSendRecord.mPhoneSpeed)); //from AP 1.4
        if (lastToSendRecord.mPhoneBear != 0)
            httpPost.setHeader("geo" + Constants.separators[sepIndex] + "bearing",
                    String.valueOf(lastToSendRecord.mPhoneBear)); //from AP 1.4
        httpPost.setHeader("geo" + Constants.separators[sepIndex] + "provider", lastToSendRecord.mGpsProvider);
        httpPost.setHeader("geo" + Constants.separators[sepIndex] + "timestamp", lastTsFormatted);
    } else if (lastToSendRecord.mGpsProvider.equals(Constants.GPS_PROVIDERS[2])) //network
    {
        httpPost.setHeader("geo" + Constants.separators[sepIndex] + "longitude",
                String.valueOf(lastToSendRecord.mNetworkLon));
        httpPost.setHeader("geo" + Constants.separators[sepIndex] + "latitude",
                String.valueOf(lastToSendRecord.mNetworkLat));
        if (lastToSendRecord.mNetworkAcc != 0)
            httpPost.setHeader("geo" + Constants.separators[sepIndex] + "accuracy",
                    String.valueOf(lastToSendRecord.mNetworkAcc));
        if (lastToSendRecord.mNetworkAltitude != 0)
            httpPost.setHeader("geo" + Constants.separators[sepIndex] + "altitude",
                    String.valueOf(lastToSendRecord.mNetworkAltitude)); //from AP 1.4
        if (lastToSendRecord.mNetworkSpeed != 0)
            httpPost.setHeader("geo" + Constants.separators[sepIndex] + "speed",
                    String.valueOf(lastToSendRecord.mNetworkSpeed)); //from AP 1.4
        if (lastToSendRecord.mNetworkBear != 0)
            httpPost.setHeader("geo" + Constants.separators[sepIndex] + "bearing",
                    String.valueOf(lastToSendRecord.mNetworkBear)); //from AP 1.4            
        httpPost.setHeader("geo" + Constants.separators[sepIndex] + "provider", lastToSendRecord.mGpsProvider);
        httpPost.setHeader("geo" + Constants.separators[sepIndex] + "timestamp", lastTsFormatted);
    }

    //******** MAKING OF HTTP CONTENT (JSON) *************

    //writing string content as an array of json object
    StringBuilder sb = new StringBuilder();
    sb.append("[");

    for (int i = 0; i < mToSendRecords.size(); i++) {
        sb.append(mToSendRecords.get(i).toJson().toString());
        if ((size != 0) && (i != size - 1))
            sb.append(",");
        sb.append("\n");
    }
    sb.append("]");

    Log.d("StoreAndForwardService", "postData()--> json: " + sb.toString());
    Log.d("StoreAndForwardService",
            "postData()--> access token: " + Utils.getAccessToken(getApplicationContext()));

    //compress json content into byte array entity
    byte[] contentGzippedBytes = zipStringToBytes(sb.toString());
    ByteArrayEntity byteArrayEntity = new ByteArrayEntity(contentGzippedBytes);
    byteArrayEntity.setChunked(false); //IMPORTANT: put false for smartcity.csp.it server

    httpPost.setEntity(byteArrayEntity);

    Log.d("StoreAndForwardService", "postData()--> Content length: " + httpPost.getEntity().getContentLength());
    Log.d("StoreAndForwardService", "postData()--> Method: " + httpPost.getMethod());

    //do http post (it performs asynchronously)
    HttpResponse response = httpClient.execute(httpPost);

    sb = null;

    //server response
    Log.d("StoreAndForwardService", "postData()--> status line: " + response.getStatusLine());

    httpClient.getConnectionManager().shutdown();

    //server response, status line
    StatusLine statusLine = response.getStatusLine();
    Log.d("StoreAndForwardService", "postData()--> status code: " + statusLine.getStatusCode());
    return statusLine.getStatusCode();
}

From source file:org.csp.everyaware.internet.StoreAndForwardService.java

public void postTags()
        throws IllegalArgumentException, ClientProtocolException, HttpHostConnectException, IOException {
    Log.d("StoreAndForwardService", "postTags()");

    int sepIndex = 1; //default is '.' separator (see Constants.separators array)
    if ((Utils.report_country != null) && (Utils.report_country.equals("IT")))
        sepIndex = 0; //0 is for '-' separator (for italian CSP server)

    List<String> sids = mDbManager.getSidsOfRecordsWithTags();

    if ((sids != null) && (sids.size() > 0)) {
        for (int i = 0; i < sids.size(); i++) {
            String sessionId = (String) sids.get(i);

            //load records containing user tags with actual session id
            List<Record> recordsWithTags = mDbManager.loadRecordsWithTagBySessionId(sessionId);

            if ((recordsWithTags != null) && (recordsWithTags.size() > 0)) {
                //get size of array of records containing tags and reference to the last record
                int size = recordsWithTags.size();

                //obtain reference to the last record of serie
                Record lastToSendRecord = recordsWithTags.get(size - 1);
                Log.d("StoreAndForwardService", "postTags()--> # of records containing tags: " + size);

                //save timestamp of last record containing tags
                long lastTimestamp = 0;
                if (lastToSendRecord.mSysTimestamp > 0)
                    lastTimestamp = lastToSendRecord.mSysTimestamp;
                else
                    lastTimestamp = lastToSendRecord.mBoxTimestamp;

                String lastTsFormatted = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss.SSSz", Locale.US)
                        .format(new Date(lastTimestamp));

                //********* MAKING OF HTTP HEADER **************

                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(Utils.report_url);

                httpPost.setHeader("Content-Encoding", "gzip");
                httpPost.setHeader("Content-Type", "application/json");
                httpPost.setHeader("Accept", "application/json");
                httpPost.setHeader("User-Agent", "AirProbe" + Utils.appVer);

                // ******* authorization bearer header ********

                httpPost.setHeader("Authorization", "Bearer " + Utils.getAccessToken(getApplicationContext()));

                //******** meta header (for new version API V1)

                httpPost.setHeader("meta" + Constants.separators[sepIndex] + "timestampRecorded",
                        lastTsFormatted);
                httpPost.setHeader("meta" + Constants.separators[sepIndex] + "deviceId", Utils.deviceID);
                httpPost.setHeader("meta" + Constants.separators[sepIndex] + "installId", Utils.installID);

                //******** data header (for new version API V1)

                //httpPost.setHeader("data"+Constants.separators[sepIndex]+"extendedPacketId", "");
                //httpPost.setHeader("data"+Constants.separators[sepIndex]+"extendedPacketPointId", "");
                //httpPost.setHeader("data"+Constants.separators[sepIndex]+"extendedSessionId", ""); //deprecated from AP 1.4

                httpPost.setHeader("data" + Constants.separators[sepIndex] + "contentDetails"
                        + Constants.separators[sepIndex] + "type", "airprobe_tags");
                httpPost.setHeader("data" + Constants.separators[sepIndex] + "contentDetails"
                        + Constants.separators[sepIndex] + "format", "json");
                //httpPost.setHeader("data"+Constants.separators[sepIndex]+"contentDetails"+Constants.separators[sepIndex]+"specification", "at-3");   //deprecated from AP 1.4
                if (size > 1)
                    httpPost.setHeader("data" + Constants.separators[sepIndex] + "contentDetails"
                            + Constants.separators[sepIndex] + "list", "true");
                else
                    httpPost.setHeader("data" + Constants.separators[sepIndex] + "contentDetails"
                            + Constants.separators[sepIndex] + "list", "false");
                httpPost.setHeader("data" + Constants.separators[sepIndex] + "contentDetails"
                        + Constants.separators[sepIndex] + "listSize", String.valueOf(size));

                /* from AP 1.4 */
                if ((lastToSendRecord.mBoxMac != null) && (!lastToSendRecord.mBoxMac.equals("")))
                    httpPost.setHeader("meta" + Constants.separators[sepIndex] + "sourceId",
                            lastToSendRecord.mBoxMac);

                httpPost.setHeader("data" + Constants.separators[sepIndex] + "extendedSourceSessionId"
                        + Constants.separators[sepIndex] + "seed", lastToSendRecord.mSourceSessionSeed);
                httpPost.setHeader(// w  ww  . ja v a2  s.co  m
                        "data" + Constants.separators[sepIndex] + "extendedSourceSessionId"
                                + Constants.separators[sepIndex] + "number",
                        String.valueOf(lastToSendRecord.mSourceSessionNumber));
                if ((lastToSendRecord.mSemanticSessionSeed != null)
                        && (!lastToSendRecord.mSemanticSessionSeed.equals(""))) {
                    httpPost.setHeader(
                            "data" + Constants.separators[sepIndex] + "extendedSemanticSessionId"
                                    + Constants.separators[sepIndex] + "seed",
                            lastToSendRecord.mSemanticSessionSeed);
                    httpPost.setHeader(
                            "data" + Constants.separators[sepIndex] + "extendedSemanticSessionId"
                                    + Constants.separators[sepIndex] + "number",
                            String.valueOf(lastToSendRecord.mSemanticSessionNumber));
                }

                httpPost.setHeader("data" + Constants.separators[sepIndex] + "contentDetails"
                        + Constants.separators[sepIndex] + "typeVersion", "30"); //update by increment this field on header changes                
                /* end of from AP 1.4 */

                //******** geo header (for new version API V1)

                //add the right provider to header
                if (lastToSendRecord.mGpsProvider.equals(Constants.GPS_PROVIDERS[0])) //sensor box
                {
                    httpPost.setHeader("geo" + Constants.separators[sepIndex] + "longitude",
                            String.valueOf(lastToSendRecord.mBoxLon));
                    httpPost.setHeader("geo" + Constants.separators[sepIndex] + "latitude",
                            String.valueOf(lastToSendRecord.mBoxLat));
                    if (lastToSendRecord.mBoxAcc != 0)
                        httpPost.setHeader("geo" + Constants.separators[sepIndex] + "hdop",
                                String.valueOf(lastToSendRecord.mBoxAcc)); //from AP 1.4
                    if (lastToSendRecord.mBoxAltitude != 0)
                        httpPost.setHeader("geo" + Constants.separators[sepIndex] + "altitude",
                                String.valueOf(lastToSendRecord.mBoxAltitude)); //from AP 1.4
                    if (lastToSendRecord.mBoxSpeed != 0)
                        httpPost.setHeader("geo" + Constants.separators[sepIndex] + "speed",
                                String.valueOf(lastToSendRecord.mBoxSpeed)); //from AP 1.4
                    if (lastToSendRecord.mBoxBear != 0)
                        httpPost.setHeader("geo" + Constants.separators[sepIndex] + "bearing",
                                String.valueOf(lastToSendRecord.mBoxBear)); //from AP 1.4           
                    httpPost.setHeader("geo" + Constants.separators[sepIndex] + "provider",
                            lastToSendRecord.mGpsProvider);
                    httpPost.setHeader("geo" + Constants.separators[sepIndex] + "timestamp", lastTsFormatted);
                } else if (lastToSendRecord.mGpsProvider.equals(Constants.GPS_PROVIDERS[1])) //phone
                {
                    httpPost.setHeader("geo" + Constants.separators[sepIndex] + "longitude",
                            String.valueOf(lastToSendRecord.mPhoneLon));
                    httpPost.setHeader("geo" + Constants.separators[sepIndex] + "latitude",
                            String.valueOf(lastToSendRecord.mPhoneLat));
                    if (lastToSendRecord.mPhoneAcc != 0)
                        httpPost.setHeader("geo" + Constants.separators[sepIndex] + "accuracy",
                                String.valueOf(lastToSendRecord.mPhoneAcc));
                    if (lastToSendRecord.mPhoneAltitude != 0)
                        httpPost.setHeader("geo" + Constants.separators[sepIndex] + "altitude",
                                String.valueOf(lastToSendRecord.mPhoneAltitude)); //from AP 1.4
                    if (lastToSendRecord.mPhoneSpeed != 0)
                        httpPost.setHeader("geo" + Constants.separators[sepIndex] + "speed",
                                String.valueOf(lastToSendRecord.mPhoneSpeed)); //from AP 1.4
                    if (lastToSendRecord.mPhoneBear != 0)
                        httpPost.setHeader("geo" + Constants.separators[sepIndex] + "bearing",
                                String.valueOf(lastToSendRecord.mPhoneBear)); //from AP 1.4
                    httpPost.setHeader("geo" + Constants.separators[sepIndex] + "provider",
                            lastToSendRecord.mGpsProvider);
                    httpPost.setHeader("geo" + Constants.separators[sepIndex] + "timestamp", lastTsFormatted);
                } else if (lastToSendRecord.mGpsProvider.equals(Constants.GPS_PROVIDERS[2])) //network
                {
                    httpPost.setHeader("geo" + Constants.separators[sepIndex] + "longitude",
                            String.valueOf(lastToSendRecord.mNetworkLon));
                    httpPost.setHeader("geo" + Constants.separators[sepIndex] + "latitude",
                            String.valueOf(lastToSendRecord.mNetworkLat));
                    if (lastToSendRecord.mNetworkAcc != 0)
                        httpPost.setHeader("geo" + Constants.separators[sepIndex] + "accuracy",
                                String.valueOf(lastToSendRecord.mNetworkAcc));
                    if (lastToSendRecord.mNetworkAltitude != 0)
                        httpPost.setHeader("geo" + Constants.separators[sepIndex] + "altitude",
                                String.valueOf(lastToSendRecord.mNetworkAltitude)); //from AP 1.4
                    if (lastToSendRecord.mNetworkSpeed != 0)
                        httpPost.setHeader("geo" + Constants.separators[sepIndex] + "speed",
                                String.valueOf(lastToSendRecord.mNetworkSpeed)); //from AP 1.4
                    if (lastToSendRecord.mNetworkBear != 0)
                        httpPost.setHeader("geo" + Constants.separators[sepIndex] + "bearing",
                                String.valueOf(lastToSendRecord.mNetworkBear)); //from AP 1.4            
                    httpPost.setHeader("geo" + Constants.separators[sepIndex] + "provider",
                            lastToSendRecord.mGpsProvider);
                    httpPost.setHeader("geo" + Constants.separators[sepIndex] + "timestamp", lastTsFormatted);
                }

                //******** MAKING OF HTTP CONTENT (JSON) *************

                //writing string content as an array of json object
                StringBuilder sb = new StringBuilder();
                sb.append("[");

                JSONObject object = new JSONObject();

                try {
                    object.put("timestamp", lastTimestamp);

                    JSONArray locations = new JSONArray();

                    //sensor box gps data
                    if (lastToSendRecord.mBoxLat != 0) {
                        JSONObject boxLocation = new JSONObject();
                        boxLocation.put("latitude", lastToSendRecord.mBoxLat);
                        boxLocation.put("longitude", lastToSendRecord.mBoxLon);
                        if (lastToSendRecord.mBoxAcc != 0)
                            boxLocation.put("hdpop", lastToSendRecord.mBoxAcc);
                        if (lastToSendRecord.mBoxAltitude != 0)
                            boxLocation.put("altitude", lastToSendRecord.mBoxAltitude);
                        if (lastToSendRecord.mBoxSpeed != 0)
                            boxLocation.put("speed", lastToSendRecord.mBoxSpeed);
                        if (lastToSendRecord.mBoxBear != 0)
                            boxLocation.put("bearing", lastToSendRecord.mBoxBear);
                        boxLocation.put("provider", Constants.GPS_PROVIDERS[0]);
                        boxLocation.put("timestamp", lastToSendRecord.mBoxTimestamp);

                        locations.put(0, boxLocation);
                    }

                    //phone gps data
                    if (lastToSendRecord.mPhoneLat != 0) {
                        JSONObject phoneLocation = new JSONObject();
                        phoneLocation.put("latitude", lastToSendRecord.mPhoneLat);
                        phoneLocation.put("longitude", lastToSendRecord.mPhoneLon);
                        if (lastToSendRecord.mPhoneAcc != 0)
                            phoneLocation.put("accuracy", lastToSendRecord.mPhoneAcc);
                        if (lastToSendRecord.mPhoneAltitude != 0)
                            phoneLocation.put("altitude", lastToSendRecord.mPhoneAltitude);
                        if (lastToSendRecord.mPhoneSpeed != 0)
                            phoneLocation.put("speed", lastToSendRecord.mPhoneSpeed);
                        if (lastToSendRecord.mPhoneBear != 0)
                            phoneLocation.put("bearing", lastToSendRecord.mPhoneBear);
                        phoneLocation.put("provider", Constants.GPS_PROVIDERS[1]);
                        phoneLocation.put("timestamp", lastToSendRecord.mPhoneTimestamp);

                        locations.put(1, phoneLocation);
                    }

                    //network gps data
                    if (lastToSendRecord.mNetworkLat != 0) {
                        JSONObject netLocation = new JSONObject();
                        netLocation.put("latitude", lastToSendRecord.mNetworkLat);
                        netLocation.put("longitude", lastToSendRecord.mNetworkLon);
                        if (lastToSendRecord.mNetworkAcc != 0)
                            netLocation.put("accuracy", lastToSendRecord.mNetworkAcc);
                        if (lastToSendRecord.mNetworkAltitude != 0)
                            netLocation.put("altitude", lastToSendRecord.mNetworkAltitude);
                        if (lastToSendRecord.mNetworkSpeed != 0)
                            netLocation.put("speed", lastToSendRecord.mNetworkSpeed);
                        if (lastToSendRecord.mNetworkBear != 0)
                            netLocation.put("bearing", lastToSendRecord.mNetworkBear);
                        netLocation.put("provider", Constants.GPS_PROVIDERS[2]);
                        netLocation.put("timestamp", lastToSendRecord.mNetworkTimestamp);

                        locations.put(2, netLocation);
                    }

                    object.put("locations", locations);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                String concatOfTags = "";

                //put the tags of all records in concatOfTags string
                for (int j = 0; j < recordsWithTags.size(); j++) {
                    if ((recordsWithTags.get(j).mUserData1 != null)
                            && (!recordsWithTags.get(j).mUserData1.equals("")))
                        concatOfTags += recordsWithTags.get(j).mUserData1 + " ";
                }
                Log.d("StoreAndForwardService", "postTags()--> concat of tags: " + concatOfTags);

                try {
                    String[] tags = concatOfTags.split(" ");
                    JSONArray tagsArray = new JSONArray();
                    if ((tags != null) && (tags.length > 0)) {
                        for (int k = 0; k < tags.length; k++) {
                            if (!tags[k].equals(""))
                                tagsArray.put(k, tags[k]);
                        }
                    }
                    object.put("tags", tagsArray);
                    //object.put("tags_cause", null);
                    //object.put("tags_location", null);
                    //object.put("tags_perception", null);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                sb.append(object.toString());
                sb.append("]");

                //Log.d("StoreAndForwardService", "]");   
                Log.d("StoreAndForwardService", "postTags()--> json to string: " + sb.toString());

                byte[] contentGzippedBytes = zipStringToBytes(sb.toString());
                ByteArrayEntity byteArrayEntity = new ByteArrayEntity(contentGzippedBytes);

                byteArrayEntity.setChunked(false); //IMPORTANT: must put false for smartcity.csp.it server

                //IMPORTANT: do not set the content-Length, because is embedded in Entity
                //httpPost.setHeader("Content-Length", byteArrayEntity.getContentLength()+"");

                httpPost.setEntity(byteArrayEntity);

                Log.d("StoreAndForwardService",
                        "postTags()--> Content length: " + httpPost.getEntity().getContentLength());
                Log.d("StoreAndForwardService", "postTags()--> Method: " + httpPost.getMethod());

                //do http post (it performs asynchronously)
                HttpResponse response = httpClient.execute(httpPost);

                sb = null;

                //server response
                //String responseBody = EntityUtils.toString(response.getEntity());
                //Log.d("StoreAndForwardService", "postTags()--> response: " +responseBody);
                Log.d("StoreAndForwardService", "postTags()--> status line: " + response.getStatusLine());

                httpClient.getConnectionManager().shutdown();

                //server response, status line
                StatusLine statusLine = response.getStatusLine();
                int statusCode = statusLine.getStatusCode();

                if (statusCode == Constants.STATUS_OK) {
                    Log.d("StoreAndForwardService", "postTags()--> STATUS OK");
                    mDbManager.deleteRecordsWithTagsBySessionId(sessionId);
                } else
                    Log.d("StoreAndForwardService", "postTags()--> status error code: " + statusCode);
            } else
                Log.d("StoreAndForwardService", "postTags()--> no tags to send");
        }
    }
}