Example usage for android.webkit CookieManager setCookie

List of usage examples for android.webkit CookieManager setCookie

Introduction

In this page you can find the example usage for android.webkit CookieManager setCookie.

Prototype

public abstract void setCookie(String url, String value);

Source Link

Document

Sets a cookie for the given URL.

Usage

From source file:com.drisoftie.cwdroid.frag.FragShoutbox.java

/**
 * Most actions are created here.//from  w  w w.  ja v a  2s  .c  o m
 */
@SuppressWarnings("unchecked")
private void initActions() {
    actionInit = new ActionBuilder().with().reg(IGenericAction.class, RegActionMethod.NONE)
            .pack(new AndroidAction<View, Void, Void, Void, Void>(null, null) {
                @Override
                public Object onActionPrepare(String methodName, Object[] methodArgs, Void tag1, Void tag2,
                        Object[] additionalTags) {
                    webShoutbox.loadUrl(getArguments().getString(FragShoutbox.class.getName()));

                    webShoutbox.getSettings().setUseWideViewPort(false);
                    webShoutbox.getSettings().setJavaScriptEnabled(true);

                    CookieManager cm = CookieManager.getInstance();
                    cm.setAcceptCookie(true);
                    if (CwApp.domain().isUserLoggedIn()) {
                        CwUser user = CwApp.domain().getLoggedInUser();

                        cm.setCookie(getString(R.string.cw_url_slash),
                                getString(R.string.cw_cookie_userid) + "=" + user.getId());
                        cm.setCookie(getString(R.string.cw_url_slash), getString(R.string.cw_cookie_pw) + "="
                                + CredentialUtils.deobfuscateFromBase64(user.getKeyData(), user.getPwHash()));
                        cm.setCookie(getString(R.string.cw_url_slash),
                                "cwbb_sessionhash" + "=" + "b71af138197a8c5443059316967d4");

                    }
                    skipWorkThreadOnce();
                    return null;
                }

                @Override
                public Void onActionDoWork(String methodName, Object[] methodArgs, Void tag1, Void tag2,
                        Object[] additionalTags) {
                    return null;
                }

                @Override
                public void onActionAfterWork(String methodName, Object[] methodArgs, Void result, Void tag1,
                        Void tag2, Object[] additionalTags) {
                }
            });

    actionRefresh = new ActionBuilder().with(swipeShoutbox)
            .reg(SwipeRefreshLayout.OnRefreshListener.class, "setOnRefreshListener")
            .reg(IGenericAction.class, RegActionMethod.NONE)
            .pack(new AndroidAction<View, List<CwNews>, List<CwNews>, Void, Void>(null, null) {
                @Override
                public Object onActionPrepare(String methodName, Object[] methodArgs, Void tag1, Void tag2,
                        Object[] additionalTags) {
                    webShoutbox.loadUrl(getArguments().getString(FragShoutbox.class.getName()));

                    CookieManager cm = CookieManager.getInstance();
                    cm.setAcceptCookie(true);
                    if (CwApp.domain().isUserLoggedIn()) {
                        CwUser user = CwApp.domain().getLoggedInUser();

                        cm.setCookie(getString(R.string.cw_url_slash),
                                getString(R.string.cw_cookie_userid) + "=" + user.getId());
                        cm.setCookie(getString(R.string.cw_url_slash), getString(R.string.cw_cookie_pw) + "="
                                + CredentialUtils.deobfuscateFromBase64(user.getKeyData(), user.getPwHash()));
                    }
                    skipWorkThreadOnce();
                    return null;
                }

                @Override
                public List<CwNews> onActionDoWork(String methodName, Object[] methodArgs, Void tag1, Void tag2,
                        Object[] additionalTags) {
                    return null;
                }

                @Override
                public void onActionAfterWork(String methodName, Object[] methodArgs, List<CwNews> result,
                        Void tag1, Void tag2, Object[] additionalTags) {
                }
            });
}

From source file:org.kotemaru.android.sample.webview.XMLHttpRequestXS.java

