Example usage for android.webkit CookieManager setAcceptCookie

List of usage examples for android.webkit CookieManager setAcceptCookie

Introduction

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

Prototype

public abstract void setAcceptCookie(boolean accept);

Source Link

Document

Sets whether the application's WebView instances should send and accept cookies.

Usage

From source file:com.nguyenmp.gauchodroid.login.LoginFragment.java

public static void setCookies(Context context, CookieStore cookies) {
    PersistentCookieStore store = new PersistentCookieStore(context);
    store.clear();/* www.  j av  a  2s .  co  m*/

    CookieSyncManager.createInstance(context);
    CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.removeAllCookie();
    cookieManager.setAcceptCookie(true);

    if (cookies != null) {
        for (Cookie cookie : cookies.getCookies()) {
            store.addCookie(cookie);
            cookieManager.setCookie(cookie.getDomain(), cookie.getName() + "=" + cookie.getValue());
        }
    }

    CookieSyncManager.getInstance().sync();
}

From source file:thiru.in.basicauthwebview.ShowWebViewActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_show_web_view);

    // Initialize the Cookie Manager
    CookieSyncManager.createInstance(this);
    CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.setAcceptCookie(true);

    String url = "http://auth.thiru.in/";
    // Call the REST Service to Authenticate
    // This is sample app, the app can have a login form, accept input, encode the
    // id and passowrd using Base64 for Validating
    AsyncTask<String, Void, CookieStore> cookieStoreTask = new Authenticate(this).execute(url + "app-auth",
            "ZGVtbzpkZW1v"); //Base64 Encoded for demo:demo

    try {//w  ww .jav  a2 s  .com
        cookieManager.removeAllCookie();
        CookieStore cookieStore = cookieStoreTask.get();
        List<Cookie> cookies = cookieStore.getCookies();
        // If the User id and password is wrong, the cookie store will not have any cookies
        // And the page will display 403 Access Denied
        for (Cookie cookie : cookies) {
            Log.i("Cookie", cookie.getName() + " ==> " + cookie.getValue());
            // Add the REST Service Cookie Responses to Cookie Manager to make it
            // Available for the WebViewClient
            cookieManager.setCookie(url, cookie.getName() + "=" + cookie.getValue());
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }

    mWebView = (WebView) findViewById(R.id.activity_main_webview);
    mWebView.setWebViewClient(new WebViewClient());
    mWebView.loadUrl(url);
}

From source file:org.forgerock.openam.mobile.example.oauth2.activities.webview.AuthorizeWebClient.java

/**
 * Used to append our authentication cookie to the authorization request
 *
 * @param name name of the cookie//from  w  ww  .ja va 2s .  c o m
 * @param value value of the cookie
 * @param domain domain in which the cookie applies
 * @param url url to register the cookie against in the cookie manager
 */
public void insertCookie(String name, String value, String domain, String url) {
    StringBuilder cookie = new StringBuilder(name);
    cookie.append("=").append(value);
    cookie.append("; domain=").append(domain);
    cookie.append("; path=/");

    CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.setAcceptCookie(true);
    cookieManager.setCookie(url, cookie.toString());
}

From source file:net.nym.mutils.ui.test.TestWebViewActivity.java

/**
 * ?cookie/*from w w w .jav a2  s.c o m*/
 */
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
protected void synCookies(Context context, String url) {
    // ??URI
    URL uri = null;
    try {
        uri = new URL(url);
    } catch (MalformedURLException e) {
        try {
            // ?
            uri = new URL(MethodNames.HOST_ADDRESS);
        } catch (MalformedURLException e1) {
            return;
        }
    }

    CookieManager cookieManager = CookieManager.getInstance();
    // cookieManager.removeAllCookie();
    cookieManager.setAcceptCookie(true);
    PersistentCookieStore cookieStore = new PersistentCookieStore(this);
    if (null != cookieStore) {
        List<Cookie> cookies = cookieStore.getCookies();
        for (Cookie c : cookies) {
            if (!StringUtils.isNullOrEmpty(c.getName()) && !StringUtils.isNullOrEmpty(c.getValue())) {
                // cookiesHttpClientcookie
                StringBuilder cookie = new StringBuilder(c.getName() + "=" + c.getValue());
                cookieManager.setCookie(uri.getHost(), cookie.toString());//
            }
        }
    }
    if (!ContextUtils.isLollipopOrLater()) {

        CookieSyncManager.getInstance().sync();
    } else {
        cookieManager.flush();
    }

}

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

/**
 * Most actions are created here.//from w  w  w  . j a  v a 2 s.  c om
 */
@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:com.cerema.cloud2.ui.dialog.SamlWebViewDialog.java

@SuppressWarnings("deprecation")
@SuppressLint("SetJavaScriptEnabled")
@Override//ww  w.j av  a  2  s .c o  m
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    Log_OC.v(TAG, "onCreateView, savedInsanceState is " + savedInstanceState);

    // Inflate layout of the dialog  
    RelativeLayout ssoRootView = (RelativeLayout) inflater.inflate(R.layout.sso_dialog, container, false); // null parent view because it will go in the dialog layout

    if (mSsoWebView == null) {
        // initialize the WebView
        mSsoWebView = new SsoWebView(getActivity().getApplicationContext());
        mSsoWebView.setFocusable(true);
        mSsoWebView.setFocusableInTouchMode(true);
        mSsoWebView.setClickable(true);

        WebSettings webSettings = mSsoWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setBuiltInZoomControls(false);
        webSettings.setLoadWithOverviewMode(false);
        webSettings.setSavePassword(false);
        webSettings.setUserAgentString(MainApp.getUserAgent());
        webSettings.setSaveFormData(false);

        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        cookieManager.removeAllCookie();

        mSsoWebView.loadUrl(mInitialUrl);
    }

    mWebViewClient.setTargetUrl(mTargetUrl);
    mSsoWebView.setWebViewClient(mWebViewClient);

    // add the webview into the layout
    RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    ssoRootView.addView(mSsoWebView, layoutParams);
    ssoRootView.requestLayout();

    return ssoRootView;
}

