Android:如何在自定义选项卡中设置 cookie 数据

Ser*_*ion 8 cookies android chrome-custom-tabs

我需要在自定义选项卡中打开一个网页。但是,该页面显然需要用户登录。我们不希望用户被要求登录,相反,我们希望将带有 token 的 cookie 设置为 CustomTab,以便他们自动登录。我在这里读过一个答案,说这是不可能的。我理解正确吗?有办法实现目标吗?

编辑:我在 @Aris Panayiotou 的回答后尝试过,但没有成功。我在这里做错了什么?

private void openWebView() {
    if (getActivity() != null) {
        CookieManager cookieManager = new CookieManager();
        CookieHandler.setDefault(cookieManager );
        String cookieStringTakenFromWeb = "some cookie string with correct token";

        CookieStore cookieStore = cookieManager.getCookieStore();
        HttpCookie cookie = new HttpCookie("Cookie", cookieStringTakenFromWeb);
        cookieStore.add(URI.create(Util.getString(R.string.myUrl)), cookie);

        final CustomTabsIntent customTabsIntent = new CustomTabsIntent.Builder(mCustomTabsSession)
                .setToolbarColor(ContextCompat.getColor(getActivity(), R.color.red))
                .setShowTitle(true)
                .build();
        customTabsIntent.launchUrl(getActivity(), Uri.parse(Util.getString(R.string.myUrl)));
    }
}
Run Code Online (Sandbox Code Playgroud)

sta*_*ej2 6

如果您可以更新网站的代码以读取标头,则可以在请求标头中传递令牌。

val customTabsIntent = CustomTabsIntent.Builder(session).build()
val headersBundle = Bundle().apply {
    putString("X-Session-Token", "token")
}
customTabsIntent.intent.putExtra(android.provider.Browser.EXTRA_HEADERS, headersBundle)
Run Code Online (Sandbox Code Playgroud)


小智 -1

据我从你的问题中了解到,你可以尝试CookieHandler。CookieHandler 对象提供回调机制,将 HTTP 状态管理策略实现挂接到 HTTP 协议处理程序中。HTTP 状态管理机制指定了一种使用 HTTP 请求和响应创建有状态会话的方法。

在此链接上阅读更多内容:CookieHandler

CookieManager了解更多:CookieManager