Example usage for javax.net.ssl HttpsURLConnection setUseCaches

List of usage examples for javax.net.ssl HttpsURLConnection setUseCaches

Introduction

In this page you can find the example usage for javax.net.ssl HttpsURLConnection setUseCaches.

Prototype

public void setUseCaches(boolean usecaches) 

Source Link

Document

Sets the value of the useCaches field of this URLConnection to the specified value.

Usage

From source file:org.disrupted.rumble.database.statistics.StatisticManager.java

public void onEventAsync(LinkLayerStarted event) {
    if (!event.linkLayerIdentifier.equals(WifiLinkLayerAdapter.LinkLayerIdentifier))
        return;// w w w  . j  a v  a2 s .  c om

    if (RumblePreferences.UserOkWithSharingAnonymousData(RumbleApplication.getContext())
            && RumblePreferences.isTimeToSync(RumbleApplication.getContext())) {
        if (!NetUtil.isURLReachable("http://disruptedsystems.org/"))
            return;

        try {
            // generate the JSON file
            byte[] json = generateStatJSON().toString().getBytes();

            // configure SSL
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            InputStream caInput = new BufferedInputStream(
                    RumbleApplication.getContext().getAssets().open("certs/disruptedsystemsCA.pem"));
            Certificate ca = cf.generateCertificate(caInput);

            String keyStoreType = KeyStore.getDefaultType();
            KeyStore keyStore = KeyStore.getInstance(keyStoreType);
            keyStore.load(null, null);
            keyStore.setCertificateEntry("ca", ca);

            String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
            tmf.init(keyStore);

            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, tmf.getTrustManagers(), null);

            URL url = new URL("https://data.disruptedsystems.org/post");
            HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
            urlConnection.setSSLSocketFactory(sslContext.getSocketFactory());

            // then configure the header
            urlConnection.setInstanceFollowRedirects(true);
            urlConnection.setRequestMethod("POST");
            urlConnection.setDoOutput(true);
            urlConnection.setRequestProperty("Content-Type", "application/json");
            urlConnection.setRequestProperty("Accept", "application/json");
            urlConnection.setRequestProperty("charset", "utf-8");
            urlConnection.setRequestProperty("Content-Length", Integer.toString(json.length));
            urlConnection.setUseCaches(false);

            // connect and send the JSON
            urlConnection.setConnectTimeout(10 * 1000);
            urlConnection.connect();
            urlConnection.getOutputStream().write(json);
            if (urlConnection.getResponseCode() != 200)
                throw new IOException("request failed");

            // erase the database
            RumblePreferences.updateLastSync(RumbleApplication.getContext());
            cleanDatabase();
        } catch (Exception ex) {
            Log.e(TAG, "Failed to establish SSL connection to server: " + ex.toString());
        }
    }
}

From source file:org.openhab.binding.unifi.internal.UnifiBinding.java

private boolean login() {
    String url = null;/*from   www  .j  av  a 2s . c o  m*/

    try {
        url = getControllerUrl("api/login");
        String urlParameters = "{'username':'" + username + "','password':'" + password + "'}";
        byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);

        URL cookieUrl = new URL(url);
        HttpsURLConnection connection = (HttpsURLConnection) cookieUrl.openConnection();
        connection.setDoOutput(true);
        connection.setInstanceFollowRedirects(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Referer", getControllerUrl("login"));
        connection.setRequestProperty("Content-Length", Integer.toString(postData.length));
        connection.setUseCaches(false);

        try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
            wr.write(postData);
        }

        //get cookie
        cookies.clear();
        String headerName;
        for (int i = 1; (headerName = connection.getHeaderFieldKey(i)) != null; i++) {
            if (headerName.equals("Set-Cookie")) {
                cookies.add(connection.getHeaderField(i));
            }
        }

        InputStream response = connection.getInputStream();
        String line = readResponse(response);
        logger.debug("Unifi response: " + line);
        return checkResponse(line);

    } catch (MalformedURLException e) {
        logger.error("The URL '" + url + "' is malformed: " + e.toString());
    } catch (Exception e) {
        logger.error("Cannot get Ubiquiti Unifi login cookie: " + e.toString());
    }
    return false;
}

From source file:org.openhab.binding.unifi.internal.UnifiBinding.java

