Example usage for java.net URLConnection setRequestProperty

List of usage examples for java.net URLConnection setRequestProperty

Introduction

In this page you can find the example usage for java.net URLConnection setRequestProperty.

Prototype

public void setRequestProperty(String key, String value) 

Source Link

Document

Sets the general request property.

Usage

From source file:carnero.cgeo.cgBase.java

public void postTweet(cgeoapplication app, cgSettings settings, String status, Double latitude,
        Double longitude) {/*from   w w  w .ja  v  a2 s. com*/
    if (app == null) {
        return;
    }
    if (settings == null || settings.tokenPublic == null || settings.tokenPublic.length() == 0
            || settings.tokenSecret == null || settings.tokenSecret.length() == 0) {
        return;
    }

    try {
        HashMap<String, String> parameters = new HashMap<String, String>();

        parameters.put("status", status);
        if (latitude != null && longitude != null) {
            parameters.put("lat", String.format("%.6f", latitude));
            parameters.put("long", String.format("%.6f", longitude));
            parameters.put("display_coordinates", "true");
        }

        final String paramsDone = cgOAuth.signOAuth("api.twitter.com", "/1/statuses/update.json", "POST", false,
                parameters, settings.tokenPublic, settings.tokenSecret);

        HttpURLConnection connection = null;
        try {
            final StringBuffer buffer = new StringBuffer();
            final URL u = new URL("http://api.twitter.com/1/statuses/update.json");
            final URLConnection uc = u.openConnection();

            uc.setRequestProperty("Host", "api.twitter.com");

            connection = (HttpURLConnection) uc;
            connection.setReadTimeout(30000);
            connection.setRequestMethod("POST");
            HttpURLConnection.setFollowRedirects(true);
            connection.setDoInput(true);
            connection.setDoOutput(true);

            final OutputStream out = connection.getOutputStream();
            final OutputStreamWriter wr = new OutputStreamWriter(out);
            wr.write(paramsDone);
            wr.flush();
            wr.close();

            Log.i(cgSettings.tag,
                    "Twitter.com: " + connection.getResponseCode() + " " + connection.getResponseMessage());

            InputStream ins;
            final String encoding = connection.getContentEncoding();

            if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
                ins = new GZIPInputStream(connection.getInputStream());
            } else if (encoding != null && encoding.equalsIgnoreCase("deflate")) {
                ins = new InflaterInputStream(connection.getInputStream(), new Inflater(true));
            } else {
                ins = connection.getInputStream();
            }

            final InputStreamReader inr = new InputStreamReader(ins);
            final BufferedReader br = new BufferedReader(inr);

            readIntoBuffer(br, buffer);

            br.close();
            ins.close();
            inr.close();
            connection.disconnect();
        } catch (IOException e) {
            Log.e(cgSettings.tag, "cgBase.postTweet.IO: " + connection.getResponseCode() + ": "
                    + connection.getResponseMessage() + " ~ " + e.toString());

            final InputStream ins = connection.getErrorStream();
            final StringBuffer buffer = new StringBuffer();
            final InputStreamReader inr = new InputStreamReader(ins);
            final BufferedReader br = new BufferedReader(inr);

            readIntoBuffer(br, buffer);

            br.close();
            ins.close();
            inr.close();
        } catch (Exception e) {
            Log.e(cgSettings.tag, "cgBase.postTweet.inner: " + e.toString());
        }

        connection.disconnect();
    } catch (Exception e) {
        Log.e(cgSettings.tag, "cgBase.postTweet: " + e.toString());
    }
}

From source file:org.tvbrowser.tvbrowser.TvBrowser.java

private void syncronizeChannels(final boolean replace) {
    new Thread() {
        public void run() {
            boolean somethingSynchonized = false;

            if (replace) {
                ContentValues values = new ContentValues();
                values.put(TvBrowserContentProvider.CHANNEL_KEY_SELECTION, 0);
                values.put(TvBrowserContentProvider.CHANNEL_KEY_ORDER_NUMBER, 0);

                getContentResolver().delete(TvBrowserContentProvider.CONTENT_URI_DATA,
                        TvBrowserContentProvider.KEY_ID + " >= 0 ", null);
                getContentResolver().delete(TvBrowserContentProvider.CONTENT_URI_DATA_VERSION,
                        TvBrowserContentProvider.KEY_ID + " >= 0", null);

                if (getContentResolver().update(TvBrowserContentProvider.CONTENT_URI_CHANNELS, values,
                        TvBrowserContentProvider.CHANNEL_KEY_SELECTION + "=1", null) > 0) {
                    somethingSynchonized = true;
                }//from www. j  a va 2 s .com
            }

            URL documentUrl;
            try {
                documentUrl = new URL(
                        "http://android.tvbrowser.org/data/scripts/syncDown.php?type=channelsFromDesktop");
                URLConnection connection = documentUrl.openConnection();

                SharedPreferences pref = getSharedPreferences("transportation", Context.MODE_PRIVATE);

                String car = pref.getString(SettingConstants.USER_NAME, null);
                String bicycle = pref.getString(SettingConstants.USER_PASSWORD, null);

                if (car != null && bicycle != null) {
                    String userpass = car + ":" + bicycle;
                    String basicAuth = "basic " + Base64.encodeToString(userpass.getBytes(), Base64.NO_WRAP);

                    connection.setRequestProperty("Authorization", basicAuth);

                    BufferedReader read = new BufferedReader(
                            new InputStreamReader(new GZIPInputStream(connection.getInputStream()), "UTF-8"));

                    String line = null;

                    int sort = 1;

                    while ((line = read.readLine()) != null) {
                        if (line.trim().length() > 0) {
                            if (line.contains(":")) {
                                String[] parts = line.split(":");

                                String dataService = null;
                                String groupKey = null;
                                String channelId = null;
                                String sortNumber = null;

                                if (parts[0].equals(SettingConstants
                                        .getNumberForDataServiceKey(SettingConstants.EPG_FREE_KEY))) {
                                    dataService = SettingConstants.EPG_FREE_KEY;
                                    groupKey = parts[1];
                                    channelId = parts[2];

                                    if (parts.length > 3) {
                                        sortNumber = parts[3];
                                    }
                                } else if (parts[0].equals(SettingConstants
                                        .getNumberForDataServiceKey(SettingConstants.EPG_DONATE_KEY))) {
                                    dataService = SettingConstants.EPG_DONATE_KEY;
                                    groupKey = SettingConstants.EPG_DONATE_GROUP_KEY;
                                    channelId = parts[1];

                                    if (parts.length > 2) {
                                        sortNumber = parts[2];
                                    }
                                }

                                if (dataService != null) {
                                    String where = " ( " + TvBrowserContentProvider.GROUP_KEY_DATA_SERVICE_ID
                                            + " = '" + dataService + "' ) AND ( "
                                            + TvBrowserContentProvider.GROUP_KEY_GROUP_ID + "='" + groupKey
                                            + "' ) ";

                                    Cursor group = getContentResolver().query(
                                            TvBrowserContentProvider.CONTENT_URI_GROUPS, null, where, null,
                                            null);

                                    if (group.moveToFirst()) {
                                        int groupId = group
                                                .getInt(group.getColumnIndex(TvBrowserContentProvider.KEY_ID));

                                        where = " ( " + TvBrowserContentProvider.GROUP_KEY_GROUP_ID + "="
                                                + groupId + " ) AND ( "
                                                + TvBrowserContentProvider.CHANNEL_KEY_CHANNEL_ID + "='"
                                                + channelId + "' ) ";

                                        ContentValues values = new ContentValues();

                                        if (sortNumber != null) {
                                            try {
                                                sort = Integer.parseInt(sortNumber);
                                            } catch (NumberFormatException e) {
                                            }
                                        }

                                        values.put(TvBrowserContentProvider.CHANNEL_KEY_SELECTION, 1);
                                        values.put(TvBrowserContentProvider.CHANNEL_KEY_ORDER_NUMBER, sort);

                                        int changed = getContentResolver().update(
                                                TvBrowserContentProvider.CONTENT_URI_CHANNELS, values, where,
                                                null);

                                        if (changed > 0) {
                                            somethingSynchonized = true;
                                        }
                                    }

                                    group.close();

                                    sort++;
                                }
                            }
                        }
                    }

                    if (somethingSynchonized) {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                SettingConstants.initializeLogoMap(TvBrowser.this, true);
                                updateProgramListChannelBar();
                                Toast.makeText(getApplicationContext(), R.string.synchronize_done,
                                        Toast.LENGTH_LONG).show();
                                checkTermsAccepted();
                            }
                        });
                    } else {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getApplicationContext(), R.string.synchronize_error,
                                        Toast.LENGTH_LONG).show();
                                showChannelSelectionInternal();
                            }
                        });
                    }
                } else {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            showChannelSelectionInternal();
                        }
                    });
                }
            } catch (Exception e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        showChannelSelectionInternal();
                    }
                });
            }

            selectingChannels = false;
        }
    }.start();

}

