Example usage for javax.net.ssl HttpsURLConnection getInputStream

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

Introduction

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

Prototype

public InputStream getInputStream() throws IOException 

Source Link

Document

Returns an input stream that reads from this open connection.

Usage

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

private String https_test(String urlString) throws IOException {

    String token = "";
    URL url = new URL(urlString);

    Log.i(TAG, "Protocol: " + url.getProtocol().toString());

    // if (url.getProtocol().toLowerCase().equals("https")) {
    trustAllHosts();//from  www .j  ava  2  s  .co m

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

    conn.setReadTimeout(20000 /* milliseconds */);
    conn.setConnectTimeout(25000 /* milliseconds */);
    // conn.setRequestMethod("GET");
    conn.setDoInput(true);
    conn.setDoOutput(true);

    conn.setChunkedStreamingMode(0);

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

    // OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
    //writer.getEncoding();
    //writer.write("&signin[username]=antoine");
    //writer.write("&signin[password]=android2015@");
    //writer.write("?control[id]=");
    //writer.write("&control[ticket_id]=2222");
    //writer.write("&control[checkpoint_id]=1");
    //  writer.write("&control[comment]=");

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); //On cre la liste qui contiendra tous nos paramtres

    //Et on y rajoute nos paramtres
    nameValuePairs.add(new BasicNameValuePair("signin[username]", "antoine"));
    nameValuePairs.add(new BasicNameValuePair("signin[password]", "android2015@"));
    //nameValuePairs.add(new BasicNameValuePair("control[id]", ""));
    //nameValuePairs.add(new BasicNameValuePair("control[ticket_id]", "2222"));
    //nameValuePairs.add(new BasicNameValuePair("control[checkpoint_id]", "1"));
    //nameValuePairs.add(new BasicNameValuePair("control[comment]", ""));

    OutputStream os = conn.getOutputStream();
    BufferedWriter writer2 = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
    writer2.write(getQuery(nameValuePairs));
    writer2.flush();
    //writer2.close();
    //os.close();

    // conn.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    //writer.write("&signin[_csrf_token]="+CSRFTOKEN);
    //writer.flush();

    conn.connect();

    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));

    }

    int responseCode = conn.getResponseCode();

    if (responseCode == conn.HTTP_OK) {
        final String COOKIES_HEADER = "Set-Cookie";
        cookie = conn.getHeaderField(COOKIES_HEADER);
    }

    if (conn.getInputStream() != null) {

        // token =getStringFromInputStream(conn.getInputStream());
        Log.i(TAG, readIt(conn.getInputStream(), 15000));
        token = readIt(conn.getInputStream(), 15000);
        Log.i(TAG, getStringFromInputStream(conn.getInputStream()));
        //data=readIt(conn.getInputStream(),7500);
        //Log.i(TAG,token);
        //token=readIt(conn.getInputStream(),7500);
    }
    //conn.connect();
    // List<String> cookiesList = conn.getHeaderFields().get("Set-Cookie");

    // }
    //conn.disconnect();
    return token;
}

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

