Example usage for javax.net.ssl HttpsURLConnection setDoOutput

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

Introduction

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

Prototype

public void setDoOutput(boolean dooutput) 

Source Link

Document

Sets the value of the doOutput field for this URLConnection to the specified value.

Usage

From source file:org.globusonline.nexus.BaseNexusRestClient.java

/**
 * @param path/*from   w  w w .jav a 2s  . c om*/
 * @return JSON Response from action
 * @throws NexusClientException
 */
protected JSONObject issueRestRequest(String path, String httpMethod, String contentType, String accept,
        JSONObject params, NexusAuthenticator auth) throws NexusClientException {

    JSONObject json = null;

    HttpsURLConnection connection;

    if (httpMethod.isEmpty()) {
        httpMethod = "GET";
    }
    if (contentType.isEmpty()) {
        contentType = "application/json";
    }
    if (accept.isEmpty()) {
        accept = "application/json";
    }
    int responseCode;

    try {

        URL url = new URL(getNexusApiUrl() + path);

        connection = (HttpsURLConnection) url.openConnection();

        if (ignoreCertErrors) {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new SecureRandom());
            connection.setSSLSocketFactory(sc.getSocketFactory());
            connection.setHostnameVerifier(allHostsValid);
        }

        if (auth != null) {
            auth.authenticate(connection);
        }

        connection.setDoOutput(true);
        connection.setInstanceFollowRedirects(false);
        connection.setRequestMethod(httpMethod);
        connection.setRequestProperty("Content-Type", contentType);
        connection.setRequestProperty("Accept", accept);
        connection.setRequestProperty("X-Go-Community-Context", community);

        String body = "";

        if (params != null) {
            OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
            body = params.toString();
            out.write(body);
            logger.debug("Body:" + body);
            out.close();
        }

        responseCode = connection.getResponseCode();

    } catch (Exception e) {
        logger.error("Unhandled connection error:", e);
        throw new ValueErrorException();
    }

    logger.info("ConnectionURL: " + connection.getURL());

    if (responseCode == 403 || responseCode == 400) {
        logger.error("Access is denied.  Invalid credentials.");
        throw new InvalidCredentialsException();
    }
    if (responseCode == 404) {
        logger.error("URL not found.");
        throw new InvalidUrlException();
    }
    if (responseCode == 500) {
        logger.error("Internal Server Error.");
        throw new ValueErrorException();
    }
    if (responseCode != 200) {
        logger.info("Response code is: " + responseCode);
    }

    try {
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String decodedString = in.readLine();

        json = new JSONObject(decodedString);
    } catch (JSONException e) {
        logger.error("JSON Error", e);
        throw new ValueErrorException();
    } catch (IOException e) {
        logger.error("IO Error", e);
        throw new ValueErrorException();
    }

    return json;
}

From source file:eu.faircode.netguard.ServiceJob.java

