Example usage for org.apache.http.entity ByteArrayEntity setChunked

List of usage examples for org.apache.http.entity ByteArrayEntity setChunked

Introduction

In this page you can find the example usage for org.apache.http.entity ByteArrayEntity setChunked.

Prototype

public void setChunked(boolean z) 

Source Link

Usage

From source file:org.coronastreet.gpxconverter.GarminForm.java

public void upload() {
    httpClient = HttpClientBuilder.create().build();
    localContext = new BasicHttpContext();
    cookieStore = new BasicCookieStore();
    localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
    //httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

    if (doLogin()) {
        try {//w  ww  .  ja  v  a2  s .com
            HttpGet get = new HttpGet("http://connect.garmin.com/transfer/upload#");
            HttpResponse formResponse = httpClient.execute(get, localContext);
            HttpEntity formEntity = formResponse.getEntity();
            EntityUtils.consume(formEntity);

            HttpPost request = new HttpPost(
                    "http://connect.garmin.com/proxy/upload-service-1.1/json/upload/.tcx");
            request.setHeader("Referer",
                    "http://connect.garmin.com/api/upload/widget/manualUpload.faces?uploadServiceVersion=1.1");
            request.setHeader("Accept", "text/html, application/xhtml+xml, */*");
            MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
            entity.addPart("data",
                    new InputStreamBody(document2InputStream(outDoc), "application/octet-stream", "temp.tcx"));

            // Need to do this bit because without it you can't disable chunked encoding
            ByteArrayOutputStream bArrOS = new ByteArrayOutputStream();
            entity.writeTo(bArrOS);
            bArrOS.flush();
            ByteArrayEntity bArrEntity = new ByteArrayEntity(bArrOS.toByteArray());
            bArrOS.close();

            bArrEntity.setChunked(false);
            bArrEntity.setContentEncoding(entity.getContentEncoding());
            bArrEntity.setContentType(entity.getContentType());

            request.setEntity(bArrEntity);

            HttpResponse response = httpClient.execute(request, localContext);

            if (response.getStatusLine().getStatusCode() != 200) {
                log("Failed to Upload");
                HttpEntity en = response.getEntity();
                if (en != null) {
                    String output = EntityUtils.toString(en);
                    log(output);
                }
            } else {
                HttpEntity ent = response.getEntity();
                if (ent != null) {
                    String output = EntityUtils.toString(ent);
                    output = "[" + output + "]"; //OMG Garmin Sucks at JSON.....
                    JSONObject uploadResponse = new JSONArray(output).getJSONObject(0);
                    JSONObject importResult = uploadResponse.getJSONObject("detailedImportResult");
                    try {
                        int uploadID = importResult.getInt("uploadId");
                        log("Success! UploadID is " + uploadID);
                    } catch (Exception e) {
                        JSONArray failures = (JSONArray) importResult.get("failures");
                        JSONObject failure = (JSONObject) failures.get(0);
                        JSONArray errorMessages = failure.getJSONArray("messages");
                        JSONObject errorMessage = errorMessages.getJSONObject(0);
                        String content = errorMessage.getString("content");
                        log("Upload Failed! Error: " + content);
                    }
                }
            }
            httpClient.close();
        } catch (Exception ex) {
            log("Exception? " + ex.getMessage());
            ex.printStackTrace();
            // handle exception here
        }
    } else {
        log("Failed to upload!");
    }
}

From source file:com.ginstr.android.service.opencellid.upload.data.MeasurementsUploaderService.java

/**
 * uploads measurements data as a batch file
 * @param dbIterator/*from   w ww .  j av  a2s  . co m*/
 * @param latLonFormat
 * @param count
 * @param max
 * @return number of uploaded measurements
 */
