0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Kotlin]Cookieを扱う(値の設定、取り出し、消去)

Last updated at Posted at 2022-02-02

概要

KotlinでCookieを扱うサンプルコードです(値の設定、取り出し、消去)
WebViewや認証処理で活用できると思います。

本文

package jp.co.cookietest

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.webkit.CookieManager
import jp.co.cookietest.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding
    private val cookieManager = CookieManager.getInstance()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        val view = binding.root
        setContentView(view)

        val url: String = "https://www.yahoo.co.jp/"
        binding.button1.setOnClickListener {
            Log.w("TAG", "cookieに値を設定します")
            setCookie(url, "count", "15")
        }
        binding.button2.setOnClickListener {
            Log.w("TAG", getCookie(url))
        }
        binding.button3.setOnClickListener {
            Log.w("TAG", "cookieを全て消去します")
            removeAllCookies()
        }
    }

    private fun setCookie(url: String, cookieName: String, cookieValue: String) {
        val cookieString = "$cookieName=$cookieValue;"
        cookieManager.setCookie(url, cookieString)
        cookieManager.flush()
    }

    private fun getCookie(url: String): String {
        return cookieManager.getCookie(url) ?: "cookieは空っぽです"
    }

    private fun removeAllCookies() {
        cookieManager.removeAllCookies(null)
    }
}

スクリーンショット 2022-02-02 21.31.58.png
スクリーンショット 2022-02-02 21.31.20.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?