@Override
public boolean onStartJob(JobParameters params) {
    Log.i(TAG, "Start job=" + params.getJobId());

    new AsyncTask<JobParameters, Object, Object>() {

        @Override/*from  w ww  .  j a va 2  s.  c o  m*/
        protected JobParameters doInBackground(JobParameters... params) {
            Log.i(TAG, "Executing job=" + params[0].getJobId());

            HttpsURLConnection urlConnection = null;
            try {
                String android_id = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
                JSONObject json = new JSONObject();

                json.put("device", Util.sha256(android_id, ""));
                json.put("product", Build.DEVICE);
                json.put("sdk", Build.VERSION.SDK_INT);
                json.put("country", Locale.getDefault().getCountry());

                json.put("netguard", Util.getSelfVersionCode(ServiceJob.this));
                try {
                    json.put("store", getPackageManager().getInstallerPackageName(getPackageName()));
                } catch (Throwable ex) {
                    Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                    json.put("store", null);
                }

                for (String name : params[0].getExtras().keySet())
                    json.put(name, params[0].getExtras().get(name));

                urlConnection = (HttpsURLConnection) new URL(cUrl).openConnection();
                urlConnection.setConnectTimeout(cTimeOutMs);
                urlConnection.setReadTimeout(cTimeOutMs);
                urlConnection.setRequestProperty("Accept", "application/json");
                urlConnection.setRequestProperty("Content-type", "application/json");
                urlConnection.setRequestMethod("POST");
                urlConnection.setDoInput(true);
                urlConnection.setDoOutput(true);

                OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
                out.write(json.toString().getBytes()); // UTF-8
                out.flush();

                int code = urlConnection.getResponseCode();
                if (code != HttpsURLConnection.HTTP_OK)
                    throw new IOException("HTTP " + code);

                InputStreamReader isr = new InputStreamReader(urlConnection.getInputStream());
                Log.i(TAG, "Response=" + Util.readString(isr).toString());

                jobFinished(params[0], false);

                if ("rule".equals(params[0].getExtras().getString("type"))) {
                    SharedPreferences history = getSharedPreferences("history", Context.MODE_PRIVATE);
                    history.edit().putLong(params[0].getExtras().getString("package") + ":submitted",
                            new Date().getTime()).apply();
                }

            } catch (Throwable ex) {
                Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                jobFinished(params[0], true);

            } finally {
                if (urlConnection != null)
                    urlConnection.disconnect();

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ignored) {
                }
            }

            return null;
        }
    }.execute(params);

    return true;
}

From source file:com.gmt2001.TwitchAPIv5.java

@SuppressWarnings("UseSpecificCatch")
private JSONObject GetData(request_type type, String url, String post, String oauth, boolean isJson) {
    JSONObject j = new JSONObject("{}");
    InputStream i = null;//  w  w w.ja v  a2s .  c  o  m
    String content = "";

    try {
        URL u = new URL(url);
        HttpsURLConnection c = (HttpsURLConnection) u.openConnection();
        c.addRequestProperty("Accept", header_accept);
        c.addRequestProperty("Content-Type", isJson ? "application/json" : "application/x-www-form-urlencoded");

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

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

        c.setRequestMethod(type.name());
        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);
            }
        }

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

        if (c.getResponseCode() == 204 || i == null) {
            content = "{}";
        } else {
            // default to UTF-8, it'll probably be the best bet if there's
            // no charset specified.
            String charset = "utf-8";
            String ct = c.getContentType();
            if (ct != null) {
                String[] cts = ct.split(" *; *");
                for (int idx = 1; idx < cts.length; ++idx) {
                    String[] val = cts[idx].split("=", 2);
                    if (val[0] == "charset" && val.length > 1) {
                        charset = val[1];
                    }
                }
            }

            if ("gzip".equals(c.getContentEncoding())) {
                i = new GZIPInputStream(i);
            }

            content = IOUtils.toString(i, charset);
        }

        j = new JSONObject(content);
        fillJSONObject(j, true, type.name(), post, url, c.getResponseCode(), "", "", content);
    } catch (Exception ex) {
        Throwable rootCause = ex;
        while (rootCause.getCause() != null && rootCause.getCause() != rootCause) {
            rootCause = rootCause.getCause();
        }

        fillJSONObject(j, false, type.name(), post, url, 0, ex.getClass().getSimpleName(), ex.getMessage(),
                content);
        com.gmt2001.Console.debug
                .println("Failed to get data [" + ex.getClass().getSimpleName() + "]: " + ex.getMessage());
    } finally {
        if (i != null) {
            try {
                i.close();
            } catch (IOException ex) {
                fillJSONObject(j, false, type.name(), post, url, 0, "IOException", ex.getMessage(), content);
                com.gmt2001.Console.err.println("IOException: " + ex.getMessage());
            }
        }
    }

    return j;
}

From source file:com.siviton.huanapi.data.HuanApi.java

