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:net.nym.mutils.ui.test.TestWebViewActivity.java

/**
 * ?cookie//from  w  ww.j  a  v a 2  s.  c om
 */
@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.suning.mobile.ebuy.lottery.network.util.Caller.java

/**
 * webviewcookie/*from  ww w .  j  a  va 2 s. c  om*/
 */
public void syncCookie() {
    List<Cookie> cookies = mClient.getCookieStore().getCookies();
    if (!cookies.isEmpty()) {
        CookieSyncManager cookieSyncManager = CookieSyncManager.createInstance(mApplication);
        CookieManager cookieManager = CookieManager.getInstance();
        for (Cookie cookie : cookies) {
            String domain = cookie.getDomain();
            String strCookies = cookie.getName() + "=" + cookie.getValue() + "; domain=" + domain;
            cookieManager.setCookie(domain, strCookies);
            cookieSyncManager.sync();
        }
    }
}

From source file:mgks.os.webview.MainActivity.java

public void get_info() {
    CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.setAcceptCookie(true);
    cookieManager.setCookie(ASWV_URL, "DEVICE=android");
    cookieManager.setCookie(ASWV_URL, "DEV_API=" + Build.VERSION.SDK_INT);
}

From source file:com.liato.bankdroid.WebViewActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.webview);/*  w  ww. jav  a 2  s .  c o m*/
    this.addTitleButton(R.drawable.title_icon_back, "back", this);
    this.addTitleButton(R.drawable.title_icon_forward, "forward", this);
    this.addTitleButton(R.drawable.title_icon_refresh, "refresh", this);
    this.setTitleButtonEnabled("forward", false);
    this.setTitleButtonEnabled("back", false);
    this.setTitleButtonEnabled("refresh", false);

    final CookieSyncManager csm = CookieSyncManager.createInstance(this);
    mWebView = (WebView) findViewById(R.id.wvBank);
    mWebView.setBackgroundColor(0);
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.getSettings().setBuiltInZoomControls(true);
    mWebView.getSettings().setUserAgentString(Urllib.DEFAULT_USER_AGENT);
    mWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);

    mWebView.setWebChromeClient(new WebChromeClient() {
        public void onProgressChanged(WebView view, int progress) {
            activity.setProgressBar(progress);
            if (progress == 100) {
                Handler handler = new Handler();
                Runnable runnable = new Runnable() {
                    public void run() {
                        activity.hideProgressBar();
                    }
                };
                // Let the progress bar hit 100% before we hide it.
                handler.postDelayed(runnable, 100);

            } else if (mFirstPageLoaded) {
                activity.showProgressBar();
            }
        }
    });
    mWebView.setWebViewClient(new BankWebViewClient());
    String preloader = "Error...";
    try {
        preloader = IOUtils.toString(getResources().openRawResource(R.raw.loading));
        preloader = String.format(preloader, "", // Javascript function
                "" // HTML
        );
    } catch (NotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    mWebView.loadDataWithBaseURL("what://is/this/i/dont/even", preloader, "text/html", "utf-8", null);

    Bundle extras = getIntent().getExtras();
    final long bankId = extras.getLong("bankid", -1);
    //final long bankId = -1;
    if (bankId >= 0) {
        Runnable generateLoginPage = new Runnable() {
            public void run() {
                Bank bank = BankFactory.bankFromDb(bankId, WebViewActivity.this, false);
                SessionPackage loginPackage = bank.getSessionPackage(WebViewActivity.this);
                CookieStore cookieStore = loginPackage.getCookiestore();
                if ((cookieStore != null) && !cookieStore.getCookies().isEmpty()) {
                    CookieManager cookieManager = CookieManager.getInstance();
                    String cookieString;
                    for (Cookie cookie : cookieStore.getCookies()) {
                        cookieString = String.format("%s=%s;%spath=%s; domain=%s;", cookie.getName(),
                                cookie.getValue(),
                                cookie.getExpiryDate() == null ? ""
                                        : "expires=" + cookie.getExpiryDate() + "; ",
                                cookie.getPath() == null ? "/" : cookie.getPath(), cookie.getDomain());
                        cookieManager.setCookie(cookie.getDomain(), cookieString);
                    }
                    csm.sync();
                }
                mWebView.loadDataWithBaseURL("what://is/this/i/dont/even", loginPackage.getHtml(), "text/html",
                        "utf-8", null);
            }
        };
        new Thread(generateLoginPage).start();
    }
}

From source file:mgks.os.webview.MainActivity.java