/**
 * @param path// www .j  a  v  a 2s.com
 * @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.AdapterRule.java

@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);

    // Get rule//from w  w  w .  j a  v a  2  s  .  c o  m
    final Rule rule = listFiltered.get(position);

    // Handle expanding/collapsing
    holder.llApplication.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            rule.expanded = !rule.expanded;
            notifyItemChanged(position);
        }
    });

    // Show if non default rules
    holder.itemView.setBackgroundColor(rule.changed ? colorChanged : Color.TRANSPARENT);

    // Show expand/collapse indicator
    holder.ivExpander.setImageLevel(rule.expanded ? 1 : 0);

    // Show application icon
    if (rule.info.applicationInfo == null || rule.info.applicationInfo.icon == 0)
        Picasso.with(context).load(android.R.drawable.sym_def_app_icon).into(holder.ivIcon);
    else {
        Uri uri = Uri
                .parse("android.resource://" + rule.info.packageName + "/" + rule.info.applicationInfo.icon);
        Picasso.with(context).load(uri).resize(iconSize, iconSize).into(holder.ivIcon);
    }

    // Show application label
    holder.tvName.setText(rule.name);

    // Show application state
    int color = rule.system ? colorOff : colorText;
    if (!rule.internet || !rule.enabled)
        color = Color.argb(128, Color.red(color), Color.green(color), Color.blue(color));
    holder.tvName.setTextColor(color);

    // Show rule count
    new AsyncTask<Object, Object, Long>() {
        @Override
        protected void onPreExecute() {
            holder.tvHosts.setVisibility(View.GONE);
        }

        @Override
        protected Long doInBackground(Object... objects) {
            return DatabaseHelper.getInstance(context).getRuleCount(rule.info.applicationInfo.uid);
        }

        @Override
        protected void onPostExecute(Long rules) {
            if (rules > 0) {
                holder.tvHosts.setVisibility(View.VISIBLE);
                holder.tvHosts.setText(Long.toString(rules));
            }
        }
    }.execute();

    // Wi-Fi settings
    holder.cbWifi.setEnabled(rule.apply);
    holder.cbWifi.setAlpha(wifiActive ? 1 : 0.5f);
    holder.cbWifi.setOnCheckedChangeListener(null);
    holder.cbWifi.setChecked(rule.wifi_blocked);
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        Drawable wrap = DrawableCompat.wrap(CompoundButtonCompat.getButtonDrawable(holder.cbWifi));
        DrawableCompat.setTint(wrap, rule.apply ? (rule.wifi_blocked ? colorOff : colorOn) : colorGrayed);
    }
    holder.cbWifi.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
            rule.wifi_blocked = isChecked;
            updateRule(rule, true, listAll);
        }
    });

    holder.ivScreenWifi.setEnabled(rule.apply);
    holder.ivScreenWifi.setAlpha(wifiActive ? 1 : 0.5f);
    holder.ivScreenWifi.setVisibility(rule.screen_wifi && rule.wifi_blocked ? View.VISIBLE : View.INVISIBLE);
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        Drawable wrap = DrawableCompat.wrap(holder.ivScreenWifi.getDrawable());
        DrawableCompat.setTint(wrap, rule.apply ? colorOn : colorGrayed);
    }

    // Mobile settings
    holder.cbOther.setEnabled(rule.apply);
    holder.cbOther.setAlpha(otherActive ? 1 : 0.5f);
    holder.cbOther.setOnCheckedChangeListener(null);
    holder.cbOther.setChecked(rule.other_blocked);
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        Drawable wrap = DrawableCompat.wrap(CompoundButtonCompat.getButtonDrawable(holder.cbOther));
        DrawableCompat.setTint(wrap, rule.apply ? (rule.other_blocked ? colorOff : colorOn) : colorGrayed);
    }
    holder.cbOther.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
            rule.other_blocked = isChecked;
            updateRule(rule, true, listAll);
        }
    });

    holder.ivScreenOther.setEnabled(rule.apply);
    holder.ivScreenOther.setAlpha(otherActive ? 1 : 0.5f);
    holder.ivScreenOther.setVisibility(rule.screen_other && rule.other_blocked ? View.VISIBLE : View.INVISIBLE);
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        Drawable wrap = DrawableCompat.wrap(holder.ivScreenOther.getDrawable());
        DrawableCompat.setTint(wrap, rule.apply ? colorOn : colorGrayed);
    }

    holder.tvRoaming.setTextColor(rule.apply ? colorOff : colorGrayed);
    holder.tvRoaming.setAlpha(otherActive ? 1 : 0.5f);
    holder.tvRoaming.setVisibility(
            rule.roaming && (!rule.other_blocked || rule.screen_other) ? View.VISIBLE : View.INVISIBLE);

    // Expanded configuration section
    holder.llConfiguration.setVisibility(rule.expanded ? View.VISIBLE : View.GONE);

    // Show application details
    holder.tvUid
            .setText(rule.info.applicationInfo == null ? "?" : Integer.toString(rule.info.applicationInfo.uid));
    holder.tvPackage.setText(rule.info.packageName);
    holder.tvVersion.setText(rule.info.versionName + '/' + rule.info.versionCode);
    holder.tvDescription.setVisibility(rule.description == null ? View.GONE : View.VISIBLE);
    holder.tvDescription.setText(rule.description);

    // Show application state
    holder.tvInternet.setVisibility(rule.internet ? View.GONE : View.VISIBLE);
    holder.tvDisabled.setVisibility(rule.enabled ? View.GONE : View.VISIBLE);

    // Show traffic statistics
    holder.tvStatistics.setText(context.getString(R.string.msg_mbday, rule.upspeed, rule.downspeed));

    // Apply
    holder.cbApply.setEnabled(rule.pkg);
    holder.cbApply.setOnCheckedChangeListener(null);
    holder.cbApply.setChecked(rule.apply);
    holder.cbApply.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
            rule.apply = isChecked;
            updateRule(rule, true, listAll);
        }
    });

    // Show related
    holder.btnRelated.setVisibility(rule.relateduids ? View.VISIBLE : View.GONE);
    holder.btnRelated.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent main = new Intent(context, ActivityMain.class);
            main.putExtra(ActivityMain.EXTRA_SEARCH, Integer.toString(rule.info.applicationInfo.uid));
            context.startActivity(main);
        }
    });

    // Fetch settings
    holder.ibFetch.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            new AsyncTask<Object, Object, Object>() {
                @Override
                protected void onPreExecute() {
                    holder.ibFetch.setEnabled(false);
                }

                @Override
                protected Object doInBackground(Object... args) {
                    HttpsURLConnection urlConnection = null;
                    try {
                        JSONObject json = new JSONObject();

                        json.put("type", "fetch");
                        json.put("country", Locale.getDefault().getCountry());
                        json.put("netguard", Util.getSelfVersionCode(context));
                        json.put("fingerprint", Util.getFingerprint(context));

                        JSONObject pkg = new JSONObject();
                        pkg.put("name", rule.info.packageName);
                        pkg.put("version_code", rule.info.versionCode);
                        pkg.put("version_name", rule.info.versionName);

                        JSONArray pkgs = new JSONArray();
                        pkgs.put(pkg);
                        json.put("package", pkgs);

                        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);

                        Log.i(TAG, "Request=" + json.toString());
                        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());
                        String response = Util.readString(isr).toString();
                        Log.i(TAG, "Response=" + response);
                        JSONObject jfetched = new JSONObject(response);
                        JSONArray jpkgs = jfetched.getJSONArray("package");
                        for (int i = 0; i < jpkgs.length(); i++) {
                            JSONObject jpkg = jpkgs.getJSONObject(i);
                            String name = jpkg.getString("name");
                            int wifi = jpkg.getInt("wifi");
                            int wifi_screen = jpkg.getInt("wifi_screen");
                            int other = jpkg.getInt("other");
                            int other_screen = jpkg.getInt("other_screen");
                            int roaming = jpkg.getInt("roaming");
                            int devices = jpkg.getInt("devices");

                            double conf_wifi;
                            boolean block_wifi;
                            if (rule.wifi_default) {
                                conf_wifi = confidence(devices - wifi, devices);
                                block_wifi = !(devices - wifi > wifi && conf_wifi > cConfidence);
                            } else {
                                conf_wifi = confidence(wifi, devices);
                                block_wifi = (wifi > devices - wifi && conf_wifi > cConfidence);
                            }

                            boolean allow_wifi_screen = rule.screen_wifi_default;
                            if (block_wifi)
                                allow_wifi_screen = (wifi_screen > wifi / 2);

                            double conf_other;
                            boolean block_other;
                            if (rule.other_default) {
                                conf_other = confidence(devices - other, devices);
                                block_other = !(devices - other > other && conf_other > cConfidence);
                            } else {
                                conf_other = confidence(other, devices);
                                block_other = (other > devices - other && conf_other > cConfidence);
                            }

                            boolean allow_other_screen = rule.screen_other_default;
                            if (block_other)
                                allow_other_screen = (other_screen > other / 2);

                            boolean block_roaming = rule.roaming_default;
                            if (!block_other || allow_other_screen)
                                block_roaming = (roaming > (devices - other) / 2);

                            Log.i(TAG,
                                    "pkg=" + name + " wifi=" + wifi + "/" + wifi_screen + "=" + block_wifi + "/"
                                            + allow_wifi_screen + " " + Math.round(100 * conf_wifi) + "%"
                                            + " other=" + other + "/" + other_screen + "/" + roaming + "="
                                            + block_other + "/" + allow_other_screen + "/" + block_roaming + " "
                                            + Math.round(100 * conf_other) + "%" + " devices=" + devices);

                            rule.wifi_blocked = block_wifi;
                            rule.screen_wifi = allow_wifi_screen;
                            rule.other_blocked = block_other;
                            rule.screen_other = allow_other_screen;
                            rule.roaming = block_roaming;
                        }

                    } catch (Throwable ex) {
                        Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                        return ex;

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

                    return null;
                }

                @Override
                protected void onPostExecute(Object result) {
                    holder.ibFetch.setEnabled(true);
                    updateRule(rule, true, listAll);
                }

            }.execute(rule);
        }
    });

    // Launch application settings
    final Intent settings = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
    settings.setData(Uri.parse("package:" + rule.info.packageName));
    holder.ibSettings.setVisibility(
            settings.resolveActivity(context.getPackageManager()) == null ? View.GONE : View.VISIBLE);
    holder.ibSettings.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            context.startActivity(settings);
        }
    });

    // Launch application
    holder.ibLaunch.setVisibility(rule.intent == null ? View.GONE : View.VISIBLE);
    holder.ibLaunch.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            context.startActivity(rule.intent);
        }
    });

    // Show Wi-Fi screen on condition
    holder.cbScreenWifi.setEnabled(rule.wifi_blocked && rule.apply);
    holder.cbScreenWifi.setOnCheckedChangeListener(null);
    holder.cbScreenWifi.setChecked(rule.screen_wifi);

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        Drawable wrap = DrawableCompat.wrap(holder.ivWifiLegend.getDrawable());
        DrawableCompat.setTint(wrap, colorOn);
    }

    holder.cbScreenWifi.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            rule.screen_wifi = isChecked;
            updateRule(rule, true, listAll);
        }
    });

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        Drawable wrap = DrawableCompat.wrap(holder.ivOtherLegend.getDrawable());
        DrawableCompat.setTint(wrap, colorOn);
    }

    // Show mobile screen on condition
    holder.cbScreenOther.setEnabled(rule.other_blocked && rule.apply);
    holder.cbScreenOther.setOnCheckedChangeListener(null);
    holder.cbScreenOther.setChecked(rule.screen_other);
    holder.cbScreenOther.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            rule.screen_other = isChecked;
            updateRule(rule, true, listAll);
        }
    });

    // Show roaming condition
    holder.cbRoaming.setEnabled((!rule.other_blocked || rule.screen_other) && rule.apply);
    holder.cbRoaming.setOnCheckedChangeListener(null);
    holder.cbRoaming.setChecked(rule.roaming);
    holder.cbRoaming.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        @TargetApi(Build.VERSION_CODES.M)
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            rule.roaming = isChecked;
            updateRule(rule, true, listAll);

            // Request permissions
            if (isChecked && !Util.hasPhoneStatePermission(context))
                context.requestPermissions(new String[] { Manifest.permission.READ_PHONE_STATE },
                        ActivityMain.REQUEST_ROAMING);
        }
    });

    // Reset rule
    holder.btnClear.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Util.areYouSure(view.getContext(), R.string.msg_clear_rules, new Util.DoubtListener() {
                @Override
                public void onSure() {
                    holder.cbApply.setChecked(true);
                    holder.cbWifi.setChecked(rule.wifi_default);
                    holder.cbOther.setChecked(rule.other_default);
                    holder.cbScreenWifi.setChecked(rule.screen_wifi_default);
                    holder.cbScreenOther.setChecked(rule.screen_other_default);
                    holder.cbRoaming.setChecked(rule.roaming_default);
                }
            });
        }
    });

    // Show logging is disabled
    boolean log_app = prefs.getBoolean("log_app", false);
    holder.tvNoLog.setVisibility(log_app ? View.GONE : View.VISIBLE);
    holder.tvNoLog.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            context.startActivity(new Intent(context, ActivitySettings.class));
        }
    });

    // Show filtering is disabled
    boolean filter = prefs.getBoolean("filter", false);
    holder.tvNoFilter.setVisibility(filter ? View.GONE : View.VISIBLE);
    holder.tvNoFilter.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            context.startActivity(new Intent(context, ActivitySettings.class));
        }
    });

    // Show access rules
    if (rule.expanded) {
        // Access the database when expanded only
        final AdapterAccess badapter = new AdapterAccess(context,
                DatabaseHelper.getInstance(context).getAccess(rule.info.applicationInfo.uid));
        holder.lvAccess.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int bposition, long bid) {
                PackageManager pm = context.getPackageManager();
                Cursor cursor = (Cursor) badapter.getItem(bposition);
                final long id = cursor.getLong(cursor.getColumnIndex("ID"));
                final int version = cursor.getInt(cursor.getColumnIndex("version"));
                final int protocol = cursor.getInt(cursor.getColumnIndex("protocol"));
                final String daddr = cursor.getString(cursor.getColumnIndex("daddr"));
                final int dport = cursor.getInt(cursor.getColumnIndex("dport"));
                long time = cursor.getLong(cursor.getColumnIndex("time"));
                int block = cursor.getInt(cursor.getColumnIndex("block"));

                PopupMenu popup = new PopupMenu(context, context.findViewById(R.id.vwPopupAnchor));
                popup.inflate(R.menu.access);

                popup.getMenu().findItem(R.id.menu_host).setTitle(Util.getProtocolName(protocol, version, false)
                        + " " + daddr + (dport > 0 ? "/" + dport : ""));

                // Whois
                final Intent lookupIP = new Intent(Intent.ACTION_VIEW,
                        Uri.parse("http://www.tcpiputils.com/whois-lookup/" + daddr));
                if (pm.resolveActivity(lookupIP, 0) == null)
                    popup.getMenu().removeItem(R.id.menu_whois);
                else
                    popup.getMenu().findItem(R.id.menu_whois)
                            .setTitle(context.getString(R.string.title_log_whois, daddr));

                // Lookup port
                final Intent lookupPort = new Intent(Intent.ACTION_VIEW,
                        Uri.parse("http://www.speedguide.net/port.php?port=" + dport));
                if (dport <= 0 || pm.resolveActivity(lookupPort, 0) == null)
                    popup.getMenu().removeItem(R.id.menu_port);
                else
                    popup.getMenu().findItem(R.id.menu_port)
                            .setTitle(context.getString(R.string.title_log_port, dport));

                popup.getMenu().findItem(R.id.menu_time)
                        .setTitle(SimpleDateFormat.getDateTimeInstance().format(time));

                popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem menuItem) {
                        switch (menuItem.getItemId()) {
                        case R.id.menu_whois:
                            context.startActivity(lookupIP);
                            return true;

                        case R.id.menu_port:
                            context.startActivity(lookupPort);
                            return true;

                        case R.id.menu_allow:
                            if (IAB.isPurchased(ActivityPro.SKU_FILTER, context)) {
                                DatabaseHelper.getInstance(context).setAccess(id, 0);
                                ServiceSinkhole.reload("allow host", context);
                                if (rule.submit)
                                    ServiceJob.submit(rule, version, protocol, daddr, dport, 0, context);
                            } else
                                context.startActivity(new Intent(context, ActivityPro.class));
                            return true;

                        case R.id.menu_block:
                            if (IAB.isPurchased(ActivityPro.SKU_FILTER, context)) {
                                DatabaseHelper.getInstance(context).setAccess(id, 1);
                                ServiceSinkhole.reload("block host", context);
                                if (rule.submit)
                                    ServiceJob.submit(rule, version, protocol, daddr, dport, 1, context);
                            } else
                                context.startActivity(new Intent(context, ActivityPro.class));
                            return true;

                        case R.id.menu_reset:
                            DatabaseHelper.getInstance(context).setAccess(id, -1);
                            ServiceSinkhole.reload("reset host", context);
                            if (rule.submit)
                                ServiceJob.submit(rule, version, protocol, daddr, dport, -1, context);
                            return true;
                        }
                        return false;
                    }
                });

                if (block == 0)
                    popup.getMenu().removeItem(R.id.menu_allow);
                else if (block == 1)
                    popup.getMenu().removeItem(R.id.menu_block);

                popup.show();
            }
        });

        holder.lvAccess.setAdapter(badapter);
    } else {
        holder.lvAccess.setAdapter(null);
        holder.lvAccess.setOnItemClickListener(null);
    }

    // Clear access log
    holder.btnClearAccess.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Util.areYouSure(view.getContext(), R.string.msg_reset_access, new Util.DoubtListener() {
                @Override
                public void onSure() {
                    DatabaseHelper.getInstance(context).clearAccess(rule.info.applicationInfo.uid, true);
                    if (rv != null)
                        rv.scrollToPosition(position);
                }
            });
        }
    });

    // Notify on access
    holder.cbNotify.setEnabled(prefs.getBoolean("notify_access", false) && rule.apply);
    holder.cbNotify.setOnCheckedChangeListener(null);
    holder.cbNotify.setChecked(rule.notify);
    holder.cbNotify.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
            rule.notify = isChecked;
            updateRule(rule, true, listAll);
        }
    });

    // Usage data sharing
    holder.cbSubmit
            .setVisibility(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? View.VISIBLE : View.GONE);
    holder.cbSubmit.setOnCheckedChangeListener(null);
    holder.cbSubmit.setChecked(rule.submit);
    holder.cbSubmit.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
            rule.submit = isChecked;
            updateRule(rule, true, listAll);
        }
    });
}

From source file:com.kimbrelk.da.oauth2.OAuth2.java

protected final JSONObject requestJSON(Verb verb, String url, String postData) {
    try {//from w w  w . ja v a 2  s . c  om
        mLog.append("SEND:\n");
        HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();
        connection.setRequestProperty("User-Agent", mUserAgent);
        connection.setRequestProperty("dA-minor-version", "" + VERSION.getMinor());
        connection.setReadTimeout(30000);
        connection.setConnectTimeout(30000);
        mLog.append(verb.toString() + " ");
        mLog.append(url);
        mLog.append("\n");
        connection.setRequestMethod(verb.toString());
        if (verb == Verb.POST) {
            mLog.append(postData);
            mLog.append("\n");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            //connection.setRequestProperty("Authorization", "Basic " + base64(CLIENT_ID + ":" + loadLast()));
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("Content-Length", "" + postData.length());
            connection.connect();
            OutputStream os = connection.getOutputStream();
            os.write(postData.getBytes());
            os.flush();
        } else if (verb == Verb.GET) {
            connection.setDoOutput(false);
            connection.setDoInput(true);
            connection.connect();
        }
        mLog.append("\nRECV:\n");

        try {
            InputStream is = connection.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader in = new BufferedReader(isr);
            String line = "";
            String page = "";
            while ((line = in.readLine()) != null) {
                page += line;
            }
            mLog.append(page);
            mLog.append("\n\n");
            return new JSONObject(page);
        } catch (Exception e) {
            try {
                JSONObject json = new JSONObject();
                json.put("status", "error");
                try {
                    InputStream is = connection.getErrorStream();
                    InputStreamReader isr = new InputStreamReader(is);
                    BufferedReader in = new BufferedReader(isr);
                    String line = "";
                    String page = "";
                    while ((line = in.readLine()) != null) {
                        page += line;
                    }
                    mLog.append(page);
                    mLog.append("\n\n");
                    return new JSONObject(page);
                } catch (Exception err) {

                }
                try {
                    if (connection.getResponseCode() == 403 || connection.getResponseCode() == 429) {
                        json.put("error_description", RespError.RATE_LIMIT.getDescription());
                        json.put("error", RespError.RATE_LIMIT.getType());
                        return json;
                    }
                } catch (IOException er) {

                }
                String str = "";
                str += "URL: " + url.split("[?]+")[0] + "\n";
                //str += "POST Data: " + postData + "\n";
                str += "\n";
                for (int a = 0; a < connection.getHeaderFields().size() - 1; a++) {
                    str += connection.getHeaderFieldKey(a) + ": " + connection.getHeaderField(a) + "\n";
                }
                json.put("error_description", str);
                json.put("error", RespError.REQUEST_FAILED.getType());
                return json;
            } catch (Exception er) {
                throw e;
            }
        } finally {
            connection.disconnect();
        }
    } catch (Exception e) {
        try {
            e.printStackTrace();
            JSONObject json = new JSONObject();
            json.put("status", "error");
            json.put("error", RespError.REQUEST_FAILED.getType());
            json.put("error_description", RespError.REQUEST_FAILED.getDescription() + " : " + e);
            return json;
        } catch (JSONException er) {
            er.printStackTrace();
            return null;
        }
    }
}

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

@Override
public void run() {
    HttpsURLConnection connection = null;
    SecretKeySpec keySpec = new SecretKeySpec(this.session.appConfiguration.apiKey.getBytes(), "HmacSHA256");
    String requestBody;// ww  w  . j  av  a2s . c om

    String hostnameForEndpoint = this.hostname;
    if (hostnameForEndpoint == null) {
        hostnameForEndpoint = this.session.remoteConfiguration.getHostnameForEndpoint(this.endpoint);
    }

    try {
        ArrayList<String> payloadKeys = new ArrayList<>(this.payload.keySet());
        Collections.sort(payloadKeys);

        StringBuilder builder = new StringBuilder();
        for (String key : payloadKeys) {
            Object value = this.payload.get(key);
            if (value != null) {
                String valueString;
                if (value instanceof Map) {
                    valueString = new JSONObject((Map) value).toString();
                } else if (value instanceof Array) {
                    valueString = new JSONArray(Collections.singletonList(value)).toString();
                } else if (value instanceof Collection) {
                    valueString = new JSONArray((Collection) value).toString();
                } else {
                    valueString = value.toString();
                }
                builder.append(key).append("=").append(valueString).append("&");
            } else {
                Log.e(LOG_TAG, "Value for key: " + key + " is null.");
            }
        }
        builder.deleteCharAt(builder.length() - 1);

        String stringToSign = "POST\n" + hostnameForEndpoint + "\n" + this.endpoint + "\n" + builder.toString();
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(keySpec);
        byte[] result = mac.doFinal(stringToSign.getBytes());

        builder = new StringBuilder();
        for (String key : payloadKeys) {
            Object value = this.payload.get(key);
            String valueString;
            if (value instanceof Map) {
                valueString = new JSONObject((Map) value).toString();
            } else if (value instanceof Array) {
                valueString = new JSONArray(Collections.singletonList(value)).toString();
            } else if (value instanceof Collection) {
                valueString = new JSONArray((Collection) value).toString();
            } else {
                valueString = value.toString();
            }
            builder.append(key).append("=").append(URLEncoder.encode(valueString, "UTF-8")).append("&");
        }
        builder.append("sig=")
                .append(URLEncoder.encode(Base64.encodeToString(result, Base64.NO_WRAP), "UTF-8"));

        requestBody = builder.toString();
    } catch (Exception e) {
        Log.e(LOG_TAG, "Error signing payload: " + Log.getStackTraceString(e));
        return;
    }

    try {
        if (Teak.isDebug) {
            Log.d(LOG_TAG, "Submitting request to '" + this.endpoint + "': "
                    + new JSONObject(this.payload).toString(2));
        }

        URL url = new URL("https://" + hostnameForEndpoint + this.endpoint);
        connection = (HttpsURLConnection) url.openConnection();

        connection.setRequestProperty("Accept-Charset", "UTF-8");
        connection.setUseCaches(false);
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("Content-Length", "" + Integer.toString(requestBody.getBytes().length));

        // Send request
        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(requestBody);
        wr.flush();
        wr.close();

        // Get Response
        InputStream is;
        if (connection.getResponseCode() < 400) {
            is = connection.getInputStream();
        } else {
            is = connection.getErrorStream();
        }
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        StringBuilder response = new StringBuilder();
        while ((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\r');
        }
        rd.close();

        if (Teak.isDebug) {
            String responseText = response.toString();
            try {
                responseText = new JSONObject(response.toString()).toString(2);
            } catch (Exception ignored) {
            }
            Log.d(LOG_TAG, "Reply from '" + this.endpoint + "': " + responseText);
        }

        // For extending classes
        done(connection.getResponseCode(), response.toString());
    } catch (Exception e) {
        Log.e(LOG_TAG, Log.getStackTraceString(e));
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:org.sakaiproject.turnitin.util.TurnitinAPIUtil.java

public static InputStream callTurnitinReturnInputStream(String apiURL, Map<String, Object> parameters,
        String secretKey, int timeout, Proxy proxy, boolean isMultipart)
        throws TransientSubmissionException, SubmissionException {
    InputStream togo = null;/*from ww  w  .  j  a v  a  2 s . c  o  m*/

    StringBuilder apiDebugSB = new StringBuilder();

    if (!parameters.containsKey("fid")) {
        throw new IllegalArgumentException("You must to include a fid in the parameters");
    }

    //if (!parameters.containsKey("gmttime")) {
    parameters.put("gmtime", getGMTime());
    //}

    /**
     * Some debug logging
     */
    if (log.isDebugEnabled()) {
        Set<Entry<String, Object>> ets = parameters.entrySet();
        Iterator<Entry<String, Object>> it = ets.iterator();
        while (it.hasNext()) {
            Entry<String, Object> entr = it.next();
            log.debug("Paramater entry: " + entr.getKey() + ": " + entr.getValue());
        }
    }

    List<String> sortedkeys = new ArrayList<String>();
    sortedkeys.addAll(parameters.keySet());

    String md5 = buildTurnitinMD5(parameters, secretKey, sortedkeys);

    HttpsURLConnection connection;
    String boundary = "";
    try {
        connection = fetchConnection(apiURL, timeout, proxy);

        if (isMultipart) {
            Random rand = new Random();
            //make up a boundary that should be unique
            boundary = Long.toString(rand.nextLong(), 26) + Long.toString(rand.nextLong(), 26)
                    + Long.toString(rand.nextLong(), 26);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        }

        log.debug("HTTPS Connection made to Turnitin");

        OutputStream outStream = connection.getOutputStream();

        if (isMultipart) {
            if (apiTraceLog.isDebugEnabled()) {
                apiDebugSB.append("Starting Multipart TII CALL:\n");
            }
            for (int i = 0; i < sortedkeys.size(); i++) {
                if (parameters.get(sortedkeys.get(i)) instanceof ContentResource) {
                    ContentResource resource = (ContentResource) parameters.get(sortedkeys.get(i));
                    outStream.write(
                            ("--" + boundary + "\r\nContent-Disposition: form-data; name=\"pdata\"; filename=\""
                                    + resource.getId() + "\"\r\n" + "Content-Type: " + resource.getContentType()
                                    + "\r\ncontent-transfer-encoding: binary" + "\r\n\r\n").getBytes());
                    //TODO this loads the doc into memory rather use the stream method
                    byte[] content = resource.getContent();
                    if (content == null) {
                        throw new SubmissionException("zero length submission!");
                    }
                    outStream.write(content);
                    outStream.write("\r\n".getBytes("UTF-8"));
                    if (apiTraceLog.isDebugEnabled()) {
                        apiDebugSB.append(sortedkeys.get(i));
                        apiDebugSB.append(" = ContentHostingResource: ");
                        apiDebugSB.append(resource.getId());
                        apiDebugSB.append("\n");
                    }
                } else {
                    if (apiTraceLog.isDebugEnabled()) {
                        apiDebugSB.append(sortedkeys.get(i));
                        apiDebugSB.append(" = ");
                        apiDebugSB.append(parameters.get(sortedkeys.get(i)).toString());
                        apiDebugSB.append("\n");
                    }
                    outStream.write(encodeParam(sortedkeys.get(i), parameters.get(sortedkeys.get(i)).toString(),
                            boundary).getBytes());
                }
            }
            outStream.write(encodeParam("md5", md5, boundary).getBytes());
            outStream.write(("--" + boundary + "--").getBytes());

            if (apiTraceLog.isDebugEnabled()) {
                apiDebugSB.append("md5 = ");
                apiDebugSB.append(md5);
                apiDebugSB.append("\n");
                apiTraceLog.debug(apiDebugSB.toString());
            }
        } else {
            writeBytesToOutputStream(outStream, sortedkeys.get(0), "=",
                    parameters.get(sortedkeys.get(0)).toString());
            if (apiTraceLog.isDebugEnabled()) {
                apiDebugSB.append("Starting TII CALL:\n");
                apiDebugSB.append(sortedkeys.get(0));
                apiDebugSB.append(" = ");
                apiDebugSB.append(parameters.get(sortedkeys.get(0)).toString());
                apiDebugSB.append("\n");
            }

            for (int i = 1; i < sortedkeys.size(); i++) {
                writeBytesToOutputStream(outStream, "&", sortedkeys.get(i), "=",
                        parameters.get(sortedkeys.get(i)).toString());
                if (apiTraceLog.isDebugEnabled()) {
                    apiDebugSB.append(sortedkeys.get(i));
                    apiDebugSB.append(" = ");
                    apiDebugSB.append(parameters.get(sortedkeys.get(i)).toString());
                    apiDebugSB.append("\n");
                }
            }

            writeBytesToOutputStream(outStream, "&md5=", md5);
            if (apiTraceLog.isDebugEnabled()) {
                apiDebugSB.append("md5 = ");
                apiDebugSB.append(md5);
                apiTraceLog.debug(apiDebugSB.toString());
            }
        }

        outStream.close();

        togo = connection.getInputStream();
    } catch (IOException t) {
        log.error("IOException making turnitin call.", t);
        throw new TransientSubmissionException("IOException making turnitin call.", t);
    } catch (ServerOverloadException t) {
        throw new TransientSubmissionException("Unable to submit the content data from ContentHosting", t);
    }

    return togo;

}