From source file:org.tvbrowser.tvbrowser.TvBrowser.java

private void synchronizeDontWantToSee(final boolean replace) {
    new Thread() {
        public void run() {
            if (!SettingConstants.UPDATING_FILTER) {
                SettingConstants.UPDATING_FILTER = true;

                Context applicationContext = getApplicationContext();

                NotificationCompat.Builder builder;

                builder = new NotificationCompat.Builder(TvBrowser.this);
                builder.setSmallIcon(R.drawable.ic_stat_notify);
                builder.setOngoing(true);
                builder.setContentTitle(getResources().getText(R.string.action_dont_want_to_see));
                builder.setContentText(getResources().getText(R.string.dont_want_to_see_notification_text));

                int notifyID = 2;

                NotificationManager notification = (NotificationManager) getSystemService(
                        Context.NOTIFICATION_SERVICE);
                notification.notify(notifyID, builder.build());

                updateProgressIcon(true);

                URL documentUrl;//w w  w . j a  v a 2  s  .  c o m

                try {
                    documentUrl = new URL(
                            "http://android.tvbrowser.org/data/scripts/syncDown.php?type=dontWantToSee");
                    URLConnection connection = documentUrl.openConnection();

                    SharedPreferences pref = getSharedPreferences("transportation", Context.MODE_PRIVATE);

                    String car = pref.getString(SettingConstants.USER_NAME, null);
                    String bicycle = pref.getString(SettingConstants.USER_PASSWORD, null);

                    if (car != null && bicycle != null) {
                        String userpass = car + ":" + bicycle;
                        String basicAuth = "basic "
                                + Base64.encodeToString(userpass.getBytes(), Base64.NO_WRAP);

                        connection.setRequestProperty("Authorization", basicAuth);

                        BufferedReader read = new BufferedReader(new InputStreamReader(
                                new GZIPInputStream(connection.getInputStream()), "UTF-8"));

                        String line = null;

                        StringBuilder exclusionBuilder = new StringBuilder();
                        HashSet<String> exclusions = new HashSet<String>();
                        ArrayList<DontWantToSeeExclusion> exclusionList = new ArrayList<DontWantToSeeExclusion>();

                        while ((line = read.readLine()) != null) {
                            if (line.contains(";;") && line.trim().length() > 0) {
                                exclusions.add(line);
                                exclusionList.add(new DontWantToSeeExclusion(line));
                                exclusionBuilder.append(line).append("\n");
                            }
                        }

                        String key = getString(R.string.I_DONT_WANT_TO_SEE_ENTRIES);
                        SharedPreferences pref1 = PreferenceManager.getDefaultSharedPreferences(TvBrowser.this);

                        Set<String> oldValues = pref1.getStringSet(key, null);

                        if (exclusions.size() > 0) {
                            if (!replace && oldValues != null) {
                                for (String old : oldValues) {
                                    if (!exclusions.contains(old)) {
                                        exclusions.add(old);
                                        exclusionList.add(new DontWantToSeeExclusion(old));
                                        exclusionBuilder.append(old).append("\n");
                                    }
                                }
                            }

                            Editor edit = pref1.edit();

                            edit.putStringSet(key, exclusions);
                            edit.commit();

                            DontWantToSeeExclusion[] exclusionArr = exclusionList
                                    .toArray(new DontWantToSeeExclusion[exclusionList.size()]);

                            Cursor c = getContentResolver().query(TvBrowserContentProvider.CONTENT_URI_DATA,
                                    new String[] { TvBrowserContentProvider.KEY_ID,
                                            TvBrowserContentProvider.DATA_KEY_TITLE },
                                    null, null, TvBrowserContentProvider.KEY_ID);
                            c.moveToPosition(-1);

                            builder.setProgress(c.getCount(), 0, true);
                            notification.notify(notifyID, builder.build());

                            ArrayList<ContentProviderOperation> updateValuesList = new ArrayList<ContentProviderOperation>();

                            int keyColumn = c.getColumnIndex(TvBrowserContentProvider.KEY_ID);
                            int titleColumn = c.getColumnIndex(TvBrowserContentProvider.DATA_KEY_TITLE);

                            while (c.moveToNext()) {
                                builder.setProgress(c.getCount(), c.getPosition(), false);
                                notification.notify(notifyID, builder.build());

                                String title = c.getString(titleColumn);

                                boolean filter = UiUtils.filter(getApplicationContext(), title, exclusionArr);
                                long progID = c.getLong(keyColumn);

                                ContentValues values = new ContentValues();
                                values.put(TvBrowserContentProvider.DATA_KEY_DONT_WANT_TO_SEE, filter ? 1 : 0);

                                ContentProviderOperation.Builder opBuilder = ContentProviderOperation
                                        .newUpdate(ContentUris.withAppendedId(
                                                TvBrowserContentProvider.CONTENT_URI_DATA_UPDATE, progID));
                                opBuilder.withValues(values);

                                updateValuesList.add(opBuilder.build());
                            }

                            c.close();

                            if (!updateValuesList.isEmpty()) {
                                try {
                                    getContentResolver().applyBatch(TvBrowserContentProvider.AUTHORITY,
                                            updateValuesList);
                                    UiUtils.sendDontWantToSeeChangedBroadcast(applicationContext, true);
                                    handler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(getApplicationContext(),
                                                    R.string.dont_want_to_see_sync_success, Toast.LENGTH_LONG)
                                                    .show();
                                        }
                                    });
                                } catch (RemoteException e) {
                                    e.printStackTrace();
                                } catch (OperationApplicationException e) {
                                    e.printStackTrace();
                                }
                            }

                            if (!replace && exclusionBuilder.length() > 0) {
                                startSynchronizeUp(false, exclusionBuilder.toString(),
                                        "http://android.tvbrowser.org/data/scripts/syncUp.php?type=dontWantToSee",
                                        null, null);
                            }
                        } else {
                            if (!replace && oldValues != null && !oldValues.isEmpty()) {
                                for (String old : oldValues) {
                                    exclusionBuilder.append(old).append("\n");
                                }

                                startSynchronizeUp(false, exclusionBuilder.toString(),
                                        "http://android.tvbrowser.org/data/scripts/syncUp.php?type=dontWantToSee",
                                        null, null);
                            }

                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(getApplicationContext(), R.string.no_dont_want_to_see_sync,
                                            Toast.LENGTH_LONG).show();
                                }
                            });
                        }
                    }
                } catch (Throwable t) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(), R.string.no_dont_want_to_see_sync,
                                    Toast.LENGTH_LONG).show();
                        }
                    });
                }

                notification.cancel(notifyID);
                updateProgressIcon(false);

                SettingConstants.UPDATING_FILTER = false;
            }
        }
    }.start();
}

