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

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

Introduction

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

Prototype

public HttpEntity getEntity() 

Source Link

Usage

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/*www.  j a  v a 2  s. com*/
        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 w w. j  ava  2  s.com*/
                        "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.apache.jmeter.protocol.http.sampler.HTTPHC4Impl.java

/**
 * // ww w.  j  av  a 2 s .  c  o m
 * @param post {@link HttpPost}
 * @return String posted body if computable
 * @throws IOException if sending the data fails due to I/O
 */
protected String sendPostData(HttpPost post) throws IOException {
    // Buffer to hold the post body, except file content
    StringBuilder postedBody = new StringBuilder(1000);
    HTTPFileArg[] files = getHTTPFiles();

    final String contentEncoding = getContentEncodingOrNull();
    final boolean haveContentEncoding = contentEncoding != null;

    // Check if we should do a multipart/form-data or an
    // application/x-www-form-urlencoded post request
    if (getUseMultipartForPost()) {
        // If a content encoding is specified, we use that as the
        // encoding of any parameter values
        Charset charset = null;
        if (haveContentEncoding) {
            charset = Charset.forName(contentEncoding);
        } else {
            charset = MIME.DEFAULT_CHARSET;
        }

        if (log.isDebugEnabled()) {
            log.debug("Building multipart with:getDoBrowserCompatibleMultipart():"
                    + getDoBrowserCompatibleMultipart() + ", with charset:" + charset + ", haveContentEncoding:"
                    + haveContentEncoding);
        }
        // Write the request to our own stream
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create().setCharset(charset);
        if (getDoBrowserCompatibleMultipart()) {
            multipartEntityBuilder.setLaxMode();
        } else {
            multipartEntityBuilder.setStrictMode();
        }
        // Create the parts
        // Add any parameters
        for (JMeterProperty jMeterProperty : getArguments()) {
            HTTPArgument arg = (HTTPArgument) jMeterProperty.getObjectValue();
            String parameterName = arg.getName();
            if (arg.isSkippable(parameterName)) {
                continue;
            }
            StringBody stringBody = new StringBody(arg.getValue(), ContentType.create("text/plain", charset));
            FormBodyPart formPart = FormBodyPartBuilder.create(parameterName, stringBody).build();
            multipartEntityBuilder.addPart(formPart);
        }

        // Add any files
        // Cannot retrieve parts once added to the MultiPartEntity, so have to save them here.
        ViewableFileBody[] fileBodies = new ViewableFileBody[files.length];
        for (int i = 0; i < files.length; i++) {
            HTTPFileArg file = files[i];

            File reservedFile = FileServer.getFileServer().getResolvedFile(file.getPath());
            fileBodies[i] = new ViewableFileBody(reservedFile, file.getMimeType());
            multipartEntityBuilder.addPart(file.getParamName(), fileBodies[i]);
        }

        HttpEntity entity = multipartEntityBuilder.build();
        post.setEntity(entity);

        if (entity.isRepeatable()) {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            for (ViewableFileBody fileBody : fileBodies) {
                fileBody.hideFileData = true;
            }
            entity.writeTo(bos);
            for (ViewableFileBody fileBody : fileBodies) {
                fileBody.hideFileData = false;
            }
            bos.flush();
            // We get the posted bytes using the encoding used to create it
            postedBody.append(new String(bos.toByteArray(), contentEncoding == null ? "US-ASCII" // $NON-NLS-1$ this is the default used by HttpClient
                    : contentEncoding));
            bos.close();
        } else {
            postedBody.append("<Multipart was not repeatable, cannot view what was sent>"); // $NON-NLS-1$
        }

        //            // Set the content type TODO - needed?
        //            String multiPartContentType = multiPart.getContentType().getValue();
        //            post.setHeader(HEADER_CONTENT_TYPE, multiPartContentType);

    } else { // not multipart
        // Check if the header manager had a content type header
        // This allows the user to specify his own content-type for a POST request
        Header contentTypeHeader = post.getFirstHeader(HTTPConstants.HEADER_CONTENT_TYPE);
        boolean hasContentTypeHeader = contentTypeHeader != null && contentTypeHeader.getValue() != null
                && contentTypeHeader.getValue().length() > 0;
        // If there are no arguments, we can send a file as the body of the request
        // TODO: needs a multiple file upload scenerio
        if (!hasArguments() && getSendFileAsPostBody()) {
            // If getSendFileAsPostBody returned true, it's sure that file is not null
            HTTPFileArg file = files[0];
            if (!hasContentTypeHeader) {
                // Allow the mimetype of the file to control the content type
                if (file.getMimeType() != null && file.getMimeType().length() > 0) {
                    post.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, file.getMimeType());
                } else {
                    post.setHeader(HTTPConstants.HEADER_CONTENT_TYPE,
                            HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED);
                }
            }

            FileEntity fileRequestEntity = new FileEntity(new File(file.getPath()), (ContentType) null);// TODO is null correct?
            post.setEntity(fileRequestEntity);

            // We just add placeholder text for file content
            postedBody.append("<actual file content, not shown here>");
        } else {
            // In a post request which is not multipart, we only support
            // parameters, no file upload is allowed

            // If a content encoding is specified, we set it as http parameter, so that
            // the post body will be encoded in the specified content encoding
            if (haveContentEncoding) {
                post.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, contentEncoding);
            }

            // If none of the arguments have a name specified, we
            // just send all the values as the post body
            if (getSendParameterValuesAsPostBody()) {
                // Allow the mimetype of the file to control the content type
                // This is not obvious in GUI if you are not uploading any files,
                // but just sending the content of nameless parameters
                // TODO: needs a multiple file upload scenerio
                if (!hasContentTypeHeader) {
                    HTTPFileArg file = files.length > 0 ? files[0] : null;
                    if (file != null && file.getMimeType() != null && file.getMimeType().length() > 0) {
                        post.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, file.getMimeType());
                    } else {
                        // TODO - is this the correct default?
                        post.setHeader(HTTPConstants.HEADER_CONTENT_TYPE,
                                HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED);
                    }
                }

                // Just append all the parameter values, and use that as the post body
                StringBuilder postBody = new StringBuilder();
                for (JMeterProperty jMeterProperty : getArguments()) {
                    HTTPArgument arg = (HTTPArgument) jMeterProperty.getObjectValue();
                    // Note: if "Encoded?" is not selected, arg.getEncodedValue is equivalent to arg.getValue
                    if (haveContentEncoding) {
                        postBody.append(arg.getEncodedValue(contentEncoding));
                    } else {
                        postBody.append(arg.getEncodedValue());
                    }
                }
                // Let StringEntity perform the encoding
                StringEntity requestEntity = new StringEntity(postBody.toString(), contentEncoding);
                post.setEntity(requestEntity);
                postedBody.append(postBody.toString());
            } else {
                // It is a normal post request, with parameter names and values

                // Set the content type
                if (!hasContentTypeHeader) {
                    post.setHeader(HTTPConstants.HEADER_CONTENT_TYPE,
                            HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED);
                }
                // Add the parameters
                PropertyIterator args = getArguments().iterator();
                List<NameValuePair> nvps = new ArrayList<>();
                String urlContentEncoding = contentEncoding;
                if (urlContentEncoding == null || urlContentEncoding.length() == 0) {
                    // Use the default encoding for urls
                    urlContentEncoding = EncoderCache.URL_ARGUMENT_ENCODING;
                }
                while (args.hasNext()) {
                    HTTPArgument arg = (HTTPArgument) args.next().getObjectValue();
                    // The HTTPClient always urlencodes both name and value,
                    // so if the argument is already encoded, we have to decode
                    // it before adding it to the post request
                    String parameterName = arg.getName();
                    if (arg.isSkippable(parameterName)) {
                        continue;
                    }
                    String parameterValue = arg.getValue();
                    if (!arg.isAlwaysEncoded()) {
                        // The value is already encoded by the user
                        // Must decode the value now, so that when the
                        // httpclient encodes it, we end up with the same value
                        // as the user had entered.
                        parameterName = URLDecoder.decode(parameterName, urlContentEncoding);
                        parameterValue = URLDecoder.decode(parameterValue, urlContentEncoding);
                    }
                    // Add the parameter, httpclient will urlencode it
                    nvps.add(new BasicNameValuePair(parameterName, parameterValue));
                }
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nvps, urlContentEncoding);
                post.setEntity(entity);
                if (entity.isRepeatable()) {
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    post.getEntity().writeTo(bos);
                    bos.flush();
                    // We get the posted bytes using the encoding used to create it
                    if (contentEncoding != null) {
                        postedBody.append(new String(bos.toByteArray(), contentEncoding));
                    } else {
                        postedBody.append(new String(bos.toByteArray(), SampleResult.DEFAULT_HTTP_ENCODING));
                    }
                    bos.close();
                } else {
                    postedBody.append("<RequestEntity was not repeatable, cannot view what was sent>");
                }
            }
        }
    }
    return postedBody.toString();
}