private int uploadMeasurementsBatch(MeasurementsDBIterator dbIterator, NumberFormat latLonFormat, int count,
        int max) {
    writeToLog("uploadMeasurementsBatch(" + count + ", " + max + ")");

    try {
        StringBuilder sb = new StringBuilder(
                "lat,lon,mcc,mnc,lac,cellid,signal,measured_at,rating,speed,direction,act\n");

        int thisBatchSize = 0;
        while (thisBatchSize < MEASUREMENTS_BATCH_SIZE && dbIterator.hasNext() && uploadThreadRunning) {
            Measurement meassurement = dbIterator.next();

            sb.append(latLonFormat.format(meassurement.getLat())).append(",");
            sb.append(latLonFormat.format(meassurement.getLon())).append(",");
            sb.append(meassurement.getMcc()).append(",");
            sb.append(meassurement.getMnc()).append(",");
            sb.append(meassurement.getLac()).append(",");
            sb.append(meassurement.getCellid()).append(",");
            sb.append(meassurement.getGsmSignalStrength()).append(",");
            sb.append(meassurement.getTimestamp()).append(",");
            sb.append((meassurement.getAccuracy() != null) ? meassurement.getAccuracy() : "").append(",");
            sb.append((int) meassurement.getSpeed()).append(",");
            sb.append((int) meassurement.getBearing()).append(",");
            sb.append((meassurement.getNetworkType() != null) ? meassurement.getNetworkType() : "");
            sb.append("\n");

            thisBatchSize++;
        }

        HttpResponse response = null;

        writeToLog("Upload request URL: " + httppost.getURI());

        if (uploadThreadRunning) {
            String csv = sb.toString();

            writeToLog("Upload data: " + csv);

            MultipartEntity mpEntity = new MultipartEntity();
            mpEntity.addPart("key", new StringBody(apiKey));
            mpEntity.addPart("appId", new StringBody(appId));
            mpEntity.addPart("datafile", new InputStreamBody(new ByteArrayInputStream(csv.getBytes()),
                    "text/csv", MULTIPART_FILENAME));

            ByteArrayOutputStream bArrOS = new ByteArrayOutputStream();
            // reqEntity is the MultipartEntity instance
            mpEntity.writeTo(bArrOS);
            bArrOS.flush();
            ByteArrayEntity bArrEntity = new ByteArrayEntity(bArrOS.toByteArray());
            bArrOS.close();

            bArrEntity.setChunked(false);
            bArrEntity.setContentEncoding(mpEntity.getContentEncoding());
            bArrEntity.setContentType(mpEntity.getContentType());

            httppost.setEntity(bArrEntity);

            response = httpclient.execute(httppost);
            if (response == null) {
                writeToLog("Upload: null HTTP-response");
                throw new IllegalStateException("no HTTP-response from server");
            }

            HttpEntity resEntity = response.getEntity();

            writeToLog(
                    "Upload: " + response.getStatusLine().getStatusCode() + " - " + response.getStatusLine());

            if (resEntity != null) {
                resEntity.consumeContent();
            }

            if (response.getStatusLine() == null) {
                writeToLog(": " + "null HTTP-status-line");
                throw new IllegalStateException("no HTTP-status returned");
            }

            if (response.getStatusLine().getStatusCode() != 200) {
                throw new IllegalStateException(
                        "HTTP-status code returned : " + response.getStatusLine().getStatusCode());
            }
        }

        return count + thisBatchSize;

    } catch (IOException e) {
        throw new IllegalStateException("IO-Error: " + e.getMessage());
    }
}

From source file:com.ginstr.android.service.opencellid.upload.data.MeasurementsUploaderService.java

/**
 * Used to upload entries from networks table to OCID servers.
 *//*from www .  j  av  a  2s .c  o  m*/
private void uploadNetworks() {
    writeToLog("uploadNetworks()");

    String existingFileName = "uploadNetworks.csv";
    String data = null;

    NetworkDBIterator dbIterator = mDatabase.getNonUploadedNetworks();
    try {
        if (dbIterator.getCount() > 0) {
            //timestamp, mcc, mnc, net (network type), nen (network name)
            StringBuilder sb = new StringBuilder("timestamp,mcc,mnc,net,nen" + ((char) 0xA));

            while (dbIterator.hasNext() && uploadThreadRunning) {
                Network network = dbIterator.next();
                sb.append(network.getTimestamp()).append(",");
                sb.append(network.getMcc()).append(",");
                sb.append(network.getMnc()).append(",");
                sb.append(network.getType()).append(",");
                sb.append(network.getName());
                sb.append(((char) 0xA));
            }

            data = sb.toString();

        } else {
            writeToLog("No networks for upload.");
            return;
        }
    } finally {
        dbIterator.close();
    }

    writeToLog("uploadNetworks(): " + data);

    if (uploadThreadRunning) {

        try {
            httppost = new HttpPost(networksUrl);

            HttpResponse response = null;

            writeToLog("Upload request URL: " + httppost.getURI());

            if (uploadThreadRunning) {
                MultipartEntity mpEntity = new MultipartEntity();
                mpEntity.addPart("apikey", new StringBody(apiKey));
                mpEntity.addPart("datafile", new InputStreamBody(new ByteArrayInputStream(data.getBytes()),
                        "text/csv", existingFileName));

                ByteArrayOutputStream bArrOS = new ByteArrayOutputStream();
                // reqEntity is the MultipartEntity instance
                mpEntity.writeTo(bArrOS);
                bArrOS.flush();
                ByteArrayEntity bArrEntity = new ByteArrayEntity(bArrOS.toByteArray());
                bArrOS.close();

                bArrEntity.setChunked(false);
                bArrEntity.setContentEncoding(mpEntity.getContentEncoding());
                bArrEntity.setContentType(mpEntity.getContentType());

                httppost.setEntity(bArrEntity);

                response = httpclient.execute(httppost);
                if (response == null) {
                    writeToLog("Upload: null HTTP-response");
                    throw new IllegalStateException("no HTTP-response from server");
                }

                HttpEntity resEntity = response.getEntity();

                writeToLog("Response: " + response.getStatusLine().getStatusCode() + " - "
                        + response.getStatusLine());

                if (resEntity != null) {
                    writeToLog("Response content: " + EntityUtils.toString(resEntity));
                    resEntity.consumeContent();
                }
            }

            if (uploadThreadRunning) {
                if (response == null) {
                    writeToLog(": " + "null response");

                    throw new IllegalStateException("no response");
                }
                if (response.getStatusLine() == null) {
                    writeToLog(": " + "null HTTP-status-line");

                    throw new IllegalStateException("no HTTP-status returned");
                }
                if (response.getStatusLine().getStatusCode() == 200) {
                    mDatabase.setAllNetworksUploaded();
                } else if (response.getStatusLine().getStatusCode() != 200) {
                    throw new IllegalStateException(
                            response.getStatusLine().getStatusCode() + " HTTP-status returned");
                }
            }

        } catch (Exception e) {
            // httppost cancellation throws exceptions
            if (uploadThreadRunning) {
                writeExceptionToLog(e);
            }
        }
    }
}