From source file:org.tvbrowser.tvbrowser.TvBrowser.java

private void restorePreferencesInternal() {
    handler.post(new Runnable() {
        @Override// ww w.j a  v  a 2  s .  c  om
        public void run() {
            mViewPager.setCurrentItem(0, true);

            for (int i = mSectionsPagerAdapter.getCount() - 1; i >= 0; i--) {
                mSectionsPagerAdapter.destroyItem(mViewPager, i,
                        mSectionsPagerAdapter.getRegisteredFragment(i));
                mSectionsPagerAdapter.notifyDataSetChanged();
                actionBar.removeTabAt(i);
            }

            actionBar.addTab(actionBar.newTab().setText(getString(R.string.tab_restoring_name))
                    .setTabListener(new ActionBar.TabListener() {
                        @Override
                        public void onTabUnselected(Tab arg0, FragmentTransaction arg1) {
                        }

                        @Override
                        public void onTabSelected(Tab arg0, FragmentTransaction arg1) {
                        }

                        @Override
                        public void onTabReselected(Tab arg0, FragmentTransaction arg1) {
                        }
                    }));

            new Thread("RESTORE PREFERENCES") {
                @Override
                public void run() {
                    updateProgressIcon(true);

                    URL documentUrl;

                    BufferedReader read = null;
                    boolean restored = false;

                    try {
                        documentUrl = new URL(
                                "http://android.tvbrowser.org/data/scripts/syncDown.php?type=preferencesBackup");
                        URLConnection connection = documentUrl.openConnection();

                        SharedPreferences pref = getSharedPreferences("transportation", Context.MODE_PRIVATE);

                        String car = pref.getString(SettingConstants.USER_NAME, null);
                        String bicycle = pref.getString(SettingConstants.USER_PASSWORD, null);

                        if (car != null && bicycle != null) {
                            String userpass = car + ":" + bicycle;
                            String basicAuth = "basic "
                                    + Base64.encodeToString(userpass.getBytes(), Base64.NO_WRAP);

                            connection.setRequestProperty("Authorization", basicAuth);

                            read = new BufferedReader(new InputStreamReader(
                                    new GZIPInputStream(connection.getInputStream()), "UTF-8"));

                            String line = null;
                            Editor edit = PreferenceManager.getDefaultSharedPreferences(getApplicationContext())
                                    .edit();

                            TvBrowserContentProvider.INFORM_FOR_CHANGES = false;

                            final Favorite[] existingFavorites = Favorite
                                    .getAllFavorites(getApplicationContext());

                            while ((line = read.readLine()) != null) {
                                int index = line.indexOf(":");

                                if (index > 0) {
                                    restored = true;
                                    String type = line.substring(0, index);
                                    String[] parts = line.substring(index + 1).split("=");

                                    if (parts != null && parts.length > 1) {
                                        if (type.equals("boolean")) {
                                            boolean boolValue = Boolean.valueOf(parts[1].trim());

                                            if (!getString(R.string.PREF_RATING_DONATION_INFO_SHOWN)
                                                    .equals(parts[0]) || boolValue) {
                                                edit.putBoolean(parts[0], boolValue);
                                            }
                                        } else if (type.equals("int")) {
                                            if (!getString(R.string.OLD_VERSION).equals(parts[0])) {
                                                edit.putInt(parts[0], Integer.valueOf(parts[1].trim()));
                                            }
                                        } else if (type.equals("float")) {
                                            edit.putFloat(parts[0], Float.valueOf(parts[1].trim()));
                                        } else if (type.equals("long")) {
                                            edit.putLong(parts[0], Long.valueOf(parts[1].trim()));
                                        } else if (type.equals("string")) {
                                            edit.putString(parts[0], parts[1].trim());
                                        } else if (type.equals("set")) {
                                            HashSet<String> set = new HashSet<String>();

                                            String[] setParts = parts[1].split("#,#");

                                            if (setParts != null && setParts.length > 0) {
                                                if (parts[0].equals("FAVORITE_LIST")) {
                                                    Favorite.deleteAllFavorites(getApplicationContext());
                                                    int id = 1000;

                                                    for (String setPart : setParts) {
                                                        Favorite favorite = new Favorite(id++, setPart);
                                                        favorite.loadChannelRestrictionIdsFromUniqueChannelRestriction(
                                                                getApplicationContext());
                                                        Favorite.handleFavoriteMarking(getApplicationContext(),
                                                                favorite, Favorite.TYPE_MARK_ADD);
                                                    }
                                                } else {
                                                    for (String setPart : setParts) {
                                                        set.add(setPart);
                                                    }

                                                    edit.putStringSet(parts[0], set);
                                                }
                                            }
                                        } else if (type.equals("favorite")) {
                                            Favorite favorite = new Favorite(Long.parseLong(parts[0]),
                                                    parts[1]);

                                            for (Favorite test : existingFavorites) {
                                                if (test.getFavoriteId() == favorite.getFavoriteId()) {
                                                    Favorite.deleteFavorite(getApplicationContext(), favorite);
                                                    break;
                                                }
                                            }

                                            favorite.loadChannelRestrictionIdsFromUniqueChannelRestriction(
                                                    getApplicationContext());
                                            Favorite.handleFavoriteMarking(getApplicationContext(), favorite,
                                                    Favorite.TYPE_MARK_ADD);
                                        }
                                    }
                                }
                            }

                            TvBrowserContentProvider.INFORM_FOR_CHANGES = true;

                            if (restored) {
                                edit.commit();
                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        updateFromPreferences(true);
                                    }
                                });

                                IOUtils.handleDataUpdatePreferences(getApplicationContext());
                            }
                        }
                    } catch (Exception e) {
                        restored = false;
                    } finally {
                        if (read != null) {
                            try {
                                read.close();
                            } catch (IOException e) {
                            }
                        }
                    }

                    if (restored) {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(TvBrowser.this,
                                        getString(R.string.backup_preferences_restore_success),
                                        Toast.LENGTH_LONG).show();
                            }
                        });
                    } else {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(TvBrowser.this,
                                        getString(R.string.backup_preferences_restore_failure),
                                        Toast.LENGTH_LONG).show();
                            }
                        });
                    }

                    updateProgressIcon(false);
                }
            }.start();
        }
    });
}

From source file:carnero.cgeo.original.libs.Base.java