public String get_location() {
    String newloc = "0,0";
    //Checking for location permissions
    if (ASWP_LOCATION && (Build.VERSION.SDK_INT < 23 || check_permission(1))) {
        GPSTrack gps;/*  w w  w .  ja  v a2s. c  o m*/
        gps = new GPSTrack(MainActivity.this);
        double latitude = gps.getLatitude();
        double longitude = gps.getLongitude();
        if (gps.canGetLocation()) {
            if (latitude != 0 || longitude != 0) {
                if (!ASWP_OFFLINE) {
                    CookieManager cookieManager = CookieManager.getInstance();
                    cookieManager.setAcceptCookie(true);
                    cookieManager.setCookie(ASWV_URL, "lat=" + latitude);
                    cookieManager.setCookie(ASWV_URL, "long=" + longitude);
                }
                //Log.w("New Updated Location:", latitude + "," + longitude);  //enable to test dummy latitude and longitude
                newloc = latitude + "," + longitude;
            } else {
                Log.w("New Updated Location:", "NULL");
            }
        } else {
            show_notification(1, 1);
            Log.w("New Updated Location:", "FAIL");
        }
    }
    return newloc;
}

From source file:de.trier.infsec.koch.droidsheep.activities.HijackActivity.java

private void setupCookies() {
    Log.i(APPLICATION_TAG, "######################## COOKIE SETUP ###############################");
    CookieManager manager = CookieManager.getInstance();
    Log.i(APPLICATION_TAG, "Cookiemanager has cookies: " + (manager.hasCookies() ? "YES" : "NO"));
    if (manager.hasCookies()) {
        manager.removeAllCookie();//from www .  ja v a  2 s  .c  om
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
        }
        Log.i(APPLICATION_TAG, "Cookiemanager has still cookies: " + (manager.hasCookies() ? "YES" : "NO"));
    }
    Log.i(APPLICATION_TAG, "######################## COOKIE SETUP START ###############################");
    for (CookieWrapper cookieWrapper : authToHijack.getCookies()) {
        Cookie cookie = cookieWrapper.getCookie();
        String cookieString = cookie.getName() + "=" + cookie.getValue() + "; domain=" + cookie.getDomain()
                + "; Path=" + cookie.getPath();
        Log.i(APPLICATION_TAG, "Setting up cookie: " + cookieString);
        manager.setCookie(cookie.getDomain(), cookieString);
    }
    CookieSyncManager.getInstance().sync();
    Log.i(APPLICATION_TAG, "######################## COOKIE SETUP DONE ###############################");
}

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

/**
 * Most actions are created here./*from ww w .j  ava2s  .  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) {
                    webBoard.loadUrl(getArguments().getString(FragBoard.class.getName()));

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

                    CookieManager cm = CookieManager.getInstance();
                    if (!CwApp.domain().isUserLoggedIn()) {
                        cm.removeAllCookie();
                    } else {
                        CwUser user = CwApp.domain().getLoggedInUser();
                        String cookie = cm.getCookie(getString(R.string.api_domain));
                        if (StringUtils.contains(cookie, getString(R.string.cw_cookie_userid))
                                && StringUtils.contains(cookie,
                                        getString(R.string.cw_cookie_userid) + "=" + user.getId())
                                && cookie.contains(getString(R.string.cw_cookie_pw) + "=" + CredentialUtils
                                        .deobfuscateFromBase64(user.getKeyData(), user.getPwHash()))) {
                        } else {
                            cm.removeAllCookie();
                            cm.setCookie(getString(R.string.api_domain),
                                    getString(R.string.cw_cookie_userid) + "=" + user.getId());
                            cm.setCookie(getString(R.string.api_domain),
                                    getString(R.string.cw_cookie_pw) + "=" + CredentialUtils
                                            .deobfuscateFromBase64(user.getKeyData(), user.getPwHash()));
                        }
                    }
                    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(swipeBoard)
            .reg(SwipeRefreshLayout.OnRefreshListener.class, "setOnRefreshListener")
            .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) {
                    webBoard.loadUrl(getArguments().getString(FragShoutbox.class.getName()));
                    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) {
                }
            });
}

From source file:com.zbrown.droidsteal.activities.HijackActivity.java

private void setupCookies() {
    Log.i(APPLICATION_TAG, "######################## COOKIE SETUP ###############################");
    CookieManager manager = CookieManager.getInstance();
    Log.i(APPLICATION_TAG, "Cookiemanager has cookies: " + (manager.hasCookies() ? "YES" : "NO"));
    if (manager.hasCookies()) {
        manager.removeAllCookie();//from w  w w  . j  a v  a  2  s .  com
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            Log.e(APPLICATION_TAG, "Error with Thread.sleep(3000)", e);
        }
        Log.i(APPLICATION_TAG, "Cookiemanager has still cookies: " + (manager.hasCookies() ? "YES" : "NO"));
    }
    Log.i(APPLICATION_TAG, "######################## COOKIE SETUP START ###############################");
    for (CookieWrapper cookieWrapper : authToHijack.getCookies()) {
        Cookie cookie = cookieWrapper.getCookie();
        String cookieString = cookie.getName() + "=" + cookie.getValue() + "; domain=" + cookie.getDomain()
                + "; Path=" + cookie.getPath();
        Log.i(APPLICATION_TAG, "Setting up cookie: " + cookieString);
        manager.setCookie(cookie.getDomain(), cookieString);
    }
    CookieSyncManager.getInstance().sync();
    Log.i(APPLICATION_TAG, "######################## COOKIE SETUP DONE ###############################");
}

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 {/*from  www. ja  va2s  .c  o m*/
        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);
}