private void doRequest(String body) throws Throwable {
    try {/*from w  ww  .  j a  v  a 2  s  .  c  om*/
        if (POST.equals(_request.getMethod())) {
            HttpPost httpPost = (HttpPost) _request;
            Header header = httpPost.getFirstHeader(CONTENT_TYPE);
            String ctype = header != null ? header.getValue() : "plain/text; charset=" + HTTP.UTF_8;
            httpPost.setEntity(new StringEntity(body, ctype));
        }
        _response = _client.execute(_request);
        _responseCode = _response.getStatusLine().getStatusCode();

        CookieManager cookieManager = CookieManager.getInstance();
        Header[] cookies = _response.getHeaders("Set-Cookie");
        for (int i = 0; i < cookies.length; i++) {
            cookieManager.setCookie(_request.getURI().toString(), cookies[i].getValue());
        }

        if (Log.isLoggable(TAG, Log.DEBUG))
            debugLog();
    } catch (Throwable t) {
        Log.e(TAG, t.getMessage(), t);
        _request.abort();
        throw t;
    }
}

From source file:com.pindroid.fragment.ViewBookmarkFragment.java

private void showInWebView(String url) {
    String readingBackground = SettingsHelper.getReadingBackground(getActivity());
    String readingFont = SettingsHelper.getReadingFont(getActivity());
    String readingFontSize = SettingsHelper.getReadingFontSize(getActivity());
    String readingMargins = SettingsHelper.getReadingMargins(getActivity());

    mWebContent.loadUrl("about:blank");
    mWebContent.clearCache(true);//w  w  w.  j  a va  2  s  .c om

    CookieManager cookieManager = CookieManager.getInstance();
    CookieSyncManager.createInstance(getActivity());

    cookieManager.setAcceptCookie(true);
    cookieManager.setCookie("http://www.instapaper.com",
            "iptcolor=" + readingBackground + "; expires=Sat, 25-Mar-2023 00:00:00 GMT;path=/;");
    cookieManager.setCookie("http://www.instapaper.com",
            "iptfont=" + readingFont + "; expires=Sat, 25-Mar-2023 00:00:00 GMT;path=/;");
    cookieManager.setCookie("http://www.instapaper.com",
            "iptsize=" + readingFontSize + "; expires=Sat, 25-Mar-2023 00:00:00 GMT;path=/;");
    cookieManager.setCookie("http://www.instapaper.com",
            "iptwidth=" + readingMargins + "; expires=Sat, 25-Mar-2023 00:00:00 GMT;path=/;");

    CookieSyncManager.getInstance().sync();

    mWebContent.setWebViewClient(new WebViewClient() {
    });

    mWebContent.loadUrl(url);
}

From source file:at.ac.uniklu.mobile.sportal.WebViewActivity.java