public String requestJSONgc(String host, String path, String params) {
    int httpCode = -1;
    String httpLocation = null;//from   w  w w. j a  v a  2 s  .  c om

    // prepare cookies
    String cookiesDone = null;
    if (cookies == null || cookies.isEmpty() == true) {
        if (cookies == null) {
            cookies = new HashMap<String, String>();
        }

        final Map<String, ?> prefsAll = prefs.getAll();
        final Set<String> prefsKeys = prefsAll.keySet();

        for (String key : prefsKeys) {
            if (key.matches("cookie_.+") == true) {
                final String cookieKey = key.substring(7);
                final String cookieValue = (String) prefsAll.get(key);

                cookies.put(cookieKey, cookieValue);
            }
        }
    }

    if (cookies != null) {
        final Object[] keys = cookies.keySet().toArray();
        final ArrayList<String> cookiesEncoded = new ArrayList<String>();

        for (int i = 0; i < keys.length; i++) {
            String value = cookies.get(keys[i].toString());
            cookiesEncoded.add(keys[i] + "=" + value);
        }

        if (cookiesEncoded.size() > 0) {
            cookiesDone = implode("; ", cookiesEncoded.toArray());
        }
    }

    if (cookiesDone == null) {
        Map<String, ?> prefsValues = prefs.getAll();

        if (prefsValues != null && prefsValues.size() > 0) {
            final Object[] keys = prefsValues.keySet().toArray();
            final ArrayList<String> cookiesEncoded = new ArrayList<String>();
            final int length = keys.length;

            for (int i = 0; i < length; i++) {
                if (keys[i].toString().length() > 7
                        && keys[i].toString().substring(0, 7).equals("cookie_") == true) {
                    cookiesEncoded
                            .add(keys[i].toString().substring(7) + "=" + prefsValues.get(keys[i].toString()));
                }
            }

            if (cookiesEncoded.size() > 0) {
                cookiesDone = implode("; ", cookiesEncoded.toArray());
            }
        }
    }

    if (cookiesDone == null) {
        cookiesDone = "";
    }

    URLConnection uc = null;
    HttpURLConnection connection = null;
    Integer timeout = 30000;
    final StringBuffer buffer = new StringBuffer();

    for (int i = 0; i < 3; i++) {
        if (i > 0) {
            Log.w(Settings.tag, "Failed to download data, retrying. Attempt #" + (i + 1));
        }

        buffer.delete(0, buffer.length());
        timeout = 30000 + (i * 15000);

        try {
            // POST
            final URL u = new URL("http://" + host + path);
            uc = u.openConnection();

            uc.setRequestProperty("Host", host);
            uc.setRequestProperty("Cookie", cookiesDone);
            uc.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            uc.setRequestProperty("X-Requested-With", "XMLHttpRequest");
            uc.setRequestProperty("Accept", "application/json, text/javascript, */*; q=0.01");
            uc.setRequestProperty("Referer", host + "/" + path);

            if (settings.asBrowser == 1) {
                uc.setRequestProperty("Accept-Charset", "utf-8, iso-8859-1, utf-16, *;q=0.7");
                uc.setRequestProperty("Accept-Language", "en-US");
                uc.setRequestProperty("User-Agent", idBrowser);
                uc.setRequestProperty("Connection", "keep-alive");
                uc.setRequestProperty("Keep-Alive", "300");
            }

            connection = (HttpURLConnection) uc;
            connection.setReadTimeout(timeout);
            connection.setRequestMethod("POST");
            HttpURLConnection.setFollowRedirects(false); // TODO: Fix these (FilCab)
            connection.setDoInput(true);
            connection.setDoOutput(true);

            final OutputStream out = connection.getOutputStream();
            final OutputStreamWriter wr = new OutputStreamWriter(out);
            wr.write(params);
            wr.flush();
            wr.close();

            String headerName = null;
            final SharedPreferences.Editor prefsEditor = prefs.edit();
            for (int j = 1; (headerName = uc.getHeaderFieldKey(j)) != null; j++) {
                if (headerName != null && headerName.equalsIgnoreCase("Set-Cookie")) {
                    int index;
                    String cookie = uc.getHeaderField(j);

                    index = cookie.indexOf(";");
                    if (index > -1) {
                        cookie = cookie.substring(0, cookie.indexOf(";"));
                    }

                    index = cookie.indexOf("=");
                    if (index > -1 && cookie.length() > (index + 1)) {
                        String name = cookie.substring(0, cookie.indexOf("="));
                        String value = cookie.substring(cookie.indexOf("=") + 1, cookie.length());

                        cookies.put(name, value);
                        prefsEditor.putString("cookie_" + name, value);
                    }
                }
            }
            prefsEditor.commit();

            final String encoding = connection.getContentEncoding();
            InputStream ins;

            if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
                ins = new GZIPInputStream(connection.getInputStream());
            } else if (encoding != null && encoding.equalsIgnoreCase("deflate")) {
                ins = new InflaterInputStream(connection.getInputStream(), new Inflater(true));
            } else {
                ins = connection.getInputStream();
            }
            final InputStreamReader inr = new InputStreamReader(ins);
            final BufferedReader br = new BufferedReader(inr);

            readIntoBuffer(br, buffer);

            httpCode = connection.getResponseCode();
            httpLocation = uc.getHeaderField("Location");

            final String paramsLog = params.replaceAll(passMatch, "password=***");
            Log.i(Settings.tag + " | JSON",
                    "[POST " + (int) (params.length() / 1024) + "k | " + httpCode + " | "
                            + (int) (buffer.length() / 1024) + "k] Downloaded " + "http://" + host + path + "?"
                            + paramsLog);

            connection.disconnect();
            br.close();
            ins.close();
            inr.close();
        } catch (IOException e) {
            Log.e(Settings.tag, "cgeoBase.requestJSONgc.IOException: " + e.toString());
        } catch (Exception e) {
            Log.e(Settings.tag, "cgeoBase.requestJSONgc: " + e.toString());
        }

        if (buffer != null && buffer.length() > 0) {
            break;
        }
    }

    String page = null;
    if (httpCode == 302 && httpLocation != null) {
        final Uri newLocation = Uri.parse(httpLocation);
        if (newLocation.isRelative() == true) {
            page = requestJSONgc(host, path, params);
        } else {
            page = requestJSONgc(newLocation.getHost(), newLocation.getPath(), params);
        }
    } else {
        page = replaceWhitespace(buffer);
    }

    if (page != null) {
        return page;
    } else {
        return "";
    }
}

From source file:carnero.cgeo.original.libs.Base.java