From source file:edu.isi.misd.tagfiler.client.JakartaClient.java

/**
 * Uploads a file block.//from   ww  w.  j  a v a  2s  . com
 * 
 * @param url
 *            the query url
 * @param inputStream
 *            the InputStream where to read from
 * @param length
 *            the number of bytes to read
 * @param first
 *            the first byte to read
 * @param fileLength
 *            the file length
 * @param cookie
 *            the cookie to be set in the request
 * @return the HTTP Response
 */
public ClientURLResponse postFile(String url, byte[] entity, long length, long first, long fileLength,
        String cookie) {
    HttpPut httpput = new HttpPut(url);
    httpput.setHeader("Content-Type", "application/octet-stream");
    if (first != 0) {
        httpput.setHeader("Content-Range", "bytes " + first + "-" + (first + length - 1) + "/" + fileLength);
    }
    ByteArrayEntity inputStreamEntity = new ByteArrayEntity(entity);
    inputStreamEntity.setChunked(false);
    httpput.setEntity(inputStreamEntity);
    return execute(httpput, cookie);
}

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/*  w  w  w.j  ava2s  . c o 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(/*from   w ww  .j a  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");
        }
    }
}

From source file:org.coronastreet.gpxconverter.StravaForm.java

public void upload() {
    //httpClient = new DefaultHttpClient();
    httpClient = HttpClientBuilder.create().build();
    localContext = new BasicHttpContext();
    cookieStore = new BasicCookieStore();
    localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
    //httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

    if (doLogin()) {
        //log("Ok....logged in...");
        try {//from  www  .  j  ava  2s . c  o  m
            // Have to fetch the form to get the CSRF Token
            HttpGet get = new HttpGet(uploadFormURL);
            HttpResponse formResponse = httpClient.execute(get, localContext);
            //log("Fetched the upload form...: " + formResponse.getStatusLine());
            org.jsoup.nodes.Document doc = Jsoup.parse(EntityUtils.toString(formResponse.getEntity()));
            String csrftoken, csrfparam;
            Elements metalinksParam = doc.select("meta[name=csrf-param]");
            if (!metalinksParam.isEmpty()) {
                csrfparam = metalinksParam.first().attr("content");
            } else {
                csrfparam = null;
                log("Missing csrf-param?");
            }
            Elements metalinksToken = doc.select("meta[name=csrf-token]");
            if (!metalinksToken.isEmpty()) {
                csrftoken = metalinksToken.first().attr("content");
            } else {
                csrftoken = null;
                log("Missing csrf-token?");
            }

            HttpPost request = new HttpPost(uploadURL);
            request.setHeader("X-CSRF-Token", csrftoken);

            MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
            entity.addPart("method", new StringBody("post"));
            entity.addPart("new_uploader", new StringBody("1"));
            entity.addPart(csrfparam, new StringBody(csrftoken));
            entity.addPart("files[]",
                    new InputStreamBody(document2InputStream(outDoc), "application/octet-stream", "temp.tcx"));

            // Need to do this bit because without it you can't disable chunked encoding, and Strava doesn't support chunked.
            ByteArrayOutputStream bArrOS = new ByteArrayOutputStream();
            entity.writeTo(bArrOS);
            bArrOS.flush();
            ByteArrayEntity bArrEntity = new ByteArrayEntity(bArrOS.toByteArray());
            bArrOS.close();

            bArrEntity.setChunked(false);
            bArrEntity.setContentEncoding(entity.getContentEncoding());
            bArrEntity.setContentType(entity.getContentType());

            request.setEntity(bArrEntity);

            HttpResponse response = httpClient.execute(request, localContext);

            if (response.getStatusLine().getStatusCode() != 200) {
                log("Failed to Upload");
                HttpEntity en = response.getEntity();
                if (en != null) {
                    String output = EntityUtils.toString(en);
                    log(output);
                }
            } else {
                HttpEntity ent = response.getEntity();
                if (ent != null) {
                    String output = EntityUtils.toString(ent);
                    //log(output);
                    JSONObject userInfo = new JSONArray(output).getJSONObject(0);
                    //log("Object: " + userInfo.toString());

                    if (userInfo.get("workflow").equals("Error")) {
                        log("Upload Error: " + userInfo.get("error"));
                    } else {
                        log("Successful Uploaded. ID is " + userInfo.get("id"));
                    }
                }
            }
            httpClient.close();
        } catch (Exception ex) {
            log("Exception? " + ex.getMessage());
            ex.printStackTrace();
            // handle exception here
        }
    } else {
        log("Failed to upload!");
    }
}