【问题标题】:Android: How to set cookie data in Custom TabsAndroid:如何在自定义选项卡中设置 cookie 数据
【发布时间】:2017-10-26 07:36:27
【问题描述】:

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

编辑:我在@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)));
    }
}

【问题讨论】:

    标签: android cookies chrome-custom-tabs


    【解决方案1】:

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

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

    【讨论】:

    • 我在检查时看不到标头在浏览器中传递,但我网站的前端团队能够访问标头并将它们设置为浏览器上的 cookie。
    【解决方案2】:

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

    在此链接上阅读更多信息:CookieHandler

    CookieManager 阅读更多:CookieManager

    【讨论】:

    • 感谢您提供的信息。你能看看我更新的问题吗?欣赏它。
    • 您的项目中有应用程序吗?如果是,则将其添加到 onCreate 方法 CookieHandler.setDefault(new CookieManager());或在您的主要活动中
    • 没有帮助:(
    猜你喜欢
    • 2018-06-23
    • 1970-01-01
    • 1970-01-01
    • 2022-09-27
    • 1970-01-01
    • 2022-12-20
    • 2022-01-14
    • 1970-01-01
    • 2011-08-22
    相关资源
    最近更新 更多