public Response request(boolean secure, String host, String path, String method, String params, int requestId,
        Boolean xContentType) {/*ww w.  j av  a  2 s.  co  m*/
    URL u = null;
    int httpCode = -1;
    String httpMessage = null;
    String httpLocation = null;

    if (requestId == 0) {
        requestId = (int) (Math.random() * 1000);
    }

    if (method == null
            || (method.equalsIgnoreCase("GET") == false && method.equalsIgnoreCase("POST") == false)) {
        method = "POST";
    } else {
        method = method.toUpperCase();
    }

    // https
    String scheme = "http://";
    if (secure) {
        scheme = "https://";
    }

    // prepare cookies
    String cookiesDone = null;
    if (cookies == null || cookies.isEmpty() == true) {
        if (cookies == null) {
            cookies = new HashMap<String, String>();
        }

        final Map<String, ?> prefsAll = prefs.getAll();
        final Set<String> prefsKeys = prefsAll.keySet();

        for (String key : prefsKeys) {
            if (key.matches("cookie_.+") == true) {
                final String cookieKey = key.substring(7);
                final String cookieValue = (String) prefsAll.get(key);

                cookies.put(cookieKey, cookieValue);
            }
        }
    }

    if (cookies != null && !cookies.isEmpty() && cookies.keySet().size() > 0) {
        final Object[] keys = cookies.keySet().toArray();
        final ArrayList<String> cookiesEncoded = new ArrayList<String>();

        for (int i = 0; i < keys.length; i++) {
            String value = cookies.get(keys[i].toString());
            cookiesEncoded.add(keys[i] + "=" + value);
        }

        if (cookiesEncoded.size() > 0) {
            cookiesDone = implode("; ", cookiesEncoded.toArray());
        }
    }

    if (cookiesDone == null) {
        Map<String, ?> prefsValues = prefs.getAll();

        if (prefsValues != null && prefsValues.size() > 0 && prefsValues.keySet().size() > 0) {
            final Object[] keys = prefsValues.keySet().toArray();
            final ArrayList<String> cookiesEncoded = new ArrayList<String>();
            final int length = keys.length;

            for (int i = 0; i < length; i++) {
                if (keys[i].toString().length() > 7
                        && keys[i].toString().substring(0, 7).equals("cookie_") == true) {
                    cookiesEncoded
                            .add(keys[i].toString().substring(7) + "=" + prefsValues.get(keys[i].toString()));
                }
            }

            if (cookiesEncoded.size() > 0) {
                cookiesDone = implode("; ", cookiesEncoded.toArray());
            }
        }
    }

    if (cookiesDone == null) {
        cookiesDone = "";
    }

    URLConnection uc = null;
    HttpURLConnection connection = null;
    Integer timeout = 30000;
    StringBuffer buffer = null;

    for (int i = 0; i < 5; i++) {
        if (i > 0) {
            Log.w(Settings.tag, "Failed to download data, retrying. Attempt #" + (i + 1));
        }

        buffer = new StringBuffer();
        timeout = 30000 + (i * 10000);

        try {
            if (method.equals("GET")) {
                // GET
                u = new URL(scheme + host + path + "?" + params);
                uc = u.openConnection();

                uc.setRequestProperty("Host", host);
                uc.setRequestProperty("Cookie", cookiesDone);
                if (xContentType == true) {
                    uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                }

                if (settings.asBrowser == 1) {
                    uc.setRequestProperty("Accept",
                            "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
                    // uc.setRequestProperty("Accept-Encoding", "gzip"); // not supported via cellular network
                    uc.setRequestProperty("Accept-Charset", "utf-8, iso-8859-1, utf-16, *;q=0.7");
                    uc.setRequestProperty("Accept-Language", "en-US");
                    uc.setRequestProperty("User-Agent", idBrowser);
                    uc.setRequestProperty("Connection", "keep-alive");
                    uc.setRequestProperty("Keep-Alive", "300");
                }

                connection = (HttpURLConnection) uc;
                connection.setReadTimeout(timeout);
                connection.setRequestMethod(method);
                HttpURLConnection.setFollowRedirects(false);
                connection.setDoInput(true);
                connection.setDoOutput(false);
            } else {
                // POST
                u = new URL(scheme + host + path);
                uc = u.openConnection();

                uc.setRequestProperty("Host", host);
                uc.setRequestProperty("Cookie", cookiesDone);
                if (xContentType == true) {
                    uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                }

                if (settings.asBrowser == 1) {
                    uc.setRequestProperty("Accept",
                            "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
                    // uc.setRequestProperty("Accept-Encoding", "gzip"); // not supported via cellular network
                    uc.setRequestProperty("Accept-Charset", "utf-8, iso-8859-1, utf-16, *;q=0.7");
                    uc.setRequestProperty("Accept-Language", "en-US");
                    uc.setRequestProperty("User-Agent", idBrowser);
                    uc.setRequestProperty("Connection", "keep-alive");
                    uc.setRequestProperty("Keep-Alive", "300");
                }

                connection = (HttpURLConnection) uc;
                connection.setReadTimeout(timeout);
                connection.setRequestMethod(method);
                HttpURLConnection.setFollowRedirects(false);
                connection.setDoInput(true);
                connection.setDoOutput(true);

                final OutputStream out = connection.getOutputStream();
                final OutputStreamWriter wr = new OutputStreamWriter(out);
                wr.write(params);
                wr.flush();
                wr.close();
            }

            String headerName = null;
            final SharedPreferences.Editor prefsEditor = prefs.edit();
            for (int j = 1; (headerName = uc.getHeaderFieldKey(j)) != null; j++) {
                if (headerName != null && headerName.equalsIgnoreCase("Set-Cookie")) {
                    int index;
                    String cookie = uc.getHeaderField(j);

                    index = cookie.indexOf(";");
                    if (index > -1) {
                        cookie = cookie.substring(0, cookie.indexOf(";"));
                    }

                    index = cookie.indexOf("=");
                    if (index > -1 && cookie.length() > (index + 1)) {
                        String name = cookie.substring(0, cookie.indexOf("="));
                        String value = cookie.substring(cookie.indexOf("=") + 1, cookie.length());

                        cookies.put(name, value);
                        prefsEditor.putString("cookie_" + name, value);
                    }
                }
            }
            prefsEditor.commit();

            final String encoding = connection.getContentEncoding();
            InputStream ins;

            if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
                ins = new GZIPInputStream(connection.getInputStream());
            } else if (encoding != null && encoding.equalsIgnoreCase("deflate")) {
                ins = new InflaterInputStream(connection.getInputStream(), new Inflater(true));
            } else {
                ins = connection.getInputStream();
            }
            final InputStreamReader inr = new InputStreamReader(ins);
            final BufferedReader br = new BufferedReader(inr);

            readIntoBuffer(br, buffer);

            httpCode = connection.getResponseCode();
            httpMessage = connection.getResponseMessage();
            httpLocation = uc.getHeaderField("Location");

            final String paramsLog = params.replaceAll(passMatch, "password=***");
            if (buffer != null && connection != null) {
                Log.i(Settings.tag + "|" + requestId,
                        "[" + method + " " + (int) (params.length() / 1024) + "k | " + httpCode + " | "
                                + (int) (buffer.length() / 1024) + "k] Downloaded " + scheme + host + path + "?"
                                + paramsLog);
            } else {
                Log.i(Settings.tag + "|" + requestId, "[" + method + " | " + httpCode + "] Failed to download "
                        + scheme + host + path + "?" + paramsLog);
            }

            connection.disconnect();
            br.close();
            ins.close();
            inr.close();
        } catch (IOException e) {
            Log.e(Settings.tag, "cgeoBase.request.IOException: " + e.toString());
        } catch (Exception e) {
            Log.e(Settings.tag, "cgeoBase.request: " + e.toString());
        }

        if (buffer != null && buffer.length() > 0) {
            break;
        }
    }

    Response response = new Response();
    String data = null;

    try {
        if (httpCode == 302 && httpLocation != null) {
            final Uri newLocation = Uri.parse(httpLocation);
            if (newLocation.isRelative() == true) {
                response = request(secure, host, path, "GET", new HashMap<String, String>(), requestId, false,
                        false, false);
            } else {
                boolean secureRedir = false;
                if (newLocation.getScheme().equals("https")) {
                    secureRedir = true;
                }
                response = request(secureRedir, newLocation.getHost(), newLocation.getPath(), "GET",
                        new HashMap<String, String>(), requestId, false, false, false);
            }
        } else {
            if (buffer != null && buffer.length() > 0) {
                data = replaceWhitespace(buffer);
                buffer = null;

                if (data != null) {
                    response.setData(data);
                } else {
                    response.setData("");
                }
                response.setStatusCode(httpCode);
                response.setStatusMessage(httpMessage);
                response.setUrl(u.toString());
            }
        }
    } catch (Exception e) {
        Log.e(Settings.tag, "cgeoBase.page: " + e.toString());
    }

    return response;
}

From source file:carnero.cgeo.cgBase.java

public String requestJSONgc(String host, String path, String params) {
    int httpCode = -1;
    String httpLocation = null;//from  ww  w . j a v a  2  s .  co  m

    // prepare cookies
    String cookiesDone = null;
    if (cookies == null || cookies.isEmpty() == true) {
        if (cookies == null) {
            cookies = new HashMap<String, String>();
        }

        final Map<String, ?> prefsAll = prefs.getAll();
        final Set<String> prefsKeys = prefsAll.keySet();

        for (String key : prefsKeys) {
            if (key.matches("cookie_.+") == true) {
                final String cookieKey = key.substring(7);
                final String cookieValue = (String) prefsAll.get(key);

                cookies.put(cookieKey, cookieValue);
            }
        }
    }

    if (cookies != null) {
        final Object[] keys = cookies.keySet().toArray();
        final ArrayList<String> cookiesEncoded = new ArrayList<String>();

        for (int i = 0; i < keys.length; i++) {
            String value = cookies.get(keys[i].toString());
            cookiesEncoded.add(keys[i] + "=" + value);
        }

        if (cookiesEncoded.size() > 0) {
            cookiesDone = implode("; ", cookiesEncoded.toArray());
        }
    }

    if (cookiesDone == null) {
        Map<String, ?> prefsValues = prefs.getAll();

        if (prefsValues != null && prefsValues.size() > 0) {
            final Object[] keys = prefsValues.keySet().toArray();
            final ArrayList<String> cookiesEncoded = new ArrayList<String>();
            final int length = keys.length;

            for (int i = 0; i < length; i++) {
                if (keys[i].toString().length() > 7
                        && keys[i].toString().substring(0, 7).equals("cookie_") == true) {
                    cookiesEncoded
                            .add(keys[i].toString().substring(7) + "=" + prefsValues.get(keys[i].toString()));
                }
            }

            if (cookiesEncoded.size() > 0) {
                cookiesDone = implode("; ", cookiesEncoded.toArray());
            }
        }
    }

    if (cookiesDone == null) {
        cookiesDone = "";
    }

    URLConnection uc = null;
    HttpURLConnection connection = null;
    Integer timeout = 30000;
    final StringBuffer buffer = new StringBuffer();

    for (int i = 0; i < 3; i++) {
        if (i > 0) {
            Log.w(cgSettings.tag, "Failed to download data, retrying. Attempt #" + (i + 1));
        }

        buffer.delete(0, buffer.length());
        timeout = 30000 + (i * 15000);

        try {
            // POST
            final URL u = new URL("http://" + host + path);
            uc = u.openConnection();

            uc.setRequestProperty("Host", host);
            uc.setRequestProperty("Cookie", cookiesDone);
            uc.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            uc.setRequestProperty("X-Requested-With", "XMLHttpRequest");
            uc.setRequestProperty("Accept", "application/json, text/javascript, */*; q=0.01");
            uc.setRequestProperty("Referer", host + "/" + path);

            if (settings.asBrowser == 1) {
                uc.setRequestProperty("Accept-Charset", "utf-8, iso-8859-1, utf-16, *;q=0.7");
                uc.setRequestProperty("Accept-Language", "en-US");
                uc.setRequestProperty("User-Agent", idBrowser);
                uc.setRequestProperty("Connection", "keep-alive");
                uc.setRequestProperty("Keep-Alive", "300");
            }

            connection = (HttpURLConnection) uc;
            connection.setReadTimeout(timeout);
            connection.setRequestMethod("POST");
            HttpURLConnection.setFollowRedirects(false); // TODO: Fix these (FilCab)
            connection.setDoInput(true);
            connection.setDoOutput(true);

            final OutputStream out = connection.getOutputStream();
            final OutputStreamWriter wr = new OutputStreamWriter(out);
            wr.write(params);
            wr.flush();
            wr.close();

            String headerName = null;
            final SharedPreferences.Editor prefsEditor = prefs.edit();
            for (int j = 1; (headerName = uc.getHeaderFieldKey(j)) != null; j++) {
                if (headerName != null && headerName.equalsIgnoreCase("Set-Cookie")) {
                    int index;
                    String cookie = uc.getHeaderField(j);

                    index = cookie.indexOf(";");
                    if (index > -1) {
                        cookie = cookie.substring(0, cookie.indexOf(";"));
                    }

                    index = cookie.indexOf("=");
                    if (index > -1 && cookie.length() > (index + 1)) {
                        String name = cookie.substring(0, cookie.indexOf("="));
                        String value = cookie.substring(cookie.indexOf("=") + 1, cookie.length());

                        cookies.put(name, value);
                        prefsEditor.putString("cookie_" + name, value);
                    }
                }
            }
            prefsEditor.commit();

            final String encoding = connection.getContentEncoding();
            InputStream ins;

            if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
                ins = new GZIPInputStream(connection.getInputStream());
            } else if (encoding != null && encoding.equalsIgnoreCase("deflate")) {
                ins = new InflaterInputStream(connection.getInputStream(), new Inflater(true));
            } else {
                ins = connection.getInputStream();
            }
            final InputStreamReader inr = new InputStreamReader(ins);
            final BufferedReader br = new BufferedReader(inr);

            readIntoBuffer(br, buffer);

            httpCode = connection.getResponseCode();
            httpLocation = uc.getHeaderField("Location");

            final String paramsLog = params.replaceAll(passMatch, "password=***");
            Log.i(cgSettings.tag + " | JSON",
                    "[POST " + (int) (params.length() / 1024) + "k | " + httpCode + " | "
                            + (int) (buffer.length() / 1024) + "k] Downloaded " + "http://" + host + path + "?"
                            + paramsLog);

            connection.disconnect();
            br.close();
            ins.close();
            inr.close();
        } catch (IOException e) {
            Log.e(cgSettings.tag, "cgeoBase.requestJSONgc.IOException: " + e.toString());
        } catch (Exception e) {
            Log.e(cgSettings.tag, "cgeoBase.requestJSONgc: " + e.toString());
        }

        if (buffer != null && buffer.length() > 0) {
            break;
        }
    }

    String page = null;
    if (httpCode == 302 && httpLocation != null) {
        final Uri newLocation = Uri.parse(httpLocation);
        if (newLocation.isRelative() == true) {
            page = requestJSONgc(host, path, params);
        } else {
            page = requestJSONgc(newLocation.getHost(), newLocation.getPath(), params);
        }
    } else {
        page = replaceWhitespace(buffer);
    }

    if (page != null) {
        return page;
    } else {
        return "";
    }
}