private String sendToController(String url, String urlParameters, String method) {
    try {/*from   w  w w . j  a v a 2 s.com*/
        synchronized (cookies) {
            byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);

            URL cookieUrl = new URL(url);
            HttpsURLConnection connection = (HttpsURLConnection) cookieUrl.openConnection();

            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod(method);
            //for(String cookie : cookies) {
            connection.setRequestProperty("Cookie", cookies.get(0) + "; " + cookies.get(1));
            //}

            if (urlParameters.length() > 0) {
                connection.setDoOutput(true);
                connection.setRequestProperty("Content-Length", Integer.toString(postData.length));
                connection.setUseCaches(false);

                try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
                    wr.write(postData);
                }
            }

            InputStream response = connection.getInputStream();
            String line = readResponse(response);
            if (!checkResponse(line)) {
                logger.error("Unifi response: " + line);

            }
            return line;
        }
    } catch (MalformedURLException e) {
        logger.error("The URL '" + url + "' is malformed: " + e.toString());
    } catch (Exception e) {
        logger.error("Cannot send data " + urlParameters + " to url " + url + ". Exception: " + e.toString());
    }
    return "";
}

From source file:com.gmt2001.TwitchAPIv3.java

@SuppressWarnings("UseSpecificCatch")
private JSONObject GetData(request_type type, String url, String post, String oauth, boolean isJson) {
    JSONObject j = new JSONObject("{}");
    InputStream i = null;//from ww  w . jav  a 2  s .c  o  m
    String rawcontent = "";

    try {
        if (url.contains("?")) {
            url += "&utcnow=" + System.currentTimeMillis();
        } else {
            url += "?utcnow=" + System.currentTimeMillis();
        }

        URL u = new URL(url);
        HttpsURLConnection c = (HttpsURLConnection) u.openConnection();

        c.addRequestProperty("Accept", header_accept);

        if (isJson) {
            c.addRequestProperty("Content-Type", "application/json");
        } else {
            c.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        }

        if (!clientid.isEmpty()) {
            c.addRequestProperty("Client-ID", clientid);
        }

        if (!oauth.isEmpty()) {
            c.addRequestProperty("Authorization", "OAuth " + oauth);
        }

        c.setRequestMethod(type.name());

        c.setUseCaches(false);
        c.setDefaultUseCaches(false);
        c.setConnectTimeout(timeout);
        c.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.52 Safari/537.36 PhantomBotJ/2015");

        if (!post.isEmpty()) {
            c.setDoOutput(true);
        }

        c.connect();

        if (!post.isEmpty()) {
            try (OutputStream o = c.getOutputStream()) {
                IOUtils.write(post, o);
            }
        }

        String content;

        if (c.getResponseCode() == 200) {
            i = c.getInputStream();
        } else {
            i = c.getErrorStream();
        }

        if (c.getResponseCode() == 204 || i == null) {
            content = "{}";
        } else {
            content = IOUtils.toString(i, c.getContentEncoding());
        }

        rawcontent = content;

        j = new JSONObject(content);
        j.put("_success", true);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", c.getResponseCode());
        j.put("_exception", "");
        j.put("_exceptionMessage", "");
        j.put("_content", content);
    } catch (JSONException ex) {
        if (ex.getMessage().contains("A JSONObject text must begin with")) {
            j = new JSONObject("{}");
            j.put("_success", true);
            j.put("_type", type.name());
            j.put("_url", url);
            j.put("_post", post);
            j.put("_http", 0);
            j.put("_exception", "");
            j.put("_exceptionMessage", "");
            j.put("_content", rawcontent);
        } else {
            com.gmt2001.Console.err.logStackTrace(ex);
        }
    } catch (NullPointerException ex) {
        com.gmt2001.Console.err.printStackTrace(ex);
    } catch (MalformedURLException ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_exception", "MalformedURLException");
        j.put("_exceptionMessage", ex.getMessage());
        j.put("_content", "");
        com.gmt2001.Console.err.logStackTrace(ex);
    } catch (SocketTimeoutException ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_exception", "SocketTimeoutException");
        j.put("_exceptionMessage", ex.getMessage());
        j.put("_content", "");
        com.gmt2001.Console.err.logStackTrace(ex);
    } catch (IOException ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_exception", "IOException");
        j.put("_exceptionMessage", ex.getMessage());
        j.put("_content", "");
        com.gmt2001.Console.err.logStackTrace(ex);
    } catch (Exception ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_exception", "Exception [" + ex.getClass().getName() + "]");
        j.put("_exceptionMessage", ex.getMessage());
        j.put("_content", "");
        com.gmt2001.Console.err.logStackTrace(ex);
    }

    if (i != null) {
        try {
            i.close();
        } catch (IOException ex) {
            j.put("_success", false);
            j.put("_type", type.name());
            j.put("_url", url);
            j.put("_post", post);
            j.put("_http", 0);
            j.put("_exception", "IOException");
            j.put("_exceptionMessage", ex.getMessage());
            j.put("_content", "");
            com.gmt2001.Console.err.logStackTrace(ex);
        }
    }

    return j;
}