From source file:com.digitalarx.android.ui.dialog.SamlWebViewDialog.java

@SuppressWarnings("deprecation")
@SuppressLint("SetJavaScriptEnabled")
@Override/*  ww  w .ja  v  a  2 s .c om*/
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    Log_OC.d(TAG, "onCreateView, savedInsanceState is " + savedInstanceState);

    // Inflate layout of the dialog  
    RelativeLayout ssoRootView = (RelativeLayout) inflater.inflate(R.layout.sso_dialog, container, false); // null parent view because it will go in the dialog layout

    if (mSsoWebView == null) {
        // initialize the WebView
        mSsoWebView = new SsoWebView(getSherlockActivity().getApplicationContext());
        mSsoWebView.setFocusable(true);
        mSsoWebView.setFocusableInTouchMode(true);
        mSsoWebView.setClickable(true);

        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        cookieManager.removeAllCookie();
        mSsoWebView.loadUrl(mInitialUrl);

        WebSettings webSettings = mSsoWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setBuiltInZoomControls(false);
        webSettings.setLoadWithOverviewMode(false);
        webSettings.setSavePassword(false);
        webSettings.setUserAgentString(OwnCloudClient.USER_AGENT);
        webSettings.setSaveFormData(false);
    }

    mWebViewClient.setTargetUrl(mTargetUrl);
    mSsoWebView.setWebViewClient(mWebViewClient);

    // add the webview into the layout
    RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    ssoRootView.addView(mSsoWebView, layoutParams);
    ssoRootView.requestLayout();

    return ssoRootView;
}

From source file:com.owncloud.android.ui.dialog.LoginWebViewDialog.java

@SuppressWarnings("deprecation")
@SuppressLint("SetJavaScriptEnabled")
@Override//from   ww  w.  j  ava  2  s .  c  o  m
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    Log_OC.v(TAG, "onCreateView, savedInsanceState is " + savedInstanceState);

    // Inflate layout of the dialog  
    RelativeLayout ssoRootView = (RelativeLayout) inflater.inflate(R.layout.webview_dialog, container, false); // null parent view because it will go in the dialog layout

    if (mWebView == null) {
        // initialize the WebView
        mWebView = new SsoWebView(getActivity().getApplicationContext());
        mWebView.setFocusable(true);
        mWebView.setFocusableInTouchMode(true);
        mWebView.setClickable(true);

        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setSavePassword(false);
        webSettings.setUserAgentString(MainApp.getUserAgent());
        webSettings.setSaveFormData(false);
        // next two settings grant that non-responsive webs are zoomed out when loaded
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        // next three settings allow the user use pinch gesture to zoom in / out
        webSettings.setSupportZoom(true);
        webSettings.setBuiltInZoomControls(true);
        webSettings.setDisplayZoomControls(false);
        webSettings.setAllowFileAccess(false);

        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        cookieManager.removeAllCookie();

        mWebView.loadUrl(mInitialUrl);
    }

    mWebViewClient.addTargetUrls(mTargetUrls);
    mWebView.setWebViewClient(mWebViewClient);

    // add the webview into the layout
    RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
    ssoRootView.addView(mWebView, layoutParams);
    ssoRootView.requestLayout();

    return ssoRootView;
}

From source file:com.tdispatch.passenger.fragment.OAuthFragment.java

@SuppressLint("SetJavaScriptEnabled")
@Override/* ww w  .j  a  va  2s  .  co m*/
protected void onPostCreateView() {

    View v = mFragmentView.findViewById(R.id.button_cancel);
    v.setOnClickListener(mOnClickListener);

    ProgressBar pb = (ProgressBar) mFragmentView.findViewById(R.id.progressbar);
    pb.setVisibility(View.GONE);

    mWebView = (WebView) mFragmentView.findViewById(R.id.webview);
    if (mWebView != null) {

        mWebView.setWebViewClient(new MyWebViewClient());
        mWebView.setWebChromeClient(new MyWebchromeClient());

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
            mWebView.setOnTouchListener(mOnTouchListener);
        }

        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSettings.setAppCacheEnabled(false);
        webSettings.setSavePassword(false);
        webSettings.setSaveFormData(false);

        CookieSyncManager.createInstance(mContext);
        CookieManager cm = CookieManager.getInstance();
        cm.setAcceptCookie(true);
        cm.removeAllCookie();

        try {
            ApiRequest req = new ApiRequest(Const.Api.OauthAuthUrl);
            req.addGetParam("key", Const.getApiKey());
            req.addGetParam("scope", "");
            req.addGetParam("response_type", "code");
            req.addGetParam("client_id", Const.getOAuthClientId());
            req.addGetParam("redirect_uri", mOAuthRedirectUrl);
            req.buildRequest();

            String url = req.getUrl();

            mWebView.loadUrl(url);

        } catch (Exception e) {
            WebnetLog.e("Failed to load oauth launch page...");
        }

    } else {
        WebnetLog.e("Failed to init WebView. Aborting");
        mHostActivity.oAuthCancelled();
    }
}

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

@SuppressLint("SetJavaScriptEnabled")
@Override//from  w  ww  .j av  a 2 s . c om
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);
}