public void AutoLoginUser() {

    new Thread() {

        public void run() {

            JSONObject jsonObject2 = new JSONObject();
            try {
                jsonObject2.putOpt("dnum", getdnum());
                jsonObject2.putOpt("didtoken", getdidtoken());
            } catch (JSONException e2) {
                // TODO Auto-generated catch block
                e2.printStackTrace();/*from   w w w.j a v a2 s  .  c  om*/
            }
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.putOpt("action", "AutoLoginUser");
                jsonObject.putOpt("device", jsonObject2);
            } catch (JSONException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            try {
                byte[] entity = jsonObject.toString().getBytes();
                URL url = new URL(getDeviceUrl());
                HttpsURLConnection connections = (HttpsURLConnection) url.openConnection();
                if (connections instanceof HttpsURLConnection) {
                    // Trust all certificates
                    SSLContext context = SSLContext.getInstance("SSL");
                    context.init(new KeyManager[0], xtmArray, new SecureRandom());
                    SSLSocketFactory socketFactory = context.getSocketFactory();
                    ((HttpsURLConnection) connections).setSSLSocketFactory(socketFactory);
                    ((HttpsURLConnection) connections).setHostnameVerifier(HOSTNAME_VERIFIER);
                }
                connections.setConnectTimeout(5 * 1000);
                connections.setRequestMethod("POST");
                connections.setDoOutput(true);// ??
                connections.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                connections.setRequestProperty("Content-Length", String.valueOf(entity.length));
                OutputStream outStream = connections.getOutputStream();
                outStream.write(entity);
                outStream.flush();
                outStream.close();
                if (connections.getResponseCode() == 200) {
                    BufferedReader in = new BufferedReader(new InputStreamReader(connections.getInputStream()));
                    String line = "";
                    StringBuilder stringBuffer = new StringBuilder();
                    while ((line = in.readLine()) != null) {
                        stringBuffer.append("" + line + "\n");
                        System.out.println("==pengbdata==AutoLoginUser=====" + line);
                    }
                    in.close();

                    JSONObject object = new JSONObject("" + stringBuffer.toString());

                    JSONObject object2 = null;
                    try {
                        object2 = object.getJSONObject("error");
                        String code = object2.getString("code");
                        String info = object2.getString("info");
                        if (!code.equals("0")) {
                            mHuanLoginListen.StateChange(STATE_USERLOGIN, STATE_USERLOGIN_ERROR_COCDE,
                                    "" + info, null, null, null);
                        } else {
                            object2 = object.getJSONObject("user");
                            String huanid = object2.getString("huanid");
                            String token = object2.getString("token");
                            if (token != null && huanid != null) {
                                huanItemInfo.setToken(token);
                                huanItemInfo.setHuanid(huanid);
                                updateData();
                                mHuanLoginListen.StateChange(STATE_USERLOGIN, STATE_USERLOGIN_LOGIN_SUCC,
                                        "user succ", null, null, null);
                            } else {
                                // ?
                                mHuanLoginListen.StateChange(STATE_USERLOGIN, STATE_USERLOGIN_HUANIDTOKEN_NULL,
                                        "huanid or huanid is null", null, null, null);
                            }
                        }
                    } catch (Exception e) {
                        // TODO: handle exception
                        mHuanLoginListen.StateChange(STATE_USERLOGIN, STATE_USERLOGIN_JESON_EXCEPTION,
                                e.toString(), null, null, null);
                    }

                } else {
                    // 
                    mHuanLoginListen.StateChange(STATE_USERLOGIN, STATE_USERLOGIN_NETCODE_ISNO200,
                            "user   network error", null, null, null);
                }

            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
                mHuanLoginListen.StateChange(STATE_USERLOGIN, STATE_USERLOGIN_NETCODE_EXCEPTION,
                        "user   network error" + e.toString(), null, null, null);
            }

        };

    }.start();

}

From source file:com.siviton.huanapi.data.HuanApi.java