From source file:com.adobe.ibm.watson.traits.impl.WatsonServiceClient.java

/**
 * Fetches the IBM Watson Personal Insights report using the user's Twitter Timeline.
 * @param language//w ww .  ja  v a  2 s. c om
 * @param tweets
 * @param resource
 * @return
 * @throws Exception
 */
public String getWatsonScore(String language, String tweets, Resource resource) throws Exception {

    HttpsURLConnection connection = null;

    // Check if the username and password have been injected to the service.
    // If not, extract them from the cloud service configuration attached to the page.
    if (this.username == null || this.password == null) {
        getWatsonCloudSettings(resource);
    }

    // Build the request to IBM Watson.
    log.info("The Base Url is: " + this.baseUrl);
    String encodedCreds = getBasicAuthenticationEncoding();
    URL url = new URL(this.baseUrl + "/v2/profile");

    connection = (HttpsURLConnection) url.openConnection();
    connection.setRequestMethod("POST");
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setRequestProperty("Accept", "application/json");
    connection.setRequestProperty("Content-Language", language);
    connection.setRequestProperty("Accept-Language", "en-us");
    connection.setRequestProperty("Content-Type", ContentType.TEXT_PLAIN.toString());
    connection.setRequestProperty("Authorization", "Basic " + encodedCreds);
    connection.setUseCaches(false);
    connection.getOutputStream().write(tweets.getBytes());
    connection.getOutputStream().flush();
    connection.connect();

    log.info("Parsing response from Watson");
    StringBuilder str = new StringBuilder();

    BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String line = "";
    while ((line = br.readLine()) != null) {
        str.append(line + System.getProperty("line.separator"));
    }

    if (connection.getResponseCode() != 200) {
        // The call failed, throw an exception.
        log.error(connection.getResponseCode() + " : " + connection.getResponseMessage());
        connection.disconnect();
        throw new Exception("IBM Watson Server responded with an error: " + connection.getResponseMessage());
    } else {
        connection.disconnect();
        return str.toString();
    }
}

From source file:org.appspot.apprtc.util.AsyncHttpURLConnection.java