@SuppressLint("SetJavaScriptEnabled")
@Override/*from   w w w . jav a 2 s. c  o  m*/
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    String targetUrl = getIntent().getStringExtra(URL);
    if (targetUrl == null || targetUrl.length() == 0) {
        // if there's no URL, close the activity
        finish();
    }

    setContentView(R.layout.webview);
    mActionBar = new ActionBarHelper(this).setupHeader().addActionRefresh();

    // set header title or hide header if no title is given
    String title = getIntent().getStringExtra(TITLE);
    if (title != null) {
        ((TextView) findViewById(R.id.view_title)).setText(title);
    } else {
        findViewById(R.id.actionbar).setVisibility(View.GONE);
    }

    // Moodle 2.0 uses SSO/CAS authentication
    mSSO = getIntent().getBooleanExtra(SSO, false);

    // the moodle hack is only needed until Android 2.3 (or maybe 3.x? - not tested)
    // Android 4.0 has the redirect history entry problem solved
    if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD_MR1) {
        mExecuteMoodleHack = getIntent().getBooleanExtra(MOODLE_HACK, false);
    }

    mWebView = (WebView) findViewById(R.id.web_view);
    //mWebView.setBackgroundColor(Color.BLACK); // black color messes up the CAS login page
    mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); // http://stackoverflow.com/questions/3998916/android-webview-leaves-space-for-scrollbar
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.getSettings().setLightTouchEnabled(true);
    mWebView.getSettings().setLoadWithOverviewMode(true);
    mWebView.getSettings().setBuiltInZoomControls(true);
    mWebView.getSettings().setUseWideViewPort(true);

    // setup custom webview client that shows a progress dialog while loading
    mWebView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.startsWith("https://sso.uni-klu.ac.at") || url.startsWith("https://sso.aau.at")
                    || url.startsWith("https://campus.aau.at") || url.startsWith("https://moodle.aau.at")) {
                return false;
            } else if (url.startsWith("http://campus-gis.aau.at/")) {
                Log.d(TAG, "REDIRECT TO MAP");
                String roomParameter = "curRouteTo=";
                int index = url.indexOf(roomParameter);
                if (index > -1) {
                    MapUtils.openMapAndShowRoom(WebViewActivity.this,
                            url.substring(index + roomParameter.length()));
                }
                return true;
            }

            // open external websites in browser
            Intent i = new Intent(Intent.ACTION_VIEW);
            i.setData(Uri.parse(url));
            startActivity(i);
            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            progressNotificationOn();
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            progressNotificationOff();
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            progressNotificationOff();

            /*
             *  the first page of moodle opens through a redirect so we need to clear the first history
             *  entry to avoid execution of the redirect when going back through the history with the back button
             */
            if (mExecuteMoodleHack && mWebView.canGoBack()) {
                mWebView.clearHistory();
                mExecuteMoodleHack = false;
            } else {
                mIsFirstPage = false;
            }
        }
    });

    mWebView.setDownloadListener(new DownloadListener() {
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype,
                long contentLength) {
            Analytics.onEvent(Analytics.EVENT_WEB_COURSEMOODLE_DOWNLOAD);
            Uri uri = Uri.parse(url);
            MoodleDownloadHelper.download(WebViewActivity.this, uri,
                    Utils.getContentDispositionOrUrlFilename(contentDisposition, uri));
        }
    });

    // set session cookie
    // http://stackoverflow.com/questions/1652850/android-webview-cookie-problem
    // http://android.joao.jp/2010/11/cookiemanager-and-removeallcookie.html
    if (Studentportal.getSportalClient().isSessionCookieAvailable()) {
        CookieSyncManager.createInstance(this);
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        //cookieManager.removeSessionCookie(); // NOTE when calling this method the cookies get removed after the next setCookie() gets called

        Cookie sessionCookie = Studentportal.getSportalClient().getSessionCookie();
        cookieManager.setCookie(sessionCookie.getDomain(), Utils.cookieHeaderString(sessionCookie));

        if (mSSO) {
            // set SSO/CAS cookie
            Cookie ssoCookie = Studentportal.getSportalClient().getCookie("CASTGC");
            if (ssoCookie != null) {
                cookieManager.setCookie(ssoCookie.getDomain(), Utils.cookieHeaderString(ssoCookie));
            }
        }

        CookieSyncManager.getInstance().sync();
    }

    mIsFirstPage = true;
    mWebView.loadUrl(targetUrl);
}

From source file:ti.modules.titanium.network.NetworkModule.java

/**
 * Removes the cookie with the domain, path and name exactly the same as the given values.
 * @param domain the domain of the cookie to remove. It is case-insensitive.
 * @param path the path of the cookie to remove. It is case-sensitive.
 * @param name the name of the cookie to remove. It is case-sensitive.
 *///w w  w. j  av  a2s  .  c o m
@Kroll.method
public void removeSystemCookie(String domain, String path, String name) {
    if (domain == null || name == null) {
        if (Log.isDebugModeEnabled()) {
            Log.e(TAG, "Unable to remove the system cookie. Need to provide a valid domain / name.");
        }
        return;
    }
    String lower_domain = domain.toLowerCase();
    String cookieString = name + "=; domain=" + lower_domain + "; path=" + path + "; expires="
            + CookieProxy.systemExpiryDateFormatter.format(new Date(0));
    CookieSyncManager.createInstance(TiApplication.getInstance().getRootOrCurrentActivity());
    CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.setCookie(lower_domain, cookieString);
    CookieSyncManager.getInstance().sync();
}

From source file:ti.modules.titanium.network.NetworkModule.java

/**
 * Adds a cookie to the system cookie store. Any existing cookie with the same domain, path and name will be replaced with
 * the new cookie. The cookie being set must not have expired, otherwise it will be ignored.
 * @param cookieProxy the cookie to add//from ww w . j a v a  2  s.c o m
 */
@Kroll.method
public void addSystemCookie(CookieProxy cookieProxy) {
    BasicClientCookie cookie = cookieProxy.getHTTPCookie();
    String cookieString = cookie.getName() + "=" + cookie.getValue();
    String domain = cookie.getDomain();
    if (domain == null) {
        Log.w(TAG, "Unable to add system cookie. Need to provide domain.");
        return;
    }
    cookieString += "; domain=" + domain;

    String path = cookie.getPath();
    Date expiryDate = cookie.getExpiryDate();
    boolean secure = cookie.isSecure();
    boolean httponly = TiConvert.toBoolean(cookieProxy.getProperty(TiC.PROPERTY_HTTP_ONLY), false);
    if (path != null) {
        cookieString += "; path=" + path;
    }
    if (expiryDate != null) {
        cookieString += "; expires=" + CookieProxy.systemExpiryDateFormatter.format(expiryDate);
    }
    if (secure) {
        cookieString += "; secure";
    }
    if (httponly) {
        cookieString += " httponly";
    }
    CookieSyncManager.createInstance(TiApplication.getInstance().getRootOrCurrentActivity());
    CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.setCookie(domain, cookieString);
    CookieSyncManager.getInstance().sync();
}