public void DeviceLogin() {

    new Thread() {

        public void run() {

            JSONObject jsonObject2 = new JSONObject();
            try {
                jsonObject2.putOpt("dnum", getdnum());
                jsonObject2.putOpt("didtoken", getdidtoken());
                jsonObject2.putOpt("activekey", getactivekey());
            } catch (JSONException e2) {
                // TODO Auto-generated catch block
                e2.printStackTrace();//from  w  w  w. jav  a  2  s  .  c o m
            }
            JSONObject jsonObject3 = new JSONObject();
            try {
                jsonObject3.putOpt("ostype", getostype());
                jsonObject3.putOpt("osversion", getosversion());
                jsonObject3.putOpt("kernelversion", getkernelversion());
                jsonObject3.putOpt("webinfo", getwebinfo());
                jsonObject3.putOpt("javainfo", getjavainfo());
                jsonObject3.putOpt("flashinfo", getflashinfo());
            } catch (JSONException e2) {
                // TODO Auto-generated catch block
                e2.printStackTrace();
            }
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.putOpt("action", "DeviceLogin");
                jsonObject.putOpt("device", jsonObject2);
                jsonObject.putOpt("param", jsonObject3);
            } catch (JSONException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            try {
                byte[] entity = jsonObject.toString().getBytes();
                URL url = new URL(getDeviceUrl());
                HttpsURLConnection connections = (HttpsURLConnection) url.openConnection();
                if (connections instanceof HttpsURLConnection) {
                    // Trust all certificates
                    SSLContext context = SSLContext.getInstance("SSL");
                    context.init(new KeyManager[0], xtmArray, new SecureRandom());
                    SSLSocketFactory socketFactory = context.getSocketFactory();
                    ((HttpsURLConnection) connections).setSSLSocketFactory(socketFactory);
                    ((HttpsURLConnection) connections).setHostnameVerifier(HOSTNAME_VERIFIER);
                }
                connections.setConnectTimeout(5 * 1000);
                connections.setRequestMethod("POST");
                connections.setDoOutput(true);// ??
                connections.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                connections.setRequestProperty("Content-Length", String.valueOf(entity.length));
                OutputStream outStream = connections.getOutputStream();
                outStream.write(entity);
                outStream.flush();
                outStream.close();
                if (connections.getResponseCode() == 200) {
                    BufferedReader in = new BufferedReader(new InputStreamReader(connections.getInputStream()));
                    String line = "";
                    StringBuilder stringBuffer = new StringBuilder();
                    while ((line = in.readLine()) != null) {
                        stringBuffer.append("" + line + "\n");
                        System.out.println("==pengbdata==DeviceLogin=====" + line);
                    }
                    in.close();

                    JSONObject object = new JSONObject("" + stringBuffer.toString());

                    JSONObject object2 = null;
                    try {
                        object2 = object.getJSONObject("error");
                        String code = object2.getString("code");
                        String info = object2.getString("info");
                        if (!code.equals("0")) {
                            mHuanLoginListen.StateChange(STATE_DEVICELOGIN, STATE_DEVICELOGIN_ERROR_COCDE,
                                    "" + info, null, null, null);
                        } else {
                            object2 = object.getJSONObject("device");
                            String activekey = object2.getString("activekey");
                            if (activekey != null) {
                                huanItemInfo.setActivekey(activekey);
                                huanItemInfo.setDidtoken(getMD5(getdeviceid() + getactivekey()));
                                System.out.println("==pengbdata==DeviceLogin======" + huanItemInfo.getDeviceid()
                                        + "===" + huanItemInfo.getDevicemodel() + "==="
                                        + huanItemInfo.getDidtoken() + "===" + huanItemInfo.getActivekey()
                                        + "===" + huanItemInfo.getDnum());
                                updateData();
                                mHuanLoginListen.StateChange(STATE_DEVICELOGIN, STATE_DEVICELOGIN_LOGIN_SUCC,
                                        "DeviceLogin succ", null, null, null);
                            } else {
                                // ?
                                mHuanLoginListen.StateChange(STATE_DEVICELOGIN,
                                        STATE_DEVICELOGIN_ACTIVEKEY_NULL, "dnum or activekey is null", null,
                                        null, null);
                            }
                        }
                    } catch (Exception e) {
                        // TODO: handle exception
                        mHuanLoginListen.StateChange(STATE_DEVICELOGIN, STATE_DEVICELOGIN_JESON_EXCEPTION,
                                e.toString(), null, null, null);
                    }

                } else {
                    // 
                    mHuanLoginListen.StateChange(STATE_DEVICELOGIN, STATE_DEVICELOGIN_NETCODE_ISNO200,
                            "DeviceLogin   network error", null, null, null);
                }

            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
                mHuanLoginListen.StateChange(STATE_DEVICELOGIN, STATE_DEVICELOGIN_NETCODE_EXCEPTION,
                        "DeviceLogin   network error" + e.toString(), null, null, null);
            }

        };

    }.start();

}