private void sendHttpMessage() {
    if (mIsBitmap) {
        Bitmap bitmap = ThumbnailsCacheManager.getBitmapFromDiskCache(url);

        if (bitmap != null) {
            events.onHttpComplete(bitmap);
            return;
        }/*w  w w. jav a 2 s .co m*/
    }

    X509TrustManager trustManager = new X509TrustManager() {

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            // NOTE : This is where we can calculate the certificate's fingerprint,
            // show it to the user and throw an exception in case he doesn't like it
        }

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }
    };

    //HttpsURLConnection.setDefaultHostnameVerifier(new NullHostNameVerifier());
    // Create a trust manager that does not validate certificate chains
    X509TrustManager[] trustAllCerts = new X509TrustManager[] { trustManager };

    // Install the all-trusting trust manager
    SSLSocketFactory noSSLv3Factory = null;
    try {
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
            noSSLv3Factory = new TLSSocketFactory(trustAllCerts, new SecureRandom());
        } else {
            noSSLv3Factory = sc.getSocketFactory();
        }
        HttpsURLConnection.setDefaultSSLSocketFactory(noSSLv3Factory);
    } catch (GeneralSecurityException e) {
    }

    HttpsURLConnection connection = null;
    try {
        URL urlObj = new URL(url);
        connection = (HttpsURLConnection) urlObj.openConnection();
        connection.setSSLSocketFactory(noSSLv3Factory);

        HttpsURLConnection.setDefaultHostnameVerifier(new NullHostNameVerifier(urlObj.getHost()));
        connection.setHostnameVerifier(new NullHostNameVerifier(urlObj.getHost()));
        byte[] postData = new byte[0];
        if (message != null) {
            postData = message.getBytes("UTF-8");
        }

        if (msCookieManager.getCookieStore().getCookies().size() > 0) {
            // While joining the Cookies, use ',' or ';' as needed. Most of the servers are using ';'
            connection.setRequestProperty("Cookie",
                    TextUtils.join(";", msCookieManager.getCookieStore().getCookies()));
        }

        /*if (method.equals("PATCH")) {
          connection.setRequestProperty("X-HTTP-Method-Override", "PATCH");
          connection.setRequestMethod("POST");
        }
        else {*/
        connection.setRequestMethod(method);
        //}

        if (authorization.length() != 0) {
            connection.setRequestProperty("Authorization", authorization);
        }
        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setConnectTimeout(HTTP_TIMEOUT_MS);
        connection.setReadTimeout(HTTP_TIMEOUT_MS);
        // TODO(glaznev) - query request origin from pref_room_server_url_key preferences.
        //connection.addRequestProperty("origin", HTTP_ORIGIN);
        boolean doOutput = false;
        if (method.equals("POST") || method.equals("PATCH")) {
            doOutput = true;
            connection.setDoOutput(true);
            connection.setFixedLengthStreamingMode(postData.length);
        }
        if (contentType == null) {
            connection.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
        } else {
            connection.setRequestProperty("Content-Type", contentType);
        }

        // Send POST request.
        if (doOutput && postData.length > 0) {
            OutputStream outStream = connection.getOutputStream();
            outStream.write(postData);
            outStream.close();
        }

        // Get response.
        int responseCode = 200;
        try {
            connection.getResponseCode();
        } catch (IOException e) {

        }
        getCookies(connection);
        InputStream responseStream;

        if (responseCode > 400) {
            responseStream = connection.getErrorStream();
        } else {
            responseStream = connection.getInputStream();
        }

        String responseType = connection.getContentType();
        if (responseType.startsWith("image/")) {
            Bitmap bitmap = BitmapFactory.decodeStream(responseStream);
            if (mIsBitmap && bitmap != null) {
                ThumbnailsCacheManager.addBitmapToCache(url, bitmap);
            }
            events.onHttpComplete(bitmap);
        } else {
            String response = drainStream(responseStream);
            events.onHttpComplete(response);
        }
        responseStream.close();
        connection.disconnect();
    } catch (SocketTimeoutException e) {
        events.onHttpError("HTTP " + method + " to " + url + " timeout");
    } catch (IOException e) {
        if (connection != null) {
            connection.disconnect();
        }
        events.onHttpError("HTTP " + method + " to " + url + " error: " + e.getMessage());
    } catch (ClassCastException e) {
        e.printStackTrace();
    }
}

From source file:io.teak.sdk.Session.java

