如何在Android WebView客户端设置cookie

bprjcwpo  于 2023-02-20  发布在  Android
关注(0)|答案(4)|浏览(329)

我想通过WebView调用一个特定的url,这个页面只有用户登录后才能调用,我使用AsyncHttpClient库进行登录调用,一旦成功登录后,通过WebView加载URL似乎无法识别正确的标题,尤其是cookie。我怀疑cookie在HttpClientWebView的HttpClient之间没有正确同步。知道为什么吗?下面是我如何使用WebView

final WebView webView = (WebView) content.findViewById(R.id.web_travel_advisory);
    String url = "http://mydomainurl.com/get_data_after_login";

    webView.setWebViewClient(new WebViewClient());

    CookieSyncManager.createInstance(getActivity());
    CookieSyncManager.getInstance().startSync();
    CookieManager.getInstance().setAcceptCookie(true);

    webView.getSettings().setJavaScriptEnabled(true);

    webView.loadUrl(url);

谢谢你的帮助。

a2mppw5e

a2mppw5e1#

哦,几个小时后,我终于弄明白了它的工作原理。首先,根据文档,CookieSyncManager自API 21以来在更高版本的android上被弃用。所以决定不再使用它。其次,CookieManager用于存储WebView的cookie。

最终代码

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

    List<Cookie> cookies = WSHelper.cookieStore.getCookies();

    cookieManager.removeAllCookie();

    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookie.getName().contains("session")){
                String cookieString = cookie.getName() + "=" + cookie.getValue() + "; Domain=" + cookie.getDomain();
                cookieManager.setCookie(cookie.getDomain(), cookieString);
                Log.d("CookieUrl",cookieString + " ");
            }
        }
    }
    webView.loadUrl(url);

解决方案的关键变更是:使用**cookie.getDomain()**代替显式域。

cookieManager.setCookie(cookie.getDomain(), cookieString);
brccelvz

brccelvz2#

尝试这个代码,经过几个变化为我工作:

public class WebViewActivity extends Activity{
    private SharedPreferences mPreferences;

    String token="";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.webviewpage);

        mPreferences = getSharedPreferences("CurrentUser", MODE_PRIVATE);

    }

    public void LaunchWebView(View view) {

        WebView myWebView = (WebView) findViewById(R.id.myWebView);
        myWebView.getSettings().setJavaScriptEnabled(true);
        myWebView.getSettings().setSaveFormData(false);

        CookieSyncManager.createInstance(this);
        CookieSyncManager.getInstance().startSync();
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        CookieManager.getInstance().setAcceptThirdPartyCookies(myWebView, true);

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        String token2= mPreferences.getString("auth_token","");

        HashMap<String, String> map = new HashMap<String, String>();
        map.put("x-auth-token", token);

        myWebView.getSettings().setAppCacheEnabled(true);
        myWebView.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view,String url) {
                view.loadUrl(url);
                return true;
            }
        });
        myWebView.loadUrl("YOUR_URL", map);
    }
}
kdfy810k

kdfy810k3#

我的问题略有不同,但@Tixeon的回答给了我解决问题的关键。我正在编写我的Cookie并将其添加到WebView请求中,但我发现Android正在覆盖我的Cookie并发送自己的Cookie。因此,首先,我必须从数组中删除所有Cookie,然后编写自己的Cookie。以下是示例代码:

// Note that my project has minSdkVersion 21, so I can directly use methods only available in Lollipop
private fun loadUrlInWebView(url: String) {
    webView.settings.apply {
        builtInZoomControls = false
        javaScriptEnabled = true
        useWideViewPort = true
        loadWithOverviewMode = true
        setSupportMultipleWindows(false)
    }
    CookieManager.getInstance().apply {
        setAcceptThirdPartyCookies(webView, true) // My minSdkVersion is 21
        removeAllCookies { value ->
            Log.d("Cookies", "Removed all cookies from CookieManager")
        }
    }

    webView.apply {
        isVerticalScrollBarEnabled = true
        isHorizontalScrollBarEnabled = true
        loadUrl(
            url,
            mutableMapOf(
                "Cookie" to "ThisIsMyCookieWithMyValues",
                "Accept" to "*/*",
                "Accept-Encoding" to "gzip, deflate",
                "Cache-Control" to "no-cache",
                "Content-type" to "application/x-www-form-urlencoded"
            )
        )
    }
}

现在请求中包含了我的Cookie,而不是Android提供的默认Cookie,并且我在WebView中的会话正在工作。希望这对其他人有所帮助

0dxa2lsx

0dxa2lsx4#

使用cookieManager设置Cookie的最新方法

val siteCookies = CookieManager.getInstance().getCookie(“https://www.dummyurl.com”)
cookieManager.removeSessionCookies {
    if (! siteCookies.isNullOrEmpty()) {
        val cookie = siteCookies.split("; ".toRegex())
            .dropLastWhile { it.isEmpty() } as ArrayList<String>
        val iterator = cookie.iterator()
        while (iterator.hasNext()) {
            val cookie = iterator.next()
            if (cookie.isNullOrEmpty()) continue
            cookieManager.setCookie(“https://www.dummyurl.com”, cookie)
        }
    }
}

如果这能帮到什么人的话。

相关问题