Passing cookie to webview

转载:http://code.walletapp.net/post/46414301269/passing-cookie-to-webview

Passing cookie to webview

In few following lines I will describe my solution, how to pass cookies from DefaultHttpClient to WebView component. I was following many tutorials, but cookies weren’t send to WebView properly (in my Android 2.2). After several experiments I found out that it is working, when we wait a little time between removeSessionCookie and setCookie methods. I don’t know why. But important is, that it is working right now for me.

public class WebViewActivity extends Activity {

  WebView myWebView;
 private final static String TAG = "WebView";

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.webview);

    myWebView = (WebView) findViewById(R.id.webview);

            new WebViewTask().execute();
    }

    private class WebViewTask extends AsyncTask<Void, Void, Boolean> {
    String sessionCookie;
    CookieManager cookieManager;

        @Override
    protected void onPreExecute() {
        CookieSyncManager.createInstance(WebViewActivity.this);
        cookieManager = CookieManager.getInstance();

        sessionCookie = new PersistentConfig(getApplicationContext()).getCookieString();
        if (sessionCookie != null) {
                            /* delete old cookies */
            cookieManager.removeSessionCookie(); 
        }
        super.onPreExecute();
    }
    protected Boolean doInBackground(Void... param) {
                    /* this is very important - THIS IS THE HACK */
        SystemClock.sleep(1000);
        return false;
    }
    @Override
    protected void onPostExecute(Boolean result) {
        if (sessionCookie != null) {
            cookieManager.setCookie("yourdomain.com", sessionCookie);
            CookieSyncManager.getInstance().sync();
        }
        WebSettings webSettings = myWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setBuiltInZoomControls(true);
        myWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return super.shouldOverrideUrlLoading(view, url);
            }

        });
        myWebView.loadUrl("https://yourdomain.com/anything");
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值