From source file:carnero.cgeo.cgBase.java

public cgResponse request(boolean secure, String host, String path, String method, String params, int requestId,
        Boolean xContentType) {/*from ww w .  j a va 2s  . c  o m*/
    URL u = null;
    int httpCode = -1;
    String httpMessage = null;
    String httpLocation = null;

    if (requestId == 0) {
        requestId = (int) (Math.random() * 1000);
    }

    if (method == null
            || (method.equalsIgnoreCase("GET") == false && method.equalsIgnoreCase("POST") == false)) {
        method = "POST";
    } else {
        method = method.toUpperCase();
    }

    // https
    String scheme = "http://";
    if (secure) {
        scheme = "https://";
    }

    // prepare cookies
    String cookiesDone = null;
    if (cookies == null || cookies.isEmpty() == true) {
        if (cookies == null) {
            cookies = new HashMap<String, String>();
        }

        final Map<String, ?> prefsAll = prefs.getAll();
        final Set<String> prefsKeys = prefsAll.keySet();

        for (String key : prefsKeys) {
            if (key.matches("cookie_.+") == true) {
                final String cookieKey = key.substring(7);
                final String cookieValue = (String) prefsAll.get(key);

                cookies.put(cookieKey, cookieValue);
            }
        }
    }

    if (cookies != null && !cookies.isEmpty() && cookies.keySet().size() > 0) {
        final Object[] keys = cookies.keySet().toArray();
        final ArrayList<String> cookiesEncoded = new ArrayList<String>();

        for (int i = 0; i < keys.length; i++) {
            String value = cookies.get(keys[i].toString());
            cookiesEncoded.add(keys[i] + "=" + value);
        }

        if (cookiesEncoded.size() > 0) {
            cookiesDone = implode("; ", cookiesEncoded.toArray());
        }
    }

    if (cookiesDone == null) {
        Map<String, ?> prefsValues = prefs.getAll();

        if (prefsValues != null && prefsValues.size() > 0 && prefsValues.keySet().size() > 0) {
            final Object[] keys = prefsValues.keySet().toArray();
            final ArrayList<String> cookiesEncoded = new ArrayList<String>();
            final int length = keys.length;

            for (int i = 0; i < length; i++) {
                if (keys[i].toString().length() > 7
                        && keys[i].toString().substring(0, 7).equals("cookie_") == true) {
                    cookiesEncoded
                            .add(keys[i].toString().substring(7) + "=" + prefsValues.get(keys[i].toString()));
                }
            }

            if (cookiesEncoded.size() > 0) {
                cookiesDone = implode("; ", cookiesEncoded.toArray());
            }
        }
    }

    if (cookiesDone == null) {
        cookiesDone = "";
    }

    URLConnection uc = null;
    HttpURLConnection connection = null;
    Integer timeout = 30000;
    StringBuffer buffer = null;

    for (int i = 0; i < 5; i++) {
        if (i > 0) {
            Log.w(cgSettings.tag, "Failed to download data, retrying. Attempt #" + (i + 1));
        }

        buffer = new StringBuffer();
        timeout = 30000 + (i * 10000);

        try {
            if (method.equals("GET")) {
                // GET
                u = new URL(scheme + host + path + "?" + params);
                uc = u.openConnection();

                uc.setRequestProperty("Host", host);
                uc.setRequestProperty("Cookie", cookiesDone);
                if (xContentType == true) {
                    uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                }

                if (settings.asBrowser == 1) {
                    uc.setRequestProperty("Accept",
                            "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
                    // uc.setRequestProperty("Accept-Encoding", "gzip"); // not supported via cellular network
                    uc.setRequestProperty("Accept-Charset", "utf-8, iso-8859-1, utf-16, *;q=0.7");
                    uc.setRequestProperty("Accept-Language", "en-US");
                    uc.setRequestProperty("User-Agent", idBrowser);
                    uc.setRequestProperty("Connection", "keep-alive");
                    uc.setRequestProperty("Keep-Alive", "300");
                }

                connection = (HttpURLConnection) uc;
                connection.setReadTimeout(timeout);
                connection.setRequestMethod(method);
                HttpURLConnection.setFollowRedirects(false);
                connection.setDoInput(true);
                connection.setDoOutput(false);
            } else {
                // POST
                u = new URL(scheme + host + path);
                uc = u.openConnection();

                uc.setRequestProperty("Host", host);
                uc.setRequestProperty("Cookie", cookiesDone);
                if (xContentType == true) {
                    uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                }

                if (settings.asBrowser == 1) {
                    uc.setRequestProperty("Accept",
                            "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
                    // uc.setRequestProperty("Accept-Encoding", "gzip"); // not supported via cellular network
                    uc.setRequestProperty("Accept-Charset", "utf-8, iso-8859-1, utf-16, *;q=0.7");
                    uc.setRequestProperty("Accept-Language", "en-US");
                    uc.setRequestProperty("User-Agent", idBrowser);
                    uc.setRequestProperty("Connection", "keep-alive");
                    uc.setRequestProperty("Keep-Alive", "300");
                }

                connection = (HttpURLConnection) uc;
                connection.setReadTimeout(timeout);
                connection.setRequestMethod(method);
                HttpURLConnection.setFollowRedirects(false);
                connection.setDoInput(true);
                connection.setDoOutput(true);

                final OutputStream out = connection.getOutputStream();
                final OutputStreamWriter wr = new OutputStreamWriter(out);
                wr.write(params);
                wr.flush();
                wr.close();
            }

            String headerName = null;
            final SharedPreferences.Editor prefsEditor = prefs.edit();
            for (int j = 1; (headerName = uc.getHeaderFieldKey(j)) != null; j++) {
                if (headerName != null && headerName.equalsIgnoreCase("Set-Cookie")) {
                    int index;
                    String cookie = uc.getHeaderField(j);

                    index = cookie.indexOf(";");
                    if (index > -1) {
                        cookie = cookie.substring(0, cookie.indexOf(";"));
                    }

                    index = cookie.indexOf("=");
                    if (index > -1 && cookie.length() > (index + 1)) {
                        String name = cookie.substring(0, cookie.indexOf("="));
                        String value = cookie.substring(cookie.indexOf("=") + 1, cookie.length());

                        cookies.put(name, value);
                        prefsEditor.putString("cookie_" + name, value);
                    }
                }
            }
            prefsEditor.commit();

            final String encoding = connection.getContentEncoding();
            InputStream ins;

            if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
                ins = new GZIPInputStream(connection.getInputStream());
            } else if (encoding != null && encoding.equalsIgnoreCase("deflate")) {
                ins = new InflaterInputStream(connection.getInputStream(), new Inflater(true));
            } else {
                ins = connection.getInputStream();
            }
            final InputStreamReader inr = new InputStreamReader(ins);
            final BufferedReader br = new BufferedReader(inr);

            readIntoBuffer(br, buffer);

            httpCode = connection.getResponseCode();
            httpMessage = connection.getResponseMessage();
            httpLocation = uc.getHeaderField("Location");

            final String paramsLog = params.replaceAll(passMatch, "password=***");
            if (buffer != null && connection != null) {
                Log.i(cgSettings.tag + "|" + requestId,
                        "[" + method + " " + (int) (params.length() / 1024) + "k | " + httpCode + " | "
                                + (int) (buffer.length() / 1024) + "k] Downloaded " + scheme + host + path + "?"
                                + paramsLog);
            } else {
                Log.i(cgSettings.tag + "|" + requestId, "[" + method + " | " + httpCode
                        + "] Failed to download " + scheme + host + path + "?" + paramsLog);
            }

            connection.disconnect();
            br.close();
            ins.close();
            inr.close();
        } catch (IOException e) {
            Log.e(cgSettings.tag, "cgeoBase.request.IOException: " + e.toString());
        } catch (Exception e) {
            Log.e(cgSettings.tag, "cgeoBase.request: " + e.toString());
        }

        if (buffer != null && buffer.length() > 0) {
            break;
        }
    }

    cgResponse response = new cgResponse();
    String data = null;

    try {
        if (httpCode == 302 && httpLocation != null) {
            final Uri newLocation = Uri.parse(httpLocation);
            if (newLocation.isRelative() == true) {
                response = request(secure, host, path, "GET", new HashMap<String, String>(), requestId, false,
                        false, false);
            } else {
                boolean secureRedir = false;
                if (newLocation.getScheme().equals("https")) {
                    secureRedir = true;
                }
                response = request(secureRedir, newLocation.getHost(), newLocation.getPath(), "GET",
                        new HashMap<String, String>(), requestId, false, false, false);
            }
        } else {
            if (buffer != null && buffer.length() > 0) {
                data = replaceWhitespace(buffer);
                buffer = null;

                if (data != null) {
                    response.setData(data);
                } else {
                    response.setData("");
                }
                response.setStatusCode(httpCode);
                response.setStatusMessage(httpMessage);
                response.setUrl(u.toString());
            }
        }
    } catch (Exception e) {
        Log.e(cgSettings.tag, "cgeoBase.page: " + e.toString());
    }

    return response;
}

From source file:carnero.cgeo.original.libs.Base.java

public String requestJSON(String scheme, String host, String path, String method, String params) {
    int httpCode = -1;
    String httpLocation = null;/*from   ww w  . j a v  a2 s  .  c om*/

    if (method == null) {
        method = "GET";
    } else {
        method = method.toUpperCase();
    }

    boolean methodPost = false;
    if (method.equalsIgnoreCase("POST")) {
        methodPost = true;
    }

    URLConnection uc = null;
    HttpURLConnection connection = null;
    Integer timeout = 30000;
    final StringBuffer buffer = new StringBuffer();

    for (int i = 0; i < 3; i++) {
        if (i > 0) {
            Log.w(Settings.tag, "Failed to download data, retrying. Attempt #" + (i + 1));
        }

        buffer.delete(0, buffer.length());
        timeout = 30000 + (i * 15000);

        try {
            try {
                URL u = null;
                if (methodPost) {
                    u = new URL(scheme + host + path);
                } else {
                    u = new URL(scheme + host + path + "?" + params);
                }

                if (u.getProtocol().toLowerCase().equals("https")) {
                    trustAllHosts();
                    HttpsURLConnection https = (HttpsURLConnection) u.openConnection();
                    https.setHostnameVerifier(doNotVerify);
                    uc = https;
                } else {
                    uc = (HttpURLConnection) u.openConnection();
                }

                uc.setRequestProperty("Host", host);
                uc.setRequestProperty("Accept", "application/json, text/javascript, */*; q=0.01");
                if (methodPost) {
                    uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    uc.setRequestProperty("Content-Length", Integer.toString(params.length()));
                    uc.setRequestProperty("X-HTTP-Method-Override", "GET");
                } else {
                    uc.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
                }
                uc.setRequestProperty("X-Requested-With", "XMLHttpRequest");

                connection = (HttpURLConnection) uc;
                connection.setReadTimeout(timeout);
                connection.setRequestMethod(method);
                HttpURLConnection.setFollowRedirects(false); // TODO: Fix these (FilCab)
                connection.setDoInput(true);
                if (methodPost) {
                    connection.setDoOutput(true);

                    final OutputStream out = connection.getOutputStream();
                    final OutputStreamWriter wr = new OutputStreamWriter(out);
                    wr.write(params);
                    wr.flush();
                    wr.close();
                } else {
                    connection.setDoOutput(false);
                }

                final String encoding = connection.getContentEncoding();
                InputStream ins;

                if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
                    ins = new GZIPInputStream(connection.getInputStream());
                } else if (encoding != null && encoding.equalsIgnoreCase("deflate")) {
                    ins = new InflaterInputStream(connection.getInputStream(), new Inflater(true));
                } else {
                    ins = connection.getInputStream();
                }
                final InputStreamReader inr = new InputStreamReader(ins);
                final BufferedReader br = new BufferedReader(inr);

                readIntoBuffer(br, buffer);

                httpCode = connection.getResponseCode();

                final String paramsLog = params.replaceAll(passMatch, "password=***");
                Log.i(Settings.tag + " | JSON",
                        "[POST " + (int) (params.length() / 1024) + "k | " + httpCode + " | "
                                + (int) (buffer.length() / 1024) + "k] Downloaded " + "http://" + host + path
                                + "?" + paramsLog);

                connection.disconnect();
                br.close();
                ins.close();
                inr.close();
            } catch (IOException e) {
                httpCode = connection.getResponseCode();

                Log.e(Settings.tag, "cgeoBase.requestJSON.IOException: " + httpCode + ": "
                        + connection.getResponseMessage() + " ~ " + e.toString());
            }
        } catch (Exception e) {
            Log.e(Settings.tag, "cgeoBase.requestJSON: " + e.toString());
        }

        if (buffer != null && buffer.length() > 0) {
            break;
        }

        if (httpCode == 403) {
            // we're not allowed to download content, so let's move
            break;
        }
    }

    String page = null;
    if (httpCode == 302 && httpLocation != null) {
        final Uri newLocation = Uri.parse(httpLocation);
        if (newLocation.isRelative() == true) {
            page = requestJSONgc(host, path, params);
        } else {
            page = requestJSONgc(newLocation.getHost(), newLocation.getPath(), params);
        }
    } else {
        page = replaceWhitespace(buffer);
    }

    if (page != null) {
        return page;
    } else {
        return "";
    }
}