From source file:com.echopf.ECHOQuery.java

/**
 * Sends a HTTP request with optional request contents/parameters.
 * @param path a request url path//from ww w .java 2s .  c o  m
 * @param httpMethod a request method (GET/POST/PUT/DELETE)
 * @param data request contents/parameters
 * @param multipart use multipart/form-data to encode the contents
 * @throws ECHOException
 */
public static InputStream requestRaw(String path, String httpMethod, JSONObject data, boolean multipart)
        throws ECHOException {
    final String secureDomain = ECHO.secureDomain;
    if (secureDomain == null)
        throw new IllegalStateException("The SDK is not initialized.Please call `ECHO.initialize()`.");

    String baseUrl = new StringBuilder("https://").append(secureDomain).toString();
    String url = new StringBuilder(baseUrl).append("/").append(path).toString();

    HttpsURLConnection httpClient = null;

    try {
        URL urlObj = new URL(url);

        StringBuilder apiUrl = new StringBuilder(baseUrl).append(urlObj.getPath()).append("/rest_api=1.0/");

        // Append the QueryString contained in path
        boolean isContainQuery = urlObj.getQuery() != null;
        if (isContainQuery)
            apiUrl.append("?").append(urlObj.getQuery());

        // Append the QueryString from data
        if (httpMethod.equals("GET") && data != null) {
            boolean firstItem = true;
            Iterator<?> iter = data.keys();
            while (iter.hasNext()) {
                if (firstItem && !isContainQuery) {
                    firstItem = false;
                    apiUrl.append("?");
                } else {
                    apiUrl.append("&");
                }
                String key = (String) iter.next();
                String value = data.optString(key);
                apiUrl.append(key);
                apiUrl.append("=");
                apiUrl.append(value);
            }
        }

        URL urlConn = new URL(apiUrl.toString());
        httpClient = (HttpsURLConnection) urlConn.openConnection();
    } catch (IOException e) {
        throw new ECHOException(e);
    }

    final String appId = ECHO.appId;
    final String appKey = ECHO.appKey;
    final String accessToken = ECHO.accessToken;

    if (appId == null || appKey == null)
        throw new IllegalStateException("The SDK is not initialized.Please call `ECHO.initialize()`.");

    InputStream responseInputStream = null;

    try {
        httpClient.setRequestMethod(httpMethod);
        httpClient.addRequestProperty("X-ECHO-APP-ID", appId);
        httpClient.addRequestProperty("X-ECHO-APP-KEY", appKey);

        // Set access token
        if (accessToken != null && !accessToken.isEmpty())
            httpClient.addRequestProperty("X-ECHO-ACCESS-TOKEN", accessToken);

        // Build content
        if (!httpMethod.equals("GET") && data != null) {

            httpClient.setDoOutput(true);
            httpClient.setChunkedStreamingMode(0); // use default chunk size

            if (multipart == false) { // application/json

                httpClient.addRequestProperty("CONTENT-TYPE", "application/json");
                BufferedWriter wrBuffer = new BufferedWriter(
                        new OutputStreamWriter(httpClient.getOutputStream()));
                wrBuffer.write(data.toString());
                wrBuffer.close();

            } else { // multipart/form-data

                final String boundary = "*****" + UUID.randomUUID().toString() + "*****";
                final String twoHyphens = "--";
                final String lineEnd = "\r\n";
                final int maxBufferSize = 1024 * 1024 * 3;

                httpClient.setRequestMethod("POST");
                httpClient.addRequestProperty("CONTENT-TYPE", "multipart/form-data; boundary=" + boundary);

                final DataOutputStream outputStream = new DataOutputStream(httpClient.getOutputStream());

                try {

                    JSONObject postData = new JSONObject();
                    postData.putOpt("method", httpMethod);
                    postData.putOpt("data", data);

                    new Object() {

                        public void post(JSONObject data, List<String> currentKeys)
                                throws JSONException, IOException {

                            Iterator<?> keys = data.keys();
                            while (keys.hasNext()) {
                                String key = (String) keys.next();
                                List<String> newKeys = new ArrayList<String>(currentKeys);
                                newKeys.add(key);

                                Object val = data.get(key);

                                // convert JSONArray into JSONObject
                                if (val instanceof JSONArray) {
                                    JSONArray array = (JSONArray) val;
                                    JSONObject val2 = new JSONObject();

                                    for (Integer i = 0; i < array.length(); i++) {
                                        val2.putOpt(i.toString(), array.get(i));
                                    }

                                    val = val2;
                                }

                                // build form-data name
                                String name = "";
                                for (int i = 0; i < newKeys.size(); i++) {
                                    String key2 = newKeys.get(i);
                                    name += (i == 0) ? key2 : "[" + key2 + "]";
                                }

                                if (val instanceof ECHOFile) {

                                    ECHOFile file = (ECHOFile) val;
                                    if (file.getLocalBytes() == null)
                                        continue;

                                    InputStream fileInputStream = new ByteArrayInputStream(
                                            file.getLocalBytes());

                                    if (fileInputStream != null) {

                                        String mimeType = URLConnection
                                                .guessContentTypeFromName(file.getFileName());

                                        // write header
                                        outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                                        outputStream.writeBytes("Content-Disposition: form-data; name=\"" + name
                                                + "\"; filename=\"" + file.getFileName() + "\"" + lineEnd);
                                        outputStream.writeBytes("Content-Type: " + mimeType + lineEnd);
                                        outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
                                        outputStream.writeBytes(lineEnd);

                                        // write content
                                        int bytesAvailable, bufferSize, bytesRead;
                                        do {
                                            bytesAvailable = fileInputStream.available();
                                            bufferSize = Math.min(bytesAvailable, maxBufferSize);
                                            byte[] buffer = new byte[bufferSize];
                                            bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                                            if (bytesRead <= 0)
                                                break;
                                            outputStream.write(buffer, 0, bufferSize);
                                        } while (true);

                                        fileInputStream.close();
                                        outputStream.writeBytes(lineEnd);
                                    }

                                } else if (val instanceof JSONObject) {

                                    this.post((JSONObject) val, newKeys);

                                } else {

                                    String data2 = null;
                                    try { // in case of boolean
                                        boolean bool = data.getBoolean(key);
                                        data2 = bool ? "true" : "";
                                    } catch (JSONException e) { // if the value is not a Boolean or the String "true" or "false".
                                        data2 = val.toString().trim();
                                    }

                                    // write header
                                    outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                                    outputStream.writeBytes(
                                            "Content-Disposition: form-data; name=\"" + name + "\"" + lineEnd);
                                    outputStream
                                            .writeBytes("Content-Type: text/plain; charset=UTF-8" + lineEnd);
                                    outputStream.writeBytes("Content-Length: " + data2.length() + lineEnd);
                                    outputStream.writeBytes(lineEnd);

                                    // write content
                                    byte[] bytes = data2.getBytes();
                                    for (int i = 0; i < bytes.length; i++) {
                                        outputStream.writeByte(bytes[i]);
                                    }

                                    outputStream.writeBytes(lineEnd);
                                }

                            }
                        }
                    }.post(postData, new ArrayList<String>());

                } catch (JSONException e) {

                    throw new ECHOException(e);

                } finally {

                    outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                    outputStream.flush();
                    outputStream.close();

                }
            }

        } else {

            httpClient.addRequestProperty("CONTENT-TYPE", "application/json");

        }

        if (httpClient.getResponseCode() != -1 /*== HttpURLConnection.HTTP_OK*/) {
            responseInputStream = httpClient.getInputStream();
        }

    } catch (IOException e) {

        // get http response code
        int errorCode = -1;

        try {
            errorCode = httpClient.getResponseCode();
        } catch (IOException e1) {
            throw new ECHOException(e1);
        }

        // get error contents
        JSONObject responseObj;
        try {
            String jsonStr = ECHOQuery.getResponseString(httpClient.getErrorStream());
            responseObj = new JSONObject(jsonStr);
        } catch (JSONException e1) {
            if (errorCode == 404) {
                throw new ECHOException(ECHOException.RESOURCE_NOT_FOUND, "Resource not found.");
            }

            throw new ECHOException(ECHOException.INVALID_JSON_FORMAT, "Invalid JSON format.");
        }

        //
        if (responseObj != null) {
            int code = responseObj.optInt("error_code");
            String message = responseObj.optString("error_message");

            if (code != 0 || !message.equals("")) {
                JSONObject details = responseObj.optJSONObject("error_details");
                if (details == null) {
                    throw new ECHOException(code, message);
                } else {
                    throw new ECHOException(code, message, details);
                }
            }
        }

        throw new ECHOException(e);

    }

    return responseInputStream;
}