From source file:org.dasein.cloud.openstack.nova.os.AbstractMethod.java

protected @Nullable String postString(@Nonnull String authToken, @Nonnull String endpoint,
        @Nonnull String resource, @Nonnull String payload) throws CloudException, InternalException {
    Logger std = NovaOpenStack.getLogger(NovaOpenStack.class, "std");
    Logger wire = NovaOpenStack.getLogger(NovaOpenStack.class, "wire");

    if (std.isTraceEnabled()) {
        std.trace("enter - " + AbstractMethod.class.getName() + ".postString(" + authToken + "," + endpoint
                + "," + resource + "," + payload + ")");
    }/*from w  w  w  .  j  a v a2 s . c om*/
    if (wire.isDebugEnabled()) {
        wire.debug("---------------------------------------------------------------------------------"
                + endpoint + resource);
        wire.debug("");
    }
    HttpClient client = null;
    try {
        client = getClient();
        HttpPost post = new HttpPost(endpoint + resource);

        post.addHeader("Content-Type", "application/json");
        post.addHeader("X-Auth-Token", authToken);
        if (wire.isDebugEnabled()) {
            wire.debug(post.getRequestLine().toString());
            for (Header header : post.getAllHeaders()) {
                wire.debug(header.getName() + ": " + header.getValue());
            }
            wire.debug("");
        }
        if (payload != null) {
            try {
                //noinspection deprecation
                post.setEntity(new StringEntity(payload == null ? "" : payload, "application/json", "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                throw new InternalException(e);
            }
            try {
                wire.debug(EntityUtils.toString(post.getEntity()));
            } catch (IOException ignore) {
            }

            wire.debug("");
        }
        HttpResponse response;

        try {
            std.debug("POST " + toAPIResource(resource));
            response = client.execute(post);
            if (wire.isDebugEnabled()) {
                wire.debug(response.getStatusLine().toString());
                for (Header header : response.getAllHeaders()) {
                    wire.debug(header.getName() + ": " + header.getValue());
                }
                wire.debug("");
            }
        } catch (IOException e) {
            std.error("I/O error from server communications: " + e.getMessage());
            e.printStackTrace();
            throw new InternalException("Communication error while reading from cloud endpoint", e);
        }
        int code = response.getStatusLine().getStatusCode();

        std.debug("HTTP STATUS: " + code);
        if (code == HttpStatus.SC_REQUEST_TOO_LONG || code == HttpStatus.SC_REQUEST_URI_TOO_LONG) {
            String data = null;

            try {
                HttpEntity entity = response.getEntity();

                if (entity != null) {
                    data = EntityUtils.toString(entity);
                    if (wire.isDebugEnabled()) {
                        wire.debug(data);
                        wire.debug("");
                    }
                }
            } catch (IOException e) {
                std.error("Failed to read response error due to a cloud I/O error: " + e.getMessage());
                e.printStackTrace();
                throw new CloudException(e);
            }
            try {
                if (data != null) {
                    JSONObject ob = new JSONObject(data);
                    if (ob.has("overLimit")) {
                        ob = ob.getJSONObject("overLimit");
                        int min = ob.optInt("retryAfter", 0);

                        if (min < 1) {
                            throw new CloudException(CloudErrorType.CAPACITY, 413, "Over Limit",
                                    ob.has("message") ? ob.getString("message") : "Over Limit");
                        }
                        try {
                            Thread.sleep(CalendarWrapper.MINUTE * min);
                        } catch (InterruptedException ignore) {
                        }
                        return postString(authToken, endpoint, resource, payload);
                    }
                }
            } catch (JSONException e) {
                throw new CloudException(e);
            }
        }
        if (code != HttpStatus.SC_OK && code != HttpStatus.SC_ACCEPTED && code != HttpStatus.SC_NO_CONTENT
                && code != HttpStatus.SC_CREATED) {
            std.error("postString(): Expected OK, ACCEPTED, or NO CONTENT for POST request, got " + code);
            String data = null;

            try {
                HttpEntity entity = response.getEntity();

                if (entity != null) {
                    data = EntityUtils.toString(entity);
                    if (wire.isDebugEnabled()) {
                        wire.debug(data);
                        wire.debug("");
                    }
                }
            } catch (IOException e) {
                std.error("Failed to read response error due to a cloud I/O error: " + e.getMessage());
                e.printStackTrace();
                throw new CloudException(e);
            }
            NovaException.ExceptionItems items = NovaException.parseException(code, data);

            if (items == null) {
                items = new NovaException.ExceptionItems();
                items.code = 404;
                items.type = CloudErrorType.COMMUNICATION;
                items.message = "itemNotFound";
                items.details = "No such object: " + resource;
            }
            std.error("postString(): [" + code + " : " + items.message + "] " + items.details);
            throw new NovaException(items);
        } else {
            if (code != HttpStatus.SC_NO_CONTENT) {
                String data = null;

                try {
                    HttpEntity entity = response.getEntity();

                    if (entity != null) {
                        data = EntityUtils.toString(entity);
                        if (wire.isDebugEnabled()) {
                            wire.debug(data);
                            wire.debug("");
                        }
                    }
                } catch (IOException e) {
                    std.error("Failed to read response due to a cloud I/O error: " + e.getMessage());
                    e.printStackTrace();
                    throw new CloudException(e);
                }
                if (data != null && !data.trim().equals("")) {
                    return data;
                } else if (code == HttpStatus.SC_ACCEPTED) {
                    Header[] headers = response.getAllHeaders();

                    for (Header h : headers) {
                        if (h.getName().equalsIgnoreCase("Location")) {
                            return "{\"location\" : \"" + h.getValue().trim() + "\"}";
                        }
                    }
                }
            }
            return null;
        }
    } finally {
        if (client != null) {
            client.getConnectionManager().shutdown();
        }
        if (std.isTraceEnabled()) {
            std.trace("exit - " + AbstractMethod.class.getName() + ".postString()");
        }
        if (wire.isDebugEnabled()) {
            wire.debug("");
            wire.debug("---------------------------------------------------------------------------------"
                    + endpoint + resource);
        }
    }
}

From source file:org.hubiquitus.twitter4j_1_1.stream.HStream.java

public void start() {
    stop();//from ww w  .j av a2 s . c  o  m
    String url = STREAMING_API_1_1_ENDPOINT;

    DefaultHttpClient client = new DefaultHttpClient();
    if ((proxyHost != null) && (proxyPort > 0)) {
        setProxyParams(client);
    }
    HttpPost post = new HttpPost(url);
    try {
        post.setEntity(new UrlEncodedFormEntity(setPostparms()));
        log.debug("post : " + post + "Entity = " + post.getEntity());
        //--------  Ask the twitter stream  API the gzip stream ------   
        post.setHeader("Accept-Encoding", "deflate, gzip");
        log.trace("using deflate, gzip");
        //--------  Sign a Post with oauth using oauth.signpost ------     
        CommonsHttpOAuthConsumer consumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret);
        consumer.setTokenWithSecret(token, tokenSecret);
        log.trace("consumer OAuth created");
        try {
            consumer.sign(post);
            log.debug("consumer OAuth signed");
            try {
                HttpResponse response = client.execute(post);
                log.trace("post executed");
                log.debug("-------->   :" + response);
                checkreconnection(hcommonsFunctions.getHTTPResponse(response));
                HttpEntity entity = response.getEntity();
                log.trace("HttpEntity fetched");
                if (entity == null)
                    throw new IOException("No entity");
                log.trace("HttpEntity not null :)");
                loop.buffer = new BufferedReader(
                        new InputStreamReader(new GZipStream(entity.getContent()), "UTF-8"));
                log.trace("Buffer created");
                loop.start();
                log.debug("Stream started");
            } catch (ClientProtocolException e) {
                log.error("Error during execution, ", e);
            } catch (IOException e) {
                log.error("Error during execution, ", e);
            }

        } catch (OAuthMessageSignerException e) {
            log.error("ERROR AT OAUTH, ", e);
        } catch (OAuthExpectationFailedException e) {
            log.error("ERROR AT OAUTH, ", e);
        } catch (OAuthCommunicationException e) {
            log.error("ERROR AT OAUTH, ", e);
        }

    } catch (UnsupportedEncodingException e1) {
        log.debug(" Error on setEntity :", e1);
    }
}

From source file:org.hubiquitus.twitter4j_1_1.stream.HUserStream.java

public void start() {
    stop();/*from  ww w. j av a 2 s.c  om*/
    String url = USERSTREAM_API_1_1_ENDPOINT;

    DefaultHttpClient client = new DefaultHttpClient();
    if ((proxyHost != null) && (proxyPort > 0)) {
        setProxyParams(client);
    }
    HttpPost post = new HttpPost(url);
    try {
        post.setEntity(new UrlEncodedFormEntity(setPostparms()));
        log.debug("post : " + post + "Entity = " + post.getEntity());
        //--------  Ask the twitter stream  API the gzip stream ------   
        post.setHeader("Accept-Encoding", "deflate, gzip");
        log.trace("using deflate, gzip");
        //--------  Sign a Post with oauth using oauth.signpost ------     
        CommonsHttpOAuthConsumer consumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret);
        consumer.setTokenWithSecret(token, tokenSecret);
        log.trace("consumer OAuth created");
        try {
            consumer.sign(post);
            log.debug("consumer OAuth signed");
            try {
                HttpResponse response = client.execute(post);
                log.trace("post executed");
                log.debug("-------->   :" + response);
                checkreconnection(hcommonsFunctions.getHTTPResponse(response));
                HttpEntity entity = response.getEntity();
                log.trace("HttpEntity fetched");
                if (entity == null)
                    throw new IOException("No entity");
                log.trace("HttpEntity not null :)");
                loop.buffer = new BufferedReader(
                        new InputStreamReader(new GZipStream(entity.getContent()), "UTF-8"));
                log.trace("Buffer created");
                loop.start();
                log.debug("Stream started");
            } catch (ClientProtocolException e) {
                log.error("Error during execution, ", e);
            } catch (IOException e) {
                log.error("Error during execution, ", e);
            }
        } catch (OAuthMessageSignerException e) {
            log.error("ERROR AT OAUTH, ", e);
        } catch (OAuthExpectationFailedException e) {
            log.error("ERROR AT OAUTH, ", e);
        } catch (OAuthCommunicationException e) {
            log.error("ERROR AT OAUTH, ", e);
        }

    } catch (UnsupportedEncodingException e1) {
        log.debug(" Error on setEntity :", e1);
    }
}