From source file:carnero.cgeo.cgBase.java

public String requestJSON(String scheme, String host, String path, String method, String params) {
    int httpCode = -1;
    String httpLocation = null;/*from ww w .j  a v  a2s .co m*/

    if (method == null) {
        method = "GET";
    } else {
        method = method.toUpperCase();
    }

    boolean methodPost = false;
    if (method.equalsIgnoreCase("POST")) {
        methodPost = true;
    }

    URLConnection uc = null;
    HttpURLConnection connection = null;
    Integer timeout = 30000;
    final StringBuffer buffer = new StringBuffer();

    for (int i = 0; i < 3; i++) {
        if (i > 0) {
            Log.w(cgSettings.tag, "Failed to download data, retrying. Attempt #" + (i + 1));
        }

        buffer.delete(0, buffer.length());
        timeout = 30000 + (i * 15000);

        try {
            try {
                URL u = null;
                if (methodPost) {
                    u = new URL(scheme + host + path);
                } else {
                    u = new URL(scheme + host + path + "?" + params);
                }

                if (u.getProtocol().toLowerCase().equals("https")) {
                    trustAllHosts();
                    HttpsURLConnection https = (HttpsURLConnection) u.openConnection();
                    https.setHostnameVerifier(doNotVerify);
                    uc = https;
                } else {
                    uc = (HttpURLConnection) u.openConnection();
                }

                uc.setRequestProperty("Host", host);
                uc.setRequestProperty("Accept", "application/json, text/javascript, */*; q=0.01");
                if (methodPost) {
                    uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    uc.setRequestProperty("Content-Length", Integer.toString(params.length()));
                    uc.setRequestProperty("X-HTTP-Method-Override", "GET");
                } else {
                    uc.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
                }
                uc.setRequestProperty("X-Requested-With", "XMLHttpRequest");

                connection = (HttpURLConnection) uc;
                connection.setReadTimeout(timeout);
                connection.setRequestMethod(method);
                HttpURLConnection.setFollowRedirects(false); // TODO: Fix these (FilCab)
                connection.setDoInput(true);
                if (methodPost) {
                    connection.setDoOutput(true);

                    final OutputStream out = connection.getOutputStream();
                    final OutputStreamWriter wr = new OutputStreamWriter(out);
                    wr.write(params);
                    wr.flush();
                    wr.close();
                } else {
                    connection.setDoOutput(false);
                }

                final String encoding = connection.getContentEncoding();
                InputStream ins;

                if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
                    ins = new GZIPInputStream(connection.getInputStream());
                } else if (encoding != null && encoding.equalsIgnoreCase("deflate")) {
                    ins = new InflaterInputStream(connection.getInputStream(), new Inflater(true));
                } else {
                    ins = connection.getInputStream();
                }
                final InputStreamReader inr = new InputStreamReader(ins);
                final BufferedReader br = new BufferedReader(inr);

                readIntoBuffer(br, buffer);

                httpCode = connection.getResponseCode();

                final String paramsLog = params.replaceAll(passMatch, "password=***");
                Log.i(cgSettings.tag + " | JSON",
                        "[POST " + (int) (params.length() / 1024) + "k | " + httpCode + " | "
                                + (int) (buffer.length() / 1024) + "k] Downloaded " + "http://" + host + path
                                + "?" + paramsLog);

                connection.disconnect();
                br.close();
                ins.close();
                inr.close();
            } catch (IOException e) {
                httpCode = connection.getResponseCode();

                Log.e(cgSettings.tag, "cgeoBase.requestJSON.IOException: " + httpCode + ": "
                        + connection.getResponseMessage() + " ~ " + e.toString());
            }
        } catch (Exception e) {
            Log.e(cgSettings.tag, "cgeoBase.requestJSON: " + e.toString());
        }

        if (buffer != null && buffer.length() > 0) {
            break;
        }

        if (httpCode == 403) {
            // we're not allowed to download content, so let's move
            break;
        }
    }

    String page = null;
    if (httpCode == 302 && httpLocation != null) {
        final Uri newLocation = Uri.parse(httpLocation);
        if (newLocation.isRelative() == true) {
            page = requestJSONgc(host, path, params);
        } else {
            page = requestJSONgc(newLocation.getHost(), newLocation.getPath(), params);
        }
    } else {
        page = replaceWhitespace(buffer);
    }

    if (page != null) {
        return page;
    } else {
        return "";
    }
}