From source file:org.sakaiproject.contentreview.turnitin.util.TurnitinAPIUtil.java

public static InputStream callTurnitinReturnInputStream(String apiURL, Map<String, Object> parameters,
        String secretKey, int timeout, Proxy proxy, boolean isMultipart)
        throws TransientSubmissionException, SubmissionException {
    InputStream togo = null;/*from  ww w  . j  a v  a2  s .  co m*/

    StringBuilder apiDebugSB = new StringBuilder();

    if (!parameters.containsKey("fid")) {
        throw new IllegalArgumentException("You must to include a fid in the parameters");
    }

    //if (!parameters.containsKey("gmttime")) {
    parameters.put("gmtime", getGMTime());
    //}

    /**
     * Some debug logging
     */
    if (log.isDebugEnabled()) {
        Set<Entry<String, Object>> ets = parameters.entrySet();
        Iterator<Entry<String, Object>> it = ets.iterator();
        while (it.hasNext()) {
            Entry<String, Object> entr = it.next();
            log.debug("Paramater entry: " + entr.getKey() + ": " + entr.getValue());
        }
    }

    List<String> sortedkeys = new ArrayList<String>();
    sortedkeys.addAll(parameters.keySet());

    String md5 = buildTurnitinMD5(parameters, secretKey, sortedkeys);

    HttpsURLConnection connection;
    String boundary = "";
    try {
        connection = fetchConnection(apiURL, timeout, proxy);
        connection.setHostnameVerifier(new HostnameVerifier() {

            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });

        if (isMultipart) {
            Random rand = new Random();
            //make up a boundary that should be unique
            boundary = Long.toString(rand.nextLong(), 26) + Long.toString(rand.nextLong(), 26)
                    + Long.toString(rand.nextLong(), 26);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        }

        log.debug("HTTPS Connection made to Turnitin");

        OutputStream outStream = connection.getOutputStream();

        if (isMultipart) {
            if (apiTraceLog.isDebugEnabled()) {
                apiDebugSB.append("Starting Multipart TII CALL:\n");
            }
            for (int i = 0; i < sortedkeys.size(); i++) {
                if (parameters.get(sortedkeys.get(i)) instanceof ContentResource) {
                    ContentResource resource = (ContentResource) parameters.get(sortedkeys.get(i));
                    outStream.write(
                            ("--" + boundary + "\r\nContent-Disposition: form-data; name=\"pdata\"; filename=\""
                                    + resource.getId() + "\"\r\n" + "Content-Type: " + resource.getContentType()
                                    + "\r\ncontent-transfer-encoding: binary" + "\r\n\r\n").getBytes());
                    //TODO this loads the doc into memory rather use the stream method
                    byte[] content = resource.getContent();
                    if (content == null) {
                        throw new SubmissionException("zero length submission!");
                    }
                    outStream.write(content);
                    outStream.write("\r\n".getBytes("UTF-8"));
                    if (apiTraceLog.isDebugEnabled()) {
                        apiDebugSB.append(sortedkeys.get(i));
                        apiDebugSB.append(" = ContentHostingResource: ");
                        apiDebugSB.append(resource.getId());
                        apiDebugSB.append("\n");
                    }
                } else {
                    if (apiTraceLog.isDebugEnabled()) {
                        apiDebugSB.append(sortedkeys.get(i));
                        apiDebugSB.append(" = ");
                        apiDebugSB.append(parameters.get(sortedkeys.get(i)).toString());
                        apiDebugSB.append("\n");
                    }
                    outStream.write(encodeParam(sortedkeys.get(i), parameters.get(sortedkeys.get(i)).toString(),
                            boundary).getBytes());
                }
            }
            outStream.write(encodeParam("md5", md5, boundary).getBytes());
            outStream.write(("--" + boundary + "--").getBytes());

            if (apiTraceLog.isDebugEnabled()) {
                apiDebugSB.append("md5 = ");
                apiDebugSB.append(md5);
                apiDebugSB.append("\n");
                apiTraceLog.debug(apiDebugSB.toString());
            }
        } else {
            writeBytesToOutputStream(outStream, sortedkeys.get(0), "=",
                    parameters.get(sortedkeys.get(0)).toString());
            if (apiTraceLog.isDebugEnabled()) {
                apiDebugSB.append("Starting TII CALL:\n");
                apiDebugSB.append(sortedkeys.get(0));
                apiDebugSB.append(" = ");
                apiDebugSB.append(parameters.get(sortedkeys.get(0)).toString());
                apiDebugSB.append("\n");
            }

            for (int i = 1; i < sortedkeys.size(); i++) {
                writeBytesToOutputStream(outStream, "&", sortedkeys.get(i), "=",
                        parameters.get(sortedkeys.get(i)).toString());
                if (apiTraceLog.isDebugEnabled()) {
                    apiDebugSB.append(sortedkeys.get(i));
                    apiDebugSB.append(" = ");
                    apiDebugSB.append(parameters.get(sortedkeys.get(i)).toString());
                    apiDebugSB.append("\n");
                }
            }

            writeBytesToOutputStream(outStream, "&md5=", md5);
            if (apiTraceLog.isDebugEnabled()) {
                apiDebugSB.append("md5 = ");
                apiDebugSB.append(md5);
                apiTraceLog.debug(apiDebugSB.toString());
            }
        }

        outStream.close();

        togo = connection.getInputStream();
    } catch (IOException t) {
        log.error("IOException making turnitin call.", t);
        throw new TransientSubmissionException("IOException making turnitin call.", t);
    } catch (ServerOverloadException t) {
        throw new TransientSubmissionException("Unable to submit the content data from ContentHosting", t);
    }

    return togo;

}

From source file:com.echopf.ECHOQuery.java

/**
 * Sends a HTTP request with optional request contents/parameters.
 * @param path a request url path/*from w  w w.j  a va2  s  . c  om*/
 * @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;
}