【问题标题】:How to set a cookie in webview depends to response in volley that obtain the cookie ? (kotlin)如何在 webview 中设置 cookie 取决于获取 cookie 的 volley 响应? (科特林)
【发布时间】:2022-01-06 11:46:31
【问题描述】:

我有一个活动,如果凭据正确(用户和通过),我会从标题中获取“Set-cookie”,并使用 post 方法验证它们是否存在于我的网站上,并将它们存储在 SharedPreferences 中,这对我来说是正确的,但是当我尝试在 webview 中设置 cookie 时,它​​根本无法识别它,我尝试了几种方法,仍然让 webview 与用户的会话一起加载。

你就是这样

params["name"] = User.text.toString()
params["pass"] = Password.text.toString()
        val request = AuthUserClass(Request.Method.POST,url,jsonObject,
                     Response.Listener { response ->
    
                     val headers = response.getJSONObject("headers")
                    val setCookie = headers.getString("Set-Cookie")
    }


现在我存储在共享首选项中

val sharedpreferences =getSharedPreferences("Set-Cookie",Context.MODE_PRIVATE)
                    val edit =sharedpreferences.edit()
                    edit.apply{
                    edit.putString("Set-Cookie",setCookie)

                    }.apply()
                    edit.commit()

最后我尝试在 webview 中设置 cookie

                val cookieManager = CookieManager.getInstance()
                cookieManager.acceptCookie()
                val cookieKey= getSharedPreferences("Set-Cookie", Context.MODE_PRIVATE)
                cookieKey.getString("Set-Cookie","")
                val domain =  urlCookie
                cookieManager.setCookie(domain,"$cookieKey")
                cookieManager.setAcceptThirdPartyCookies(binding.webView,true)

我不知道我做错了什么请帮帮我

【问题讨论】:

    标签: android kotlin cookies webview hybrid-mobile-app


    【解决方案1】:

    您在 cookieManager 中设置的 cookie 不是 cookie 值,而是您的 Shared pPreferences 实例的字符串表示形式。

    为了清楚起见,您应该将您的 cookieKey 重命名为 sharedPrefs。然后提取 cookie 字符串值并将其保存到,比如说,cookieValue

    val sharedPrefs: SharedPreferences = getSharedPreferences("Set-Cookie", Context.MODE_PRIVATE)
    val cookieValue: String? = sharedPrefs.getString("Set-Cookie", "")
    
    CookieManager.getInstance().setCookie(domain, cookieValue)
    

    为了清楚起见,我明确设置了变量类型。

    【讨论】:

      猜你喜欢
      • 2023-04-01
      • 1970-01-01
      • 2019-10-22
      • 2013-03-08
      • 1970-01-01
      • 1970-01-01
      • 2016-11-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多