From source file:biz.varkon.shelvesom.util.CookieStore.java

public String getCookie(String url) {
    final CookieManager cookieManager = CookieManager.getInstance();
    String cookie = cookieManager.getCookie(url);

    if (cookie == null || cookie.length() == 0) {
        final HttpHead head = new HttpHead(url);
        HttpEntity entity = null;/* ww  w.  j  a va2s.c om*/
        try {
            final HttpResponse response = HttpManager.execute(head);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                entity = response.getEntity();

                final Header[] cookies = response.getHeaders("set-cookie");
                for (Header cooky : cookies) {
                    cookieManager.setCookie(url, cooky.getValue());
                }

                CookieSyncManager.getInstance().sync();
                cookie = cookieManager.getCookie(url);
            }
        } catch (IOException e) {
            Log.e(LOG_TAG, "Could not retrieve cookie", e);
        } finally {
            if (entity != null) {
                try {
                    entity.consumeContent();
                } catch (IOException e) {
                    Log.e(LOG_TAG, "Could not retrieve cookie", e);
                }
            }
        }
    }

    return cookie;
}

From source file:org.sufficientlysecure.keychain.ui.linked.LinkedIdCreateGithubFragment.java

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    if (savedInstanceState != null) {
        String cookie = savedInstanceState.getString(ARG_GITHUB_COOKIE);
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setCookie("https://github.com/", cookie);
    }//from   www . j  a  v  a2s.c o m
}

From source file:com.directsiding.android.WebActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
    setContentView(R.layout.activity_web);

    // Le ponemos la font Signika al titulo del Action Bar
    SpannableString s = new SpannableString(getString(R.string.app_name));
    s.setSpan(new TypefaceSpan(this, LoginActivity.PATH_SIGNIKA_FONT), 0, s.length(),
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

    // Agregamos lo necesario al Action Bar
    ActionBar actionBar = getSupportActionBar();
    actionBar.setTitle(s);/*from   w  w w .  j  av a2s .com*/
    actionBar.setDisplayShowHomeEnabled(true);
    actionBar.setHomeButtonEnabled(true);

    // Obtenemos la url a la que el usuario va a ingresar
    String url = getIntent().getExtras().getString(LoginActivity.EXTRA_URL);

    // Obtenemos la cookie y la agregamos al webview
    Cookie sessionCookie = LoginOpActivity.cookie;
    CookieSyncManager.createInstance(this);
    CookieManager cookieManager = CookieManager.getInstance();
    if (sessionCookie != null) {
        //cookieManager.removeSessionCookie();
        String cookieString = sessionCookie.getName() + "=" + sessionCookie.getValue() + "; domain="
                + sessionCookie.getDomain();
        cookieManager.setCookie(LoginActivity.POST_URL, cookieString);
        CookieSyncManager.getInstance().sync();
    }

    mProgressBar = (ProgressBar) findViewById(R.id.progressBar_webView);
    webView = (WebView) findViewById(R.id.webView_ing);

    webViewConfig();
    webView.loadUrl(url);
    //webView.loadUrl("http://www.google.com");

    // guardamos el tiempo en el que se creo la actividad
    lastTimeStamp = SystemClock.elapsedRealtime();

}

From source file:net.niyonkuru.koodroid.service.SessionService.java

/**
 * Save cookies for later use by a {@link WebView}
 *//*from w  ww .ja va  2s .  c o m*/
private void saveCookies() {
    List<Cookie> cookies = mHttpClient.getCookieStore().getCookies();
    if (cookies.isEmpty())
        return;

    CookieSyncManager.createInstance(this);
    CookieManager cookieManager = CookieManager.getInstance();

    for (Cookie cookie : cookies) {
        String url = (cookie.isSecure() ? "https://" : "http://") + Config.DOMAIN + cookie.getPath();

        String value = cookie.getName() + "=" + cookie.getValue();

        if (cookie.getDomain().startsWith(".")) {
            value += "; domain=" + cookie.getDomain();
        }

        cookieManager.setCookie(url, value);
    }
}