private void startHeartbeat() {
    final Session _this = this;

    this.heartbeatService = Executors.newSingleThreadScheduledExecutor();
    this.heartbeatService.scheduleAtFixedRate(new Runnable() {
        public void run() {
            if (Teak.isDebug) {
                Log.v(LOG_TAG, "Sending heartbeat for user: " + userId);
            }/*w  ww. ja  va  2  s .c o  m*/

            HttpsURLConnection connection = null;
            try {
                String queryString = "game_id=" + URLEncoder.encode(_this.appConfiguration.appId, "UTF-8")
                        + "&api_key=" + URLEncoder.encode(_this.userId, "UTF-8") + "&sdk_version="
                        + URLEncoder.encode(Teak.SDKVersion, "UTF-8") + "&sdk_platform="
                        + URLEncoder.encode(_this.deviceConfiguration.platformString, "UTF-8") + "&app_version="
                        + URLEncoder.encode(String.valueOf(_this.appConfiguration.appVersion), "UTF-8")
                        + (_this.countryCode == null ? ""
                                : "&country_code="
                                        + URLEncoder.encode(String.valueOf(_this.countryCode), "UTF-8"))
                        + "&buster=" + URLEncoder.encode(UUID.randomUUID().toString(), "UTF-8");
                URL url = new URL("https://iroko.gocarrot.com/ping?" + queryString);
                connection = (HttpsURLConnection) url.openConnection();
                connection.setRequestProperty("Accept-Charset", "UTF-8");
                connection.setUseCaches(false);

                int responseCode = connection.getResponseCode();
                if (Teak.isDebug) {
                    Log.v(LOG_TAG, "Heartbeat response code: " + responseCode);
                }
            } catch (Exception e) {
                Log.e(LOG_TAG, Log.getStackTraceString(e));
            } finally {
                if (connection != null) {
                    connection.disconnect();
                }
            }
        }
    }, 0, 1, TimeUnit.MINUTES); // TODO: If RemoteConfiguration specifies a different rate, use that
}

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

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

    //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", "postSecureData()--> # of records: " + size);

    //save timestamp
    long lastTimestamp = 0;
    if (lastToSendRecord.mSysTimestamp > 0)
        lastTimestamp = lastToSendRecord.mSysTimestamp;
    else// w ww .j a  v  a  2s  .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 **************

    URL url = new URL(Utils.report_url);
    HttpsURLConnection con = (HttpsURLConnection) url.openConnection();

    con.setRequestMethod("POST");
    con.setUseCaches(false);
    con.setDoInput(true);
    con.setDoOutput(true);

    con.setRequestProperty("Content-Encoding", "gzip");
    con.setRequestProperty("Content-Type", "application/json");
    con.setRequestProperty("Accept", "application/json");
    con.setRequestProperty("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()))
        con.setRequestProperty("Authorization", "Bearer " + Utils.getAccessToken(getApplicationContext()));
    else if (Utils.getAccountActivationStateForClient(getApplicationContext()))
        con.setRequestProperty("Authorization",
                "Bearer " + Utils.getAccessTokenForClient(getApplicationContext()));

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

    con.setRequestProperty("meta" + Constants.separators[sepIndex] + "timestampRecorded", lastTsFormatted);
    //con.setRequestProperty("meta"+Constants.separators[sepIndex]+"sessionId", lastToSendRecord.mSessionId); //deprecated from AP 1.4
    con.setRequestProperty("meta" + Constants.separators[sepIndex] + "deviceId", Utils.deviceID);
    con.setRequestProperty("meta" + Constants.separators[sepIndex] + "installId", Utils.installID);
    //con.setRequestProperty("meta"+Constants.separators[sepIndex]+"userFeedId", "");
    //con.setRequestProperty("meta"+Constants.separators[sepIndex]+"eventFeedId", "");
    con.setRequestProperty("meta" + Constants.separators[sepIndex] + "visibilityEvent",
            Constants.DATA_VISIBILITY[0]);
    con.setRequestProperty("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(""))) {
        Log.d("StoreAndForwardService", "postSecureData()--> box mac address: " + lastToSendRecord.mBoxMac);
        con.setRequestProperty("meta" + Constants.separators[sepIndex] + "sourceId", lastToSendRecord.mBoxMac);
    } else
        con.setRequestProperty("meta" + Constants.separators[sepIndex] + "sourceId",
                Utils.getDeviceAddress(getApplicationContext()));

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

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

    con.setRequestProperty("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)

    con.setRequestProperty("data" + Constants.separators[sepIndex] + "contentDetails"
            + Constants.separators[sepIndex] + "type", "airprobe_report");
    con.setRequestProperty("data" + Constants.separators[sepIndex] + "contentDetails"
            + Constants.separators[sepIndex] + "format", "json");
    //con.setRequestProperty("data"+Constants.separators[sepIndex]+"contentDetails"+Constants.separators[sepIndex]+"specification", "a-3"); //deprecated from AP 1.4
    if (size > 1)
        con.setRequestProperty("data" + Constants.separators[sepIndex] + "contentDetails"
                + Constants.separators[sepIndex] + "list", "true");
    else
        con.setRequestProperty("data" + Constants.separators[sepIndex] + "contentDetails"
                + Constants.separators[sepIndex] + "list", "false");
    con.setRequestProperty("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
    {
        con.setRequestProperty("geo" + Constants.separators[sepIndex] + "longitude",
                String.valueOf(lastToSendRecord.mBoxLon));
        con.setRequestProperty("geo" + Constants.separators[sepIndex] + "latitude",
                String.valueOf(lastToSendRecord.mBoxLat));
        if (lastToSendRecord.mBoxAcc != 0)
            con.setRequestProperty("geo" + Constants.separators[sepIndex] + "hdop",
                    String.valueOf(lastToSendRecord.mBoxAcc)); //from AP 1.4
        if (lastToSendRecord.mBoxAltitude != 0)
            con.setRequestProperty("geo" + Constants.separators[sepIndex] + "altitude",
                    String.valueOf(lastToSendRecord.mBoxAltitude)); //from AP 1.4
        if (lastToSendRecord.mBoxSpeed != 0)
            con.setRequestProperty("geo" + Constants.separators[sepIndex] + "speed",
                    String.valueOf(lastToSendRecord.mBoxSpeed)); //from AP 1.4
        if (lastToSendRecord.mBoxBear != 0)
            con.setRequestProperty("geo" + Constants.separators[sepIndex] + "bearing",
                    String.valueOf(lastToSendRecord.mBoxBear)); //from AP 1.4           
        con.setRequestProperty("geo" + Constants.separators[sepIndex] + "provider",
                lastToSendRecord.mGpsProvider);
        con.setRequestProperty("geo" + Constants.separators[sepIndex] + "timestamp", lastTsFormatted);
    } else if (lastToSendRecord.mGpsProvider.equals(Constants.GPS_PROVIDERS[1])) //phone
    {
        con.setRequestProperty("geo" + Constants.separators[sepIndex] + "longitude",
                String.valueOf(lastToSendRecord.mPhoneLon));
        con.setRequestProperty("geo" + Constants.separators[sepIndex] + "latitude",
                String.valueOf(lastToSendRecord.mPhoneLat));
        if (lastToSendRecord.mPhoneAcc != 0)
            con.setRequestProperty("geo" + Constants.separators[sepIndex] + "accuracy",
                    String.valueOf(lastToSendRecord.mPhoneAcc));
        if (lastToSendRecord.mPhoneAltitude != 0)
            con.setRequestProperty("geo" + Constants.separators[sepIndex] + "altitude",
                    String.valueOf(lastToSendRecord.mPhoneAltitude)); //from AP 1.4
        if (lastToSendRecord.mPhoneSpeed != 0)
            con.setRequestProperty("geo" + Constants.separators[sepIndex] + "speed",
                    String.valueOf(lastToSendRecord.mPhoneSpeed)); //from AP 1.4
        if (lastToSendRecord.mPhoneBear != 0)
            con.setRequestProperty("geo" + Constants.separators[sepIndex] + "bearing",
                    String.valueOf(lastToSendRecord.mPhoneBear)); //from AP 1.4
        con.setRequestProperty("geo" + Constants.separators[sepIndex] + "provider",
                lastToSendRecord.mGpsProvider);
        con.setRequestProperty("geo" + Constants.separators[sepIndex] + "timestamp", lastTsFormatted);
    } else if (lastToSendRecord.mGpsProvider.equals(Constants.GPS_PROVIDERS[2])) //network
    {
        con.setRequestProperty("geo" + Constants.separators[sepIndex] + "longitude",
                String.valueOf(lastToSendRecord.mNetworkLon));
        con.setRequestProperty("geo" + Constants.separators[sepIndex] + "latitude",
                String.valueOf(lastToSendRecord.mNetworkLat));
        if (lastToSendRecord.mNetworkAcc != 0)
            con.setRequestProperty("geo" + Constants.separators[sepIndex] + "accuracy",
                    String.valueOf(lastToSendRecord.mNetworkAcc));
        if (lastToSendRecord.mNetworkAltitude != 0)
            con.setRequestProperty("geo" + Constants.separators[sepIndex] + "altitude",
                    String.valueOf(lastToSendRecord.mNetworkAltitude)); //from AP 1.4
        if (lastToSendRecord.mNetworkSpeed != 0)
            con.setRequestProperty("geo" + Constants.separators[sepIndex] + "speed",
                    String.valueOf(lastToSendRecord.mNetworkSpeed)); //from AP 1.4
        if (lastToSendRecord.mNetworkBear != 0)
            con.setRequestProperty("geo" + Constants.separators[sepIndex] + "bearing",
                    String.valueOf(lastToSendRecord.mNetworkBear)); //from AP 1.4            
        con.setRequestProperty("geo" + Constants.separators[sepIndex] + "provider",
                lastToSendRecord.mGpsProvider);
        con.setRequestProperty("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", "postSecureData()--> json: " +sb.toString());
    //Log.d("StoreAndForwardService", "postSecureData()--> access token: "+Utils.getAccessToken(getApplicationContext()));

    //compress json content into byte array entity
    byte[] contentGzippedBytes = zipStringToBytes(sb.toString());

    //write json compressed content into output stream
    OutputStream outputStream = con.getOutputStream();
    outputStream.write(contentGzippedBytes);
    outputStream.flush();
    outputStream.close();

    int responseCode = con.getResponseCode();

    Log.d("StoreAndForwardService", "postSecureData()--> response code: " + responseCode);

    sb = null;

    return responseCode;
}

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

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

    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", "postSecureTags()--> # 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 **************

                URL url = new URL(Utils.report_url);
                HttpsURLConnection con = (HttpsURLConnection) url.openConnection();

                con.setRequestMethod("POST");
                con.setUseCaches(false);
                con.setDoInput(true);//  ww w.  j av a 2s. c o  m
                con.setDoOutput(true);

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

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

                if (Utils.getAccountActivationState(getApplicationContext()))
                    con.setRequestProperty("Authorization",
                            "Bearer " + Utils.getAccessToken(getApplicationContext()));
                else if (Utils.getAccountActivationStateForClient(getApplicationContext()))
                    con.setRequestProperty("Authorization",
                            "Bearer " + Utils.getAccessTokenForClient(getApplicationContext()));

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

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

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

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

                con.setRequestProperty("data" + Constants.separators[sepIndex] + "contentDetails"
                        + Constants.separators[sepIndex] + "type", "airprobe_tags");
                con.setRequestProperty("data" + Constants.separators[sepIndex] + "contentDetails"
                        + Constants.separators[sepIndex] + "format", "json");
                //con.setRequestProperty("data"+Constants.separators[sepIndex]+"contentDetails"+Constants.separators[sepIndex]+"specification", "at-3");   //update by increment this field on header changes    
                if (size > 1)
                    con.setRequestProperty("data" + Constants.separators[sepIndex] + "contentDetails"
                            + Constants.separators[sepIndex] + "list", "true");
                else
                    con.setRequestProperty("data" + Constants.separators[sepIndex] + "contentDetails"
                            + Constants.separators[sepIndex] + "list", "false");
                con.setRequestProperty("data" + Constants.separators[sepIndex] + "contentDetails"
                        + Constants.separators[sepIndex] + "listSize", String.valueOf(size));

                /* from AP 1.4 */
                if ((lastToSendRecord.mBoxMac != null) && (!lastToSendRecord.mBoxMac.equals(""))) {
                    Log.d("StoreAndForwardService",
                            "postSecureData()--> box mac address: " + lastToSendRecord.mBoxMac);
                    con.setRequestProperty("meta" + Constants.separators[sepIndex] + "sourceId",
                            lastToSendRecord.mBoxMac);
                } else
                    con.setRequestProperty("meta" + Constants.separators[sepIndex] + "sourceId",
                            Utils.getDeviceAddress(getApplicationContext()));

                con.setRequestProperty("data" + Constants.separators[sepIndex] + "extendedSourceSessionId"
                        + Constants.separators[sepIndex] + "seed", lastToSendRecord.mSourceSessionSeed);
                con.setRequestProperty(
                        "data" + Constants.separators[sepIndex] + "extendedSourceSessionId"
                                + Constants.separators[sepIndex] + "number",
                        String.valueOf(lastToSendRecord.mSourceSessionNumber));
                if ((lastToSendRecord.mSemanticSessionSeed != null)
                        && (!lastToSendRecord.mSemanticSessionSeed.equals(""))) {
                    con.setRequestProperty(
                            "data" + Constants.separators[sepIndex] + "extendedSemanticSessionId"
                                    + Constants.separators[sepIndex] + "seed",
                            lastToSendRecord.mSemanticSessionSeed);
                    con.setRequestProperty(
                            "data" + Constants.separators[sepIndex] + "extendedSemanticSessionId"
                                    + Constants.separators[sepIndex] + "number",
                            String.valueOf(lastToSendRecord.mSemanticSessionNumber));
                }

                con.setRequestProperty("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
                {
                    con.setRequestProperty("geo" + Constants.separators[sepIndex] + "longitude",
                            String.valueOf(lastToSendRecord.mBoxLon));
                    con.setRequestProperty("geo" + Constants.separators[sepIndex] + "latitude",
                            String.valueOf(lastToSendRecord.mBoxLat));
                    con.setRequestProperty("geo" + Constants.separators[sepIndex] + "provider",
                            lastToSendRecord.mGpsProvider);
                    con.setRequestProperty("geo" + Constants.separators[sepIndex] + "timestamp",
                            lastTsFormatted);
                } else if (lastToSendRecord.mGpsProvider.equals(Constants.GPS_PROVIDERS[1])) //phone
                {
                    con.setRequestProperty("geo" + Constants.separators[sepIndex] + "longitude",
                            String.valueOf(lastToSendRecord.mPhoneLon));
                    con.setRequestProperty("geo" + Constants.separators[sepIndex] + "latitude",
                            String.valueOf(lastToSendRecord.mPhoneLat));
                    con.setRequestProperty("geo" + Constants.separators[sepIndex] + "accuracy",
                            String.valueOf(lastToSendRecord.mPhoneAcc));
                    con.setRequestProperty("geo" + Constants.separators[sepIndex] + "altitude",
                            String.valueOf(lastToSendRecord.mPhoneAltitude)); //from AP 1.4
                    con.setRequestProperty("geo" + Constants.separators[sepIndex] + "speed",
                            String.valueOf(lastToSendRecord.mPhoneSpeed)); //from AP 1.4
                    con.setRequestProperty("geo" + Constants.separators[sepIndex] + "bearing",
                            String.valueOf(lastToSendRecord.mPhoneBear)); //from AP 1.4
                    con.setRequestProperty("geo" + Constants.separators[sepIndex] + "provider",
                            lastToSendRecord.mGpsProvider);
                    con.setRequestProperty("geo" + Constants.separators[sepIndex] + "timestamp",
                            lastTsFormatted);
                } else if (lastToSendRecord.mGpsProvider.equals(Constants.GPS_PROVIDERS[2])) //network
                {
                    con.setRequestProperty("geo" + Constants.separators[sepIndex] + "longitude",
                            String.valueOf(lastToSendRecord.mNetworkLon));
                    con.setRequestProperty("geo" + Constants.separators[sepIndex] + "latitude",
                            String.valueOf(lastToSendRecord.mNetworkLat));
                    con.setRequestProperty("geo" + Constants.separators[sepIndex] + "accuracy",
                            String.valueOf(lastToSendRecord.mNetworkAcc));
                    con.setRequestProperty("geo" + Constants.separators[sepIndex] + "altitude",
                            String.valueOf(lastToSendRecord.mNetworkAltitude)); //from AP 1.4
                    con.setRequestProperty("geo" + Constants.separators[sepIndex] + "speed",
                            String.valueOf(lastToSendRecord.mNetworkSpeed)); //from AP 1.4
                    con.setRequestProperty("geo" + Constants.separators[sepIndex] + "bearing",
                            String.valueOf(lastToSendRecord.mNetworkBear)); //from AP 1.4            
                    con.setRequestProperty("geo" + Constants.separators[sepIndex] + "provider",
                            lastToSendRecord.mGpsProvider);
                    con.setRequestProperty("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);
                        //boxLocation.put("accuracy", "null");
                        //boxLocation.put("altitude", "null");
                        //boxLocation.put("speed", "null");
                        //boxLocation.put("bearing", "null");
                        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);
                        phoneLocation.put("accuracy", lastToSendRecord.mAccuracy);
                        phoneLocation.put("altitude", lastToSendRecord.mPhoneAltitude);
                        phoneLocation.put("speed", lastToSendRecord.mPhoneSpeed);
                        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);
                        netLocation.put("accuracy", lastToSendRecord.mNetworkAcc);
                        netLocation.put("altitude", lastToSendRecord.mNetworkAltitude);
                        netLocation.put("speed", lastToSendRecord.mNetworkSpeed);
                        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", "postSecureTags()--> 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", "postSecureTags()--> json to string: " + sb.toString());

                //compress json content into byte array entity
                byte[] contentGzippedBytes = zipStringToBytes(sb.toString());

                //write json compressed content into output stream
                OutputStream outputStream = con.getOutputStream();
                outputStream.write(contentGzippedBytes);
                outputStream.flush();
                outputStream.close();

                int responseCode = con.getResponseCode();

                Log.d("StoreAndForwardService", "postSecureTags()--> response code: " + responseCode);

                sb = null;

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