From source file:com.example.android.networkconnect.MainActivity.java

private String httpstestconnect(String urlString) throws IOException {
    CookieManager msCookieManager = new CookieManager();

    URL url = new URL(urlString);

    if (url.getProtocol().toLowerCase().equals("https")) {
        trustAllHosts();//from   ww w . j  a v  a2  s  .  c om

        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

        try {

            String headerName = null;

            for (int i = 1; (headerName = conn.getHeaderFieldKey(i)) != null; i++) {
                //data=data+"Header Nme : " + headerName;
                //data=data+conn.getHeaderField(i);
                // Log.i (TAG,headerName);
                Log.i(TAG, headerName + ": " + conn.getHeaderField(i));
            }

            //  Map<String, List<String>> headerFields = conn.getHeaderFields();
            //List<String> cookiesHeader = headerFields.get("Set-Cookie");

            //if(cookiesHeader != null)
            //{
            //  for (String cookie : cookiesHeader)
            // {
            //   msCookieManager.getCookieStore().add(null,HttpCookie.parse(cookie).get(0));

            //}
            //}

        } catch (Exception e) {
            Log.i(TAG, "Erreur Cookie" + e);
        }

        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);

        conn.setChunkedStreamingMode(0);

        conn.setRequestProperty("User-Agent", "e-venement-app/");

        //if(msCookieManager.getCookieStore().getCookies().size() > 0)
        //{
        //        conn.setRequestProperty("Cookie",
        //            TextUtils.join(",", msCookieManager.getCookieStore().getCookies()));
        //}

        // conn= (HttpsURLConnection) url.wait(); ;
        //(HttpsURLConnection) url.openConnection();

        final String password = "android2015@";

        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
        writer.getEncoding();
        writer.write("&signin[username]=antoine");
        writer.write("&signin[password]=android2015@");
        //writer.write("&signin[_csrf_token]="+CSRFTOKEN);
        writer.flush();
        //Log.i(TAG,"Writer: "+writer.toString());

        //   conn.connect();

        String data = null;

        //
        if (conn.getInputStream() != null) {
            Log.i(TAG, readIt(conn.getInputStream(), 2500));
            data = readIt(conn.getInputStream(), 7500);
        }

        //  return conn.getResponseCode();
        return data;
        //return readIt(inputStream,1028);
    }

    else {
        return url.getProtocol();
    }

}

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;
        }//from  w  w w . ja  va  2s  . c  o  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: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/*www.  j  av  a  2 s  .co  m*/
        lastTimestamp = lastToSendRecord.mBoxTimestamp;

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

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

    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);/*from  w ww  . ja v a  2  s .co 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");
        }
    }
}