├── .editorconfig ├── .github ├── FUNDING.yml ├── dependabot.yml └── workflows │ └── android.yml ├── .gitignore ├── LICENSE ├── README.md ├── SECURITY.md ├── build.gradle ├── cookie-store-okhttp ├── build.gradle ├── proguard-rules.pro └── src │ ├── main │ └── java │ │ └── net │ │ └── gotev │ │ └── cookiestore │ │ └── okhttp │ │ └── JavaNetCookieJar.kt │ └── test │ └── java │ └── net │ └── gotev │ └── cookiestore │ └── okhttp │ └── ExampleUnitTest.kt ├── cookie-store ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── net │ │ └── gotev │ │ └── cookiestore │ │ └── ExampleInstrumentedTest.kt │ ├── main │ ├── AndroidManifest.xml │ └── java │ │ └── net │ │ └── gotev │ │ └── cookiestore │ │ ├── CookieStoreExtensions.kt │ │ ├── InMemoryCookieStore.kt │ │ ├── InternalCookie.kt │ │ ├── SharedPreferencesCookieStore.kt │ │ └── WebKitSyncCookieManager.kt │ └── test │ └── java │ └── net │ └── gotev │ └── cookiestore │ └── ExampleUnitTest.kt ├── example ├── .gitignore ├── app │ ├── .gitignore │ ├── build.gradle │ ├── gradle │ │ └── wrapper │ │ │ ├── gradle-wrapper.jar │ │ │ └── gradle-wrapper.properties │ ├── gradlew │ ├── gradlew.bat │ ├── local.properties │ ├── proguard-rules.pro │ └── src │ │ ├── androidTest │ │ └── java │ │ │ └── net │ │ │ └── gotev │ │ │ └── cookiestoredemo │ │ │ └── ExampleInstrumentedTest.kt │ │ ├── main │ │ ├── AndroidManifest.xml │ │ ├── java │ │ │ └── net │ │ │ │ └── gotev │ │ │ │ └── cookiestoredemo │ │ │ │ ├── App.kt │ │ │ │ ├── CookieAPI.kt │ │ │ │ └── MainActivity.kt │ │ └── res │ │ │ ├── layout │ │ │ └── activity_main.xml │ │ │ ├── mipmap-hdpi │ │ │ ├── ic_launcher.png │ │ │ └── ic_launcher_round.png │ │ │ ├── mipmap-mdpi │ │ │ ├── ic_launcher.png │ │ │ └── ic_launcher_round.png │ │ │ ├── mipmap-xhdpi │ │ │ ├── ic_launcher.png │ │ │ └── ic_launcher_round.png │ │ │ ├── mipmap-xxhdpi │ │ │ ├── ic_launcher.png │ │ │ └── ic_launcher_round.png │ │ │ ├── mipmap-xxxhdpi │ │ │ ├── ic_launcher.png │ │ │ └── ic_launcher_round.png │ │ │ └── values │ │ │ ├── colors.xml │ │ │ ├── strings.xml │ │ │ └── styles.xml │ │ └── test │ │ └── java │ │ └── net │ │ └── gotev │ │ └── cookiestoredemo │ │ └── ExampleUnitTest.kt ├── build.gradle ├── gradle.properties ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── settings.gradle ├── generate-debug-apk ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── manifest.gradle ├── release └── settings.gradle /.editorconfig: -------------------------------------------------------------------------------- 1 | [*.{kt,kts}] 2 | disabled_rules = import-ordering 3 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | custom: ["https://paypal.me/alexgt"] 2 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: gradle 4 | directory: "/" 5 | schedule: 6 | interval: daily 7 | time: "04:00" 8 | open-pull-requests-limit: 10 9 | -------------------------------------------------------------------------------- /.github/workflows/android.yml: -------------------------------------------------------------------------------- 1 | name: Android CI 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | pull_request: 7 | branches: [ master ] 8 | 9 | jobs: 10 | android-test: 11 | runs-on: macos-latest 12 | if: ${{ false }} # skip job as it currently does not support Android API 31 13 | steps: 14 | - name: checkout 15 | uses: actions/checkout@v2 16 | 17 | - name: run tests 18 | uses: reactivecircus/android-emulator-runner@v2 19 | with: 20 | api-level: 31 21 | script: ./gradlew connectedCheck 22 | 23 | build: 24 | runs-on: ubuntu-latest 25 | 26 | steps: 27 | - uses: actions/checkout@v2 28 | - name: set up JDK 29 | uses: actions/setup-java@v1 30 | with: 31 | java-version: 11 32 | - name: Build with Gradle 33 | run: ./gradlew clean build 34 | 35 | build-demo-app: 36 | runs-on: ubuntu-latest 37 | 38 | steps: 39 | - uses: actions/checkout@v2 40 | - name: set up JDK 41 | uses: actions/setup-java@v1 42 | with: 43 | java-version: 11 44 | - name: Build with Gradle 45 | run: cd example && ./gradlew clean assembleDebug 46 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea/workspace.xml 5 | /.idea/libraries 6 | .DS_Store 7 | build 8 | /captures 9 | .externalNativeBuild 10 | .idea 11 | .iml 12 | *.apk 13 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2019 Aleksandar Gotev 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Android Cookie Store 2 | [![Android Arsenal](https://img.shields.io/badge/Android%20Arsenal-Android%20Cookie%20Store-green.svg?style=flat)](https://android-arsenal.com/details/1/8000) [![Android Weekly](https://img.shields.io/badge/Android%20Weekly-394-green)](https://androidweekly.net/issues/issue-394) [![ktlint](https://img.shields.io/badge/code%20style-%E2%9D%A4-FF4081.svg)](https://ktlint.github.io/) ![Maven Central](https://img.shields.io/maven-central/v/net.gotev/cookie-store) [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](http://makeapullrequest.com) 3 | #### [Latest version Release Notes and Demo App](https://github.com/gotev/android-cookie-store/releases/latest) | [Demo App Sources](https://github.com/gotev/android-cookie-store/tree/master/example/app/src/main/java/net/gotev/cookiestoredemo) 4 | 5 | Android InMemory and persistent Cookie Store for `HttpURLConnection` and `OkHttp`, with extensions to easily sync cookies in Android WebViews. 6 | 7 | ## Why? 8 | Neither `HttpURLConnection` nor `OkHttp` provides a native and rapid way of storing cookies persistently on Android. This library aims to fill this gap, by implementing the standard `java.net.InMemoryCookieStore` in Kotlin, with extendability in mind. 9 | 10 | With this library you have: 11 | - super tiny footprint (the library is only a bunch of classes) 12 | - an in memory only cookie store 13 | - a shared preferences backed cookie store which can survive app reboots 14 | - possibility to extend both to provide your own custom implementation which best fits your needs without reinventing the wheel for cookie management 15 | 16 | ## Compatibility 17 | Android API 16+ 18 | 19 | ## Getting started 20 | Add this to your dependencies: 21 | 22 | ```groovy 23 | implementation "net.gotev:cookie-store:x.y.z" 24 | ``` 25 | Replace `x.y.z` with ![Maven Central](https://img.shields.io/maven-central/v/net.gotev/cookie-store) 26 | 27 | ## Usage 28 | Create your Cookie Manager: 29 | 30 | ```kotlin 31 | // Example extension function to demonstrate how to create both cookie stores 32 | fun Context.createCookieStore(name: String, persistent: Boolean) = if (persistent) { 33 | SharedPreferencesCookieStore(applicationContext, name) 34 | } else { 35 | InMemoryCookieStore(name) 36 | } 37 | 38 | val cookieManager = CookieManager( 39 | createCookieStore(name = "myCookies", persistent = true), 40 | CookiePolicy.ACCEPT_ALL 41 | ) 42 | ``` 43 | 44 | ### HttpURLConnection 45 | To setup the default Cookie Manager: 46 | 47 | ```kotlin 48 | CookieManager.setDefault(cookieManager) 49 | ``` 50 | 51 | ### OkHttp 52 | Add the following dependency (suitable for JVM and Android): 53 | 54 | ```groovy 55 | implementation "net.gotev:cookie-store-okhttp:$cookieStoreVersion" 56 | ``` 57 | 58 | And when you build your OkHttpClient, set the Cookie Jar: 59 | 60 | ```kotlin 61 | val okHttpClient = OkHttpClient.Builder() 62 | .cookieJar(JavaNetCookieJar(cookieManager)) 63 | .build() 64 | ``` 65 | 66 | ### WebView 67 | It's a common thing to obtain a cookie from an API and to open an authenticated web page inside an app which needs the cookie. You can find a complete working example in the demo app. 68 | 69 | You have two ways of doing this: 70 | - Using `WebKitSyncCookieManager` 71 | - Using standard `java.net.CookieManager` 72 | 73 | #### Using WebKitSyncCookieManager 74 | ```kotlin 75 | val cookieManager = WebKitSyncCookieManager( 76 | store = createCookieStore(name = "myCookies", persistent = true), 77 | cookiePolicy = CookiePolicy.ACCEPT_ALL, 78 | onWebKitCookieManagerError = { exception -> 79 | // This gets invoked when there's internal webkit cookie manager exceptions 80 | Log.e("COOKIE-STORE", "WebKitSyncCookieManager error", exception) 81 | } 82 | ) 83 | ``` 84 | Then follow standard instructions from the Usage section to setup `HttpURLConnection` or `OkHttp` according to your needs. 85 | 86 | > Incoming Cookies will be automatically synced to WebKit's CookieManager. Syncing is unidirectional from `WebKitSyncCookieManager` to `android.webkit.CookieManager` to have a single source of truth and to prevent attacks coming from URLs loaded in WebViews. If you need bi-directional sync, think twice before doing it. 87 | 88 | To clear cookies: 89 | 90 | ```kotlin 91 | cookieManager.removeAll() 92 | ``` 93 | 94 | This will clear both the `CookieStore` and WebKit's Cookie Manager. 95 | 96 | #### Using standard java.net.CookieManager 97 | Cookies syncing is entirely up to you and manual. 98 | 99 | To copy all cookies from the cookie store to the WebKit Cookie Manager: 100 | ```kotlin 101 | cookieManager.cookieStore.syncToWebKitCookieManager() 102 | ``` 103 | Remember to do this before loading any URL in your web view. 104 | 105 | To remove all cookies from the Cookie Store: 106 | ```kotlin 107 | cookieManager.cookieStore.removeAll() 108 | ``` 109 | 110 | To remove all cookies from WebKit Cookie Manager: 111 | ```kotlin 112 | android.webkit.CookieManager.getInstance().removeAll() 113 | ``` 114 | 115 | That's all folks! 116 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | ## Supported Versions 4 | 5 | | Version | Supported | 6 | | ------- | ------------------ | 7 | | 1.2.x | :white_check_mark: | 8 | | < 1.2 | :x: | 9 | 10 | ## Reporting a Vulnerability 11 | 12 | Please report (suspected) security vulnerabilities to 13 | **alex@gotev.net**. You will receive a response from 14 | me within 48 hours. If the issue is confirmed, I will release a patch as soon 15 | as possible depending on complexity but historically within a few days. 16 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | buildscript { 3 | apply from: 'manifest.gradle' 4 | 5 | repositories { 6 | google() 7 | mavenCentral() 8 | maven { 9 | url "https://plugins.gradle.org/m2/" 10 | } 11 | } 12 | 13 | dependencies { 14 | classpath "com.android.tools.build:gradle:$gradle_version" 15 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" 16 | classpath "org.jlleitschuh.gradle:ktlint-gradle:$kotlin_lint_version" 17 | 18 | // NOTE: Do not place your application dependencies here; they belong 19 | // in the individual module build.gradle files 20 | } 21 | } 22 | 23 | allprojects { 24 | repositories { 25 | google() 26 | mavenCentral() 27 | } 28 | } 29 | 30 | task clean(type: Delete) { 31 | delete rootProject.buildDir 32 | } 33 | -------------------------------------------------------------------------------- /cookie-store-okhttp/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'java-library' 2 | apply plugin: 'kotlin' 3 | apply plugin: "org.jlleitschuh.gradle.ktlint" 4 | 5 | // start - do not modify this if your project is on github 6 | project.ext { 7 | mavDevelopers = [(github_username): (maintainer)] 8 | mavSiteUrl = "https://github.com/${github_username}/${github_repository_name}" 9 | mavGitUrl = mavSiteUrl + '.git' 10 | bugTrackerUrl = mavSiteUrl + '/issues/' 11 | mavProjectName = "android-cookie-store-okhttp" 12 | mavLibraryLicenses = ["Apache-2.0": 'http://www.apache.org/licenses/LICENSE-2.0.txt'] 13 | mavLibraryDescription = "OkHttp Cookie Jar implementation for java.net.CookieManager" 14 | mavVersion = library_version 15 | } 16 | // end - do not modify this if your project is on github 17 | 18 | group = library_project_group 19 | version = library_version 20 | 21 | dependencies { 22 | // Testing dependencies 23 | testImplementation "junit:junit:$junit_version" 24 | testImplementation "org.jetbrains.kotlin:kotlin-test-junit:$kotlin_version" 25 | 26 | // Kotlin 27 | api "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" 28 | implementation "com.squareup.okhttp3:okhttp:4.9.3" 29 | } 30 | 31 | test { 32 | useJUnit() 33 | maxHeapSize = '1G' 34 | } 35 | 36 | sourceCompatibility = "8" 37 | targetCompatibility = "8" 38 | 39 | apply from: 'https://raw.githubusercontent.com/sky-uk/gradle-maven-plugin/master/gradle-mavenizer.gradle' 40 | -------------------------------------------------------------------------------- /cookie-store-okhttp/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /Users/alex/workspace/sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /cookie-store-okhttp/src/main/java/net/gotev/cookiestore/okhttp/JavaNetCookieJar.kt: -------------------------------------------------------------------------------- 1 | package net.gotev.cookiestore.okhttp 2 | 3 | import okhttp3.Cookie 4 | import okhttp3.CookieJar 5 | import okhttp3.HttpUrl 6 | import java.io.IOException 7 | import java.net.CookieHandler 8 | import java.net.HttpCookie 9 | import java.text.DateFormat 10 | import java.text.SimpleDateFormat 11 | import java.util.Collections 12 | import java.util.Date 13 | import java.util.Locale 14 | import java.util.TimeZone 15 | import java.util.logging.Level 16 | import java.util.logging.Logger 17 | 18 | /** 19 | * A cookie jar that delegates to a [java.net.CookieHandler]. 20 | * 21 | * Copied from https://github.com/square/okhttp/blob/master/okhttp-urlconnection/src/main/java/okhttp3/JavaNetCookieJar.kt 22 | * to not depend on okhttp-urlconnection as suggested by @swankjesse 23 | */ 24 | class JavaNetCookieJar(private val cookieHandler: CookieHandler) : CookieJar { 25 | 26 | companion object { 27 | private const val WARN = 5 28 | } 29 | 30 | private val logger by lazy { 31 | Logger.getLogger(javaClass.name) 32 | } 33 | 34 | private val STANDARD_DATE_FORMAT = object : ThreadLocal() { 35 | override fun initialValue(): DateFormat { 36 | // Date format specified by RFC 7231 section 7.1.1.1. 37 | return SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US).apply { 38 | isLenient = false 39 | timeZone = TimeZone.getTimeZone("GMT") 40 | } 41 | } 42 | } 43 | 44 | private fun log(level: Int, message: String, t: Throwable?) { 45 | val logLevel = if (level == WARN) Level.WARNING else Level.INFO 46 | logger.log(logLevel, message, t) 47 | } 48 | 49 | private fun Date.toHttpDateString(): String = STANDARD_DATE_FORMAT.get().format(this) 50 | 51 | /** 52 | * @param forObsoleteRfc2965 true to include a leading `.` on the domain pattern. This is 53 | * necessary for `example.com` to match `www.example.com` under RFC 2965. This extra dot is 54 | * ignored by more recent specifications. 55 | */ 56 | private fun Cookie.toString(forObsoleteRfc2965: Boolean): String { 57 | return buildString { 58 | append(name) 59 | append('=') 60 | append(value) 61 | 62 | if (persistent) { 63 | if (expiresAt == Long.MIN_VALUE) { 64 | append("; max-age=0") 65 | } else { 66 | append("; expires=").append(Date(expiresAt).toHttpDateString()) 67 | } 68 | } 69 | 70 | if (!hostOnly) { 71 | append("; domain=") 72 | if (forObsoleteRfc2965) { 73 | append(".") 74 | } 75 | append(domain) 76 | } 77 | 78 | append("; path=").append(path) 79 | 80 | if (secure) { 81 | append("; secure") 82 | } 83 | 84 | if (httpOnly) { 85 | append("; httponly") 86 | } 87 | 88 | return toString() 89 | } 90 | } 91 | 92 | /** 93 | * Returns the index of the first character in this string that contains a character in 94 | * [delimiters]. Returns endIndex if there is no such character. 95 | */ 96 | private fun String.delimiterOffset( 97 | delimiters: String, 98 | startIndex: Int = 0, 99 | endIndex: Int = length 100 | ): Int { 101 | for (i in startIndex until endIndex) { 102 | if (this[i] in delimiters) return i 103 | } 104 | return endIndex 105 | } 106 | 107 | /** 108 | * Increments [startIndex] until this string is not ASCII whitespace. Stops at [endIndex]. 109 | */ 110 | private fun String.indexOfFirstNonAsciiWhitespace( 111 | startIndex: Int = 0, 112 | endIndex: Int = length 113 | ): Int { 114 | for (i in startIndex until endIndex) { 115 | when (this[i]) { 116 | '\t', '\n', '\u000C', '\r', ' ' -> Unit 117 | else -> return i 118 | } 119 | } 120 | return endIndex 121 | } 122 | 123 | /** 124 | * Decrements [endIndex] until `input[endIndex - 1]` is not ASCII whitespace. Stops at [startIndex]. 125 | */ 126 | private fun String.indexOfLastNonAsciiWhitespace( 127 | startIndex: Int = 0, 128 | endIndex: Int = length 129 | ): Int { 130 | for (i in endIndex - 1 downTo startIndex) { 131 | when (this[i]) { 132 | '\t', '\n', '\u000C', '\r', ' ' -> Unit 133 | else -> return i + 1 134 | } 135 | } 136 | return startIndex 137 | } 138 | 139 | /** Equivalent to `string.substring(startIndex, endIndex).trim()`. */ 140 | private fun String.trimSubstring(startIndex: Int = 0, endIndex: Int = length): String { 141 | val start = indexOfFirstNonAsciiWhitespace(startIndex, endIndex) 142 | val end = indexOfLastNonAsciiWhitespace(start, endIndex) 143 | return substring(start, end) 144 | } 145 | 146 | override fun saveFromResponse(url: HttpUrl, cookies: List) { 147 | val cookieStrings = mutableListOf() 148 | for (cookie in cookies) { 149 | cookieStrings.add(cookie.toString(forObsoleteRfc2965 = true)) 150 | } 151 | val multimap = mapOf("Set-Cookie" to cookieStrings) 152 | try { 153 | cookieHandler.put(url.toUri(), multimap) 154 | } catch (e: IOException) { 155 | log(WARN, "Saving cookies failed for " + url.resolve("/...")!!, e) 156 | } 157 | } 158 | 159 | override fun loadForRequest(url: HttpUrl): List { 160 | val cookieHeaders = try { 161 | // The RI passes all headers. We don't have 'em, so we don't pass 'em! 162 | cookieHandler.get(url.toUri(), emptyMap>()) 163 | } catch (e: IOException) { 164 | log(WARN, "Loading cookies failed for " + url.resolve("/...")!!, e) 165 | return emptyList() 166 | } 167 | 168 | var cookies: MutableList? = null 169 | for ((key, value) in cookieHeaders) { 170 | if (("Cookie".equals(key, ignoreCase = true) || "Cookie2".equals( 171 | key, 172 | ignoreCase = true 173 | )) && 174 | value.isNotEmpty() 175 | ) { 176 | for (header in value) { 177 | if (cookies == null) cookies = mutableListOf() 178 | cookies.addAll(decodeHeaderAsJavaNetCookies(url, header)) 179 | } 180 | } 181 | } 182 | 183 | return if (cookies != null) { 184 | Collections.unmodifiableList(cookies) 185 | } else { 186 | emptyList() 187 | } 188 | } 189 | 190 | /** 191 | * Convert a request header to OkHttp's cookies via [HttpCookie]. That extra step handles 192 | * multiple cookies in a single request header, which [Cookie.parse] doesn't support. 193 | */ 194 | private fun decodeHeaderAsJavaNetCookies(url: HttpUrl, header: String): List { 195 | val result = mutableListOf() 196 | var pos = 0 197 | val limit = header.length 198 | var pairEnd: Int 199 | while (pos < limit) { 200 | pairEnd = header.delimiterOffset(";,", pos, limit) 201 | val equalsSign = header.delimiterOffset("=", pos, pairEnd) 202 | val name = header.trimSubstring(pos, equalsSign) 203 | if (name.startsWith("$")) { 204 | pos = pairEnd + 1 205 | continue 206 | } 207 | 208 | // We have either name=value or just a name. 209 | var value = if (equalsSign < pairEnd) { 210 | header.trimSubstring(equalsSign + 1, pairEnd) 211 | } else { 212 | "" 213 | } 214 | 215 | // If the value is "quoted", drop the quotes. 216 | if (value.startsWith("\"") && value.endsWith("\"")) { 217 | value = value.substring(1, value.length - 1) 218 | } 219 | 220 | result.add( 221 | Cookie.Builder() 222 | .name(name) 223 | .value(value) 224 | .domain(url.host) 225 | .build() 226 | ) 227 | pos = pairEnd + 1 228 | } 229 | return result 230 | } 231 | } 232 | -------------------------------------------------------------------------------- /cookie-store-okhttp/src/test/java/net/gotev/cookiestore/okhttp/ExampleUnitTest.kt: -------------------------------------------------------------------------------- 1 | package net.gotev.cookiestore.okhttp 2 | 3 | import org.junit.Assert.assertEquals 4 | import org.junit.Test 5 | 6 | /** 7 | * Example local unit test, which will execute on the development machine (host). 8 | * 9 | * @see [Testing documentation](http://d.android.com/tools/testing) 10 | */ 11 | class ExampleUnitTest { 12 | @Test 13 | @Throws(Exception::class) 14 | fun addition_isCorrect() { 15 | assertEquals(4, (2 + 2).toLong()) 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /cookie-store/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | apply plugin: 'kotlin-android' 3 | apply plugin: "org.jlleitschuh.gradle.ktlint" 4 | 5 | // start - do not modify this if your project is on github 6 | project.ext { 7 | mavDevelopers = [(github_username): (maintainer)] 8 | mavSiteUrl = "https://github.com/${github_username}/${github_repository_name}" 9 | mavGitUrl = mavSiteUrl + '.git' 10 | bugTrackerUrl = mavSiteUrl + '/issues/' 11 | mavProjectName = "android-cookie-store" 12 | mavLibraryLicenses = ["Apache-2.0": 'http://www.apache.org/licenses/LICENSE-2.0.txt'] 13 | mavLibraryDescription = "Android InMemory and persistent Cookie Store for HttpURLConnection and OkHttp, with extensions to easily sync cookies in Android WebViews." 14 | mavVersion = library_version 15 | } 16 | // end - do not modify this if your project is on github 17 | 18 | group = library_project_group 19 | version = library_version 20 | 21 | android { 22 | compileSdkVersion target_sdk 23 | 24 | defaultConfig { 25 | minSdkVersion min_sdk 26 | targetSdkVersion target_sdk 27 | versionCode version_code 28 | versionName library_version 29 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 30 | } 31 | 32 | buildTypes { 33 | release { 34 | minifyEnabled false 35 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 36 | consumerProguardFiles 'proguard-rules.pro' 37 | } 38 | } 39 | 40 | compileOptions { 41 | sourceCompatibility JavaVersion.VERSION_1_8 42 | targetCompatibility JavaVersion.VERSION_1_8 43 | } 44 | 45 | lintOptions { 46 | warning 'InvalidPackage' 47 | } 48 | } 49 | 50 | dependencies { 51 | // Testing - https://developer.android.com/training/testing/set-up-project 52 | testImplementation "junit:junit:$junit_version" 53 | 54 | // Core library 55 | androidTestImplementation "androidx.test:core:$androidx_test_core_version" 56 | 57 | // AndroidJUnitRunner and JUnit Rules 58 | androidTestImplementation "androidx.test:runner:$androidx_test_runner_version" 59 | androidTestImplementation "androidx.test:rules:$androidx_test_rules_version" 60 | 61 | // Assertions 62 | androidTestImplementation "androidx.test.ext:junit:$androidx_test_ext_junit_version" 63 | androidTestImplementation "androidx.test.ext:truth:$androidx_test_ext_truth_version" 64 | androidTestImplementation "com.google.truth:truth:$truth_version" 65 | 66 | // Espresso dependencies 67 | androidTestImplementation "androidx.test.espresso:espresso-core:$androidx_test_espresso_version" 68 | 69 | // Kotlin 70 | api "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" 71 | implementation "com.google.code.gson:gson:2.9.0" 72 | } 73 | 74 | apply from: 'https://raw.githubusercontent.com/sky-uk/gradle-maven-plugin/master/gradle-mavenizer.gradle' 75 | -------------------------------------------------------------------------------- /cookie-store/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /Users/alex/workspace/sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | 19 | # Application class that will be serialized/deserialized over Gson 20 | -keep class java.net.HttpCookie { ; } 21 | -------------------------------------------------------------------------------- /cookie-store/src/androidTest/java/net/gotev/cookiestore/ExampleInstrumentedTest.kt: -------------------------------------------------------------------------------- 1 | package net.gotev.cookiestore 2 | 3 | import android.app.Application 4 | import androidx.test.core.app.ApplicationProvider 5 | import androidx.test.ext.junit.runners.AndroidJUnit4 6 | import org.junit.Assert.assertEquals 7 | import org.junit.Test 8 | import org.junit.runner.RunWith 9 | 10 | /** 11 | * Instrumentation test, which will execute on an Android device. 12 | * 13 | * @see [Testing documentation](http://d.android.com/tools/testing) 14 | */ 15 | @RunWith(AndroidJUnit4::class) 16 | class ExampleInstrumentedTest { 17 | @Test 18 | @Throws(Exception::class) 19 | fun useAppContext() { 20 | // Context of the app under test. 21 | val appContext = ApplicationProvider.getApplicationContext() 22 | 23 | assertEquals("net.gotev.cookiestore.test", appContext.packageName) 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /cookie-store/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /cookie-store/src/main/java/net/gotev/cookiestore/CookieStoreExtensions.kt: -------------------------------------------------------------------------------- 1 | package net.gotev.cookiestore 2 | 3 | import android.os.Build 4 | import java.net.CookieStore 5 | import java.net.HttpCookie 6 | import java.text.SimpleDateFormat 7 | import java.util.Calendar 8 | import java.util.Locale 9 | import java.util.TimeZone 10 | 11 | fun HttpCookie.toSetCookieString(): String { 12 | val expires = if (maxAge != -1L) { 13 | val dateFormat = SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.UK).apply { 14 | timeZone = TimeZone.getTimeZone("GMT") 15 | } 16 | 17 | val calendar = Calendar.getInstance(Locale.UK).apply { set(Calendar.SECOND, maxAge.toInt()) } 18 | 19 | "; expires=${dateFormat.format(calendar.time)}" 20 | } else { 21 | "" 22 | } 23 | 24 | val path = if (path != null) "; path=$path" else "" 25 | val domain = if (domain != null) "; domain=$domain" else "" 26 | val secure = if (secure) "; secure" else "" 27 | val httpOnly = if (Build.VERSION.SDK_INT >= 24) { 28 | if (isHttpOnly) "; httponly" else "" 29 | } else { 30 | "" 31 | } 32 | 33 | return "$name=$value$expires$path$domain$secure$httpOnly" 34 | } 35 | 36 | @Synchronized 37 | fun CookieStore.syncToWebKitCookieManager() { 38 | val webKitCookieManager = android.webkit.CookieManager.getInstance() 39 | 40 | cookies.forEach { 41 | val hostUrl = "${if (it.secure) "https" else "http"}://${it.domain}" 42 | webKitCookieManager.setCookie(hostUrl, it.toSetCookieString()) 43 | } 44 | 45 | if (Build.VERSION.SDK_INT >= 21) { 46 | webKitCookieManager.flush() 47 | } 48 | } 49 | 50 | @Synchronized 51 | @Suppress("DEPRECATION") 52 | fun android.webkit.CookieManager.removeAll() { 53 | if (Build.VERSION.SDK_INT >= 21) { 54 | removeAllCookies(null) 55 | flush() 56 | } else { 57 | removeAllCookie() 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /cookie-store/src/main/java/net/gotev/cookiestore/InMemoryCookieStore.kt: -------------------------------------------------------------------------------- 1 | package net.gotev.cookiestore 2 | 3 | import android.os.Build 4 | import android.util.Log 5 | import java.net.CookieStore 6 | import java.net.HttpCookie 7 | import java.net.URI 8 | import java.net.URISyntaxException 9 | import java.util.Collections 10 | import java.util.LinkedHashMap 11 | import java.util.concurrent.locks.ReentrantLock 12 | 13 | // Kotlin-ized starting from https://chromium.googlesource.com/android_tools/+/master/sdk/sources/android-25/java/net/InMemoryCookieStore.java 14 | open class InMemoryCookieStore(private val name: String) : CookieStore { 15 | 16 | internal val uriIndex = LinkedHashMap>() 17 | private val lock = ReentrantLock(false) 18 | 19 | override fun removeAll(): Boolean { 20 | lock.lock() 21 | 22 | val result: Boolean 23 | 24 | try { 25 | result = uriIndex.isNotEmpty() 26 | uriIndex.clear() 27 | } finally { 28 | lock.unlock() 29 | } 30 | 31 | return result 32 | } 33 | 34 | override fun add(uri: URI?, cookie: HttpCookie?) { 35 | if (cookie == null) { 36 | Log.i( 37 | javaClass.simpleName, 38 | "tried to add null cookie in cookie store named $name. Doing nothing." 39 | ) 40 | return 41 | } 42 | 43 | if (uri == null) { 44 | Log.i( 45 | javaClass.simpleName, 46 | "tried to add null URI in cookie store named $name. Doing nothing." 47 | ) 48 | return 49 | } 50 | 51 | lock.lock() 52 | try { 53 | addIndex(getEffectiveURI(uri), cookie) 54 | } finally { 55 | lock.unlock() 56 | } 57 | } 58 | 59 | override fun getCookies(): List { 60 | val rt = arrayListOf() 61 | 62 | lock.lock() 63 | try { 64 | for (list in uriIndex.values) { 65 | val it = list.iterator() 66 | while (it.hasNext()) { 67 | val cookie = it.next() 68 | if (cookie.hasExpired()) { 69 | it.remove() 70 | } else if (!rt.contains(cookie)) { 71 | rt.add(cookie) 72 | } 73 | } 74 | } 75 | } finally { 76 | lock.unlock() 77 | } 78 | 79 | return Collections.unmodifiableList(rt) 80 | } 81 | 82 | override fun getURIs(): List { 83 | val uris = arrayListOf() 84 | 85 | lock.lock() 86 | try { 87 | val result = ArrayList(uriIndex.keys) 88 | result.remove(null) 89 | return Collections.unmodifiableList(result) 90 | } finally { 91 | uris.addAll(uriIndex.keys) 92 | lock.unlock() 93 | } 94 | } 95 | 96 | override fun remove(uri: URI?, cookie: HttpCookie?): Boolean { 97 | if (cookie == null) { 98 | Log.i( 99 | javaClass.simpleName, 100 | "tried to remove null cookie from cookie store named $name. Doing nothing." 101 | ) 102 | return true 103 | } 104 | 105 | if (uri == null) { 106 | Log.i( 107 | javaClass.simpleName, 108 | "tried to remove null URI from cookie store named $name. Doing nothing." 109 | ) 110 | return true 111 | } 112 | 113 | lock.lock() 114 | 115 | return try { 116 | val lintedURI = getEffectiveURI(uri) 117 | 118 | if (uriIndex[lintedURI] == null) { 119 | false 120 | } else { 121 | val cookies = uriIndex[lintedURI] 122 | cookies?.remove(cookie) ?: false 123 | } 124 | } finally { 125 | lock.unlock() 126 | } 127 | } 128 | 129 | override fun get(uri: URI?): List { 130 | if (uri == null) { 131 | Log.i( 132 | javaClass.simpleName, 133 | "getting cookies from cookie store named $name for null URI results in empty list" 134 | ) 135 | return emptyList() 136 | } 137 | 138 | val cookies = arrayListOf() 139 | 140 | lock.lock() 141 | try { 142 | uri.host?.let { cookies.addAll(getInternal1(it)) } 143 | val internal2 = getInternal2(getEffectiveURI(uri)).filter { !cookies.contains(it) } 144 | cookies.addAll(internal2) 145 | } finally { 146 | lock.unlock() 147 | } 148 | 149 | return cookies 150 | } 151 | 152 | // Copied from java.net.InMemoryCookieStore and migrated to Kotlin + minor improvements 153 | 154 | // for cookie purpose, the effective uri should only be http://host 155 | // the path will be taken into account when path-match algorithm applied 156 | internal fun getEffectiveURI(uri: URI): URI { 157 | return try { 158 | URI(uri.scheme ?: "http", uri.host, null, null, null) 159 | } catch (ignored: URISyntaxException) { 160 | uri 161 | } 162 | } 163 | 164 | private fun addIndex(index: URI, cookie: HttpCookie) { 165 | val cookies = uriIndex[index] 166 | 167 | if (cookies != null) { 168 | cookies.remove(cookie) 169 | cookies.add(cookie) 170 | } else { 171 | val newCookies = ArrayList() 172 | newCookies.add(cookie) 173 | uriIndex[index] = newCookies 174 | } 175 | } 176 | 177 | private fun netscapeDomainMatches(domain: String?, host: String?): Boolean { 178 | if (domain == null || host == null) { 179 | return false 180 | } 181 | 182 | // if there's no embedded dot in domain and domain is not .local 183 | val isLocalDomain = ".local".equals(domain, ignoreCase = true) 184 | var embeddedDotInDomain = domain.indexOf('.') 185 | if (embeddedDotInDomain == 0) { 186 | embeddedDotInDomain = domain.indexOf('.', 1) 187 | } 188 | if (!isLocalDomain && (embeddedDotInDomain == -1 || embeddedDotInDomain == domain.length - 1)) { 189 | return false 190 | } 191 | 192 | // if the host name contains no dot and the domain name is .local 193 | val firstDotInHost = host.indexOf('.') 194 | if (firstDotInHost == -1 && isLocalDomain) { 195 | return true 196 | } 197 | 198 | val domainLength = domain.length 199 | val lengthDiff = host.length - domainLength 200 | if (lengthDiff == 0) { 201 | // if the host name and the domain name are just string-compare euqal 202 | return host.equals(domain, ignoreCase = true) 203 | } else if (lengthDiff > 0) { 204 | // need to check H & D component 205 | val D = host.substring(lengthDiff) 206 | 207 | // Android-changed: b/26456024 targetSdkVersion based compatibility for domain matching 208 | // Android M and earlier: Cookies with domain "foo.com" would not match "bar.foo.com". 209 | // The RFC dictates that the user agent must treat those domains as if they had a 210 | // leading period and must therefore match "bar.foo.com". 211 | return if (Build.VERSION.SDK_INT <= 23 && !domain.startsWith(".")) { 212 | false 213 | } else D.equals(domain, ignoreCase = true) 214 | } else if (lengthDiff == -1) { 215 | // if domain is actually .host 216 | return domain[0] == '.' && host.equals(domain.substring(1), ignoreCase = true) 217 | } 218 | 219 | return false 220 | } 221 | 222 | private fun getInternal1(host: String): List { 223 | // BEGIN Android-changed: b/25897688 InMemoryCookieStore ignores scheme (http/https) 224 | // Use a separate list to handle cookies that need to be removed so 225 | // that there is no conflict with iterators. 226 | val toRemove = ArrayList() 227 | val cookies = ArrayList() 228 | 229 | for ((_, lst) in uriIndex) { 230 | for (c in lst) { 231 | val domain = c.domain 232 | if (c.version == 0 && netscapeDomainMatches( 233 | domain, 234 | host 235 | ) || c.version == 1 && HttpCookie.domainMatches(domain, host) 236 | ) { 237 | 238 | // the cookie still in main cookie store 239 | if (!c.hasExpired()) { 240 | // don't add twice 241 | if (!cookies.contains(c)) { 242 | cookies.add(c) 243 | } 244 | } else { 245 | toRemove.add(c) 246 | } 247 | } 248 | } 249 | // Clear up the cookies that need to be removed 250 | for (c in toRemove) { 251 | lst.remove(c) 252 | } 253 | toRemove.clear() 254 | } 255 | 256 | return cookies 257 | } 258 | 259 | private fun getInternal2(comparator: URI): List { 260 | // BEGIN Android-changed: b/25897688 InMemoryCookieStore ignores scheme (http/https) 261 | // Removed cookieJar 262 | val cookies = ArrayList() 263 | 264 | for (index in uriIndex.keys) { 265 | if (index === comparator || comparator.compareTo(index) == 0) { 266 | val indexedCookies = uriIndex[index] 267 | // check the list of cookies associated with this domain 268 | if (indexedCookies != null) { 269 | val it = indexedCookies.iterator() 270 | while (it.hasNext()) { 271 | val ck = it.next() 272 | // the cookie still in main cookie store 273 | if (!ck.hasExpired()) { 274 | // don't add twice 275 | if (!cookies.contains(ck)) 276 | cookies.add(ck) 277 | } else { 278 | it.remove() 279 | } 280 | } 281 | } // end of indexedCookies != null 282 | } // end of comparator.compareTo(index) == 0 283 | } // end of cookieIndex iteration 284 | 285 | return cookies 286 | } 287 | } 288 | -------------------------------------------------------------------------------- /cookie-store/src/main/java/net/gotev/cookiestore/InternalCookie.kt: -------------------------------------------------------------------------------- 1 | package net.gotev.cookiestore 2 | 3 | import android.os.Build 4 | import java.net.HttpCookie 5 | 6 | data class InternalCookie( 7 | val comment: String?, 8 | val commentURL: String?, 9 | val discard: Boolean?, 10 | val domain: String, 11 | val maxAge: Long?, 12 | val name: String, 13 | val path: String?, 14 | val portlist: String?, 15 | val secure: Boolean?, 16 | val value: String, 17 | val version: Int?, 18 | var httpOnly: Boolean? = null 19 | ) { 20 | constructor(cookie: HttpCookie) : this( 21 | comment = cookie.comment, 22 | commentURL = cookie.commentURL, 23 | discard = cookie.discard, 24 | domain = cookie.domain, 25 | maxAge = cookie.maxAge, 26 | name = cookie.name, 27 | path = cookie.path, 28 | portlist = cookie.portlist, 29 | secure = cookie.secure, 30 | value = cookie.value, 31 | version = cookie.version 32 | ) 33 | 34 | fun toHttpCookie() = HttpCookie(name, value).apply { 35 | comment = this@InternalCookie.comment 36 | commentURL = this@InternalCookie.commentURL 37 | discard = this@InternalCookie.discard == true 38 | domain = this@InternalCookie.domain 39 | maxAge = this@InternalCookie.maxAge ?: 0 40 | path = this@InternalCookie.path 41 | portlist = this@InternalCookie.portlist 42 | secure = this@InternalCookie.secure == true 43 | version = this@InternalCookie.version ?: 0 44 | 45 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { 46 | isHttpOnly = this@InternalCookie.httpOnly == true 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /cookie-store/src/main/java/net/gotev/cookiestore/SharedPreferencesCookieStore.kt: -------------------------------------------------------------------------------- 1 | package net.gotev.cookiestore 2 | 3 | import android.content.Context 4 | import android.os.Build 5 | import android.util.Log 6 | import com.google.gson.Gson 7 | import com.google.gson.reflect.TypeToken 8 | import java.net.HttpCookie 9 | import java.net.URI 10 | 11 | open class SharedPreferencesCookieStore( 12 | context: Context, 13 | private val name: String 14 | ) : InMemoryCookieStore(name) { 15 | 16 | private val preferences = context.getSharedPreferences(name, Context.MODE_PRIVATE) 17 | private val gson = Gson() 18 | 19 | init { 20 | synchronized(SharedPreferencesCookieStore::class.java) { 21 | preferences.all.forEach { (key, value) -> 22 | try { 23 | val index = URI.create(key) 24 | val listType = object : TypeToken>() {}.type 25 | val internalCookies = 26 | gson.fromJson>(value.toString(), listType) 27 | val cookies = internalCookies.map { it.toHttpCookie() }.toMutableList() 28 | uriIndex[index] = cookies 29 | } catch (exception: Throwable) { 30 | Log.e( 31 | javaClass.simpleName, 32 | "Error while loading key = $key, value = $value from cookie store named $name", 33 | exception 34 | ) 35 | } 36 | } 37 | } 38 | } 39 | 40 | override fun removeAll(): Boolean = 41 | synchronized(SharedPreferencesCookieStore::class.java) { 42 | super.removeAll() 43 | preferences.edit().clear().apply() 44 | true 45 | } 46 | 47 | override fun add(uri: URI?, cookie: HttpCookie?) = 48 | synchronized(SharedPreferencesCookieStore::class.java) { 49 | uri ?: return@synchronized 50 | 51 | super.add(uri, cookie) 52 | val index = getEffectiveURI(uri) 53 | val cookies = uriIndex[index] ?: return@synchronized 54 | 55 | val internalCookies = cookies.map { 56 | InternalCookie(it).apply { 57 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { 58 | httpOnly = it.isHttpOnly 59 | } 60 | } 61 | } 62 | 63 | val listType = object : TypeToken>() {}.type 64 | val json = gson.toJson(internalCookies, listType) 65 | 66 | preferences 67 | .edit() 68 | .putString(index.toString(), json) 69 | .apply() 70 | } 71 | 72 | override fun remove(uri: URI?, cookie: HttpCookie?): Boolean = 73 | synchronized(SharedPreferencesCookieStore::class.java) { 74 | uri ?: return false 75 | 76 | val result = super.remove(uri, cookie) 77 | val index = getEffectiveURI(uri) 78 | val cookies = uriIndex[index] 79 | val internalCookies = cookies?.map { 80 | InternalCookie(it).apply { 81 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { 82 | httpOnly = it.isHttpOnly 83 | } 84 | } 85 | } 86 | val listType = object : TypeToken>() {}.type 87 | val json = gson.toJson(internalCookies, listType) 88 | 89 | preferences.edit().apply { 90 | when (cookies) { 91 | null -> remove(index.toString()) 92 | else -> putString(index.toString(), json) 93 | } 94 | }.apply() 95 | 96 | return result 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /cookie-store/src/main/java/net/gotev/cookiestore/WebKitSyncCookieManager.kt: -------------------------------------------------------------------------------- 1 | package net.gotev.cookiestore 2 | 3 | import android.util.Log 4 | import java.net.CookieManager 5 | import java.net.CookiePolicy 6 | import java.net.CookieStore 7 | import java.net.URI 8 | 9 | class WebKitSyncCookieManager( 10 | store: CookieStore, 11 | cookiePolicy: CookiePolicy, 12 | private val onWebKitCookieManagerError: ((Throwable) -> Unit)? = null 13 | ) : CookieManager(store, cookiePolicy) { 14 | 15 | private inline fun handleExceptions(block: () -> Unit) { 16 | try { 17 | block() 18 | } catch (exc: Throwable) { 19 | onWebKitCookieManagerError?.invoke(exc) 20 | ?: Log.e( 21 | "COOKIE-STORE", 22 | "Unhandled WebKitSyncCookieManager error. " + 23 | "You could handle it by setting onWebKitCookieManagerError when you create " + 24 | "WebKitSyncCookieManager. This exception is caused by the underlying " + 25 | "android.webkit.CookieManager", exc 26 | ) 27 | } 28 | } 29 | 30 | init { 31 | handleExceptions { 32 | android.webkit.CookieManager.getInstance().setAcceptCookie(true) 33 | } 34 | } 35 | 36 | override fun put(uri: URI?, responseHeaders: MutableMap>?) { 37 | super.put(uri, responseHeaders) 38 | handleExceptions { 39 | cookieStore.syncToWebKitCookieManager() 40 | } 41 | } 42 | 43 | fun removeAll() { 44 | cookieStore.removeAll() 45 | handleExceptions { 46 | android.webkit.CookieManager.getInstance().removeAll() 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /cookie-store/src/test/java/net/gotev/cookiestore/ExampleUnitTest.kt: -------------------------------------------------------------------------------- 1 | package net.gotev.cookiestore 2 | 3 | import org.junit.Assert.assertEquals 4 | import org.junit.Test 5 | 6 | /** 7 | * Example local unit test, which will execute on the development machine (host). 8 | * 9 | * @see [Testing documentation](http://d.android.com/tools/testing) 10 | */ 11 | class ExampleUnitTest { 12 | @Test 13 | @Throws(Exception::class) 14 | fun addition_isCorrect() { 15 | assertEquals(4, (2 + 2).toLong()) 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /example/.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea/workspace.xml 5 | /.idea/libraries 6 | .DS_Store 7 | /build 8 | /captures 9 | .externalNativeBuild 10 | -------------------------------------------------------------------------------- /example/app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /example/app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | apply plugin: 'kotlin-android' 3 | apply plugin: "org.jlleitschuh.gradle.ktlint" 4 | 5 | android { 6 | compileSdkVersion target_sdk 7 | 8 | defaultConfig { 9 | applicationId demo_app_id 10 | minSdkVersion min_sdk 11 | targetSdkVersion target_sdk 12 | versionCode version_code 13 | versionName library_version 14 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 15 | } 16 | 17 | buildTypes { 18 | release { 19 | minifyEnabled false 20 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 21 | } 22 | } 23 | 24 | compileOptions { 25 | sourceCompatibility JavaVersion.VERSION_1_8 26 | targetCompatibility JavaVersion.VERSION_1_8 27 | } 28 | } 29 | 30 | dependencies { 31 | // Testing - https://developer.android.com/training/testing/set-up-project 32 | testImplementation "junit:junit:$junit_version" 33 | testImplementation "org.jetbrains.kotlin:kotlin-test-junit:$kotlin_version" 34 | 35 | def chucker_version = "3.5.2" 36 | debugImplementation "com.github.chuckerteam.chucker:library:$chucker_version" 37 | releaseImplementation "com.github.chuckerteam.chucker:library-no-op:$chucker_version" 38 | 39 | // Core library 40 | androidTestImplementation "androidx.test:core:$androidx_test_core_version" 41 | 42 | // AndroidJUnitRunner and JUnit Rules 43 | androidTestImplementation "androidx.test:runner:$androidx_test_runner_version" 44 | androidTestImplementation "androidx.test:rules:$androidx_test_rules_version" 45 | 46 | // Assertions 47 | androidTestImplementation "androidx.test.ext:junit:$androidx_test_ext_junit_version" 48 | androidTestImplementation "androidx.test.ext:truth:$androidx_test_ext_truth_version" 49 | androidTestImplementation "com.google.truth:truth:$truth_version" 50 | 51 | // Espresso dependencies 52 | androidTestImplementation "androidx.test.espresso:espresso-core:$androidx_test_espresso_version" 53 | 54 | // Support 55 | implementation "androidx.appcompat:appcompat:$androidx_appcompat_version" 56 | implementation 'com.google.android.material:material:1.5.0' 57 | 58 | implementation project(':cookie-store') 59 | implementation project(':cookie-store-okhttp') 60 | 61 | def okHttpVersion = "4.9.3" 62 | implementation "com.squareup.okhttp3:okhttp:$okHttpVersion" 63 | 64 | def retrofitVersion = "2.9.0" 65 | implementation "com.squareup.retrofit2:retrofit:$retrofitVersion" 66 | implementation "com.squareup.retrofit2:converter-scalars:$retrofitVersion" 67 | implementation "com.squareup.retrofit2:converter-gson:$retrofitVersion" 68 | 69 | implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.0' 70 | } 71 | 72 | task prepareKotlinBuildScriptModel {} 73 | -------------------------------------------------------------------------------- /example/app/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gotev/android-cookie-store/d500be6b1d46df2f85c99e09ab72b00635124878/example/app/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /example/app/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Mon Feb 01 06:52:44 CET 2021 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-bin.zip 7 | -------------------------------------------------------------------------------- /example/app/gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /example/app/gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /example/app/local.properties: -------------------------------------------------------------------------------- 1 | ## This file must *NOT* be checked into Version Control Systems, 2 | # as it contains information specific to your local configuration. 3 | # 4 | # Location of the SDK. This is only used by Gradle. 5 | # For customization when using a Version Control System, please read the 6 | # header note. 7 | #Mon Feb 01 06:50:31 CET 2021 8 | sdk.dir=/Users/alex/Library/Android/sdk 9 | -------------------------------------------------------------------------------- /example/app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /Users/alex/Library/Android/sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | 19 | # Uncomment this to preserve the line number information for 20 | # debugging stack traces. 21 | #-keepattributes SourceFile,LineNumberTable 22 | 23 | # If you keep the line number information, uncomment this to 24 | # hide the original source file name. 25 | #-renamesourcefileattribute SourceFile 26 | 27 | # Class is serialized/deserialized over Gson by cookie-store dependency. 28 | -keep class java.net.HttpCookie { ; } 29 | -------------------------------------------------------------------------------- /example/app/src/androidTest/java/net/gotev/cookiestoredemo/ExampleInstrumentedTest.kt: -------------------------------------------------------------------------------- 1 | package net.gotev.cookiestoredemo 2 | 3 | import androidx.test.core.app.ApplicationProvider 4 | import androidx.test.ext.junit.runners.AndroidJUnit4 5 | import org.junit.Assert.assertEquals 6 | import org.junit.Test 7 | import org.junit.runner.RunWith 8 | 9 | /** 10 | * Instrumentation test, which will execute on an Android device. 11 | * 12 | * @see [Testing documentation](http://d.android.com/tools/testing) 13 | */ 14 | @RunWith(AndroidJUnit4::class) 15 | class ExampleInstrumentedTest { 16 | @Test 17 | @Throws(Exception::class) 18 | fun useAppContext() { 19 | // Context of the app under test. 20 | val appContext = ApplicationProvider.getApplicationContext() 21 | 22 | assertEquals("net.gotev.cookiestoredemo", appContext.packageName) 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /example/app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 16 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /example/app/src/main/java/net/gotev/cookiestoredemo/App.kt: -------------------------------------------------------------------------------- 1 | package net.gotev.cookiestoredemo 2 | 3 | import android.app.Application 4 | import android.util.Log 5 | import com.chuckerteam.chucker.api.ChuckerInterceptor 6 | import net.gotev.cookiestore.InMemoryCookieStore 7 | import net.gotev.cookiestore.SharedPreferencesCookieStore 8 | import net.gotev.cookiestore.WebKitSyncCookieManager 9 | import net.gotev.cookiestore.okhttp.JavaNetCookieJar 10 | import okhttp3.OkHttpClient 11 | import retrofit2.Retrofit 12 | import retrofit2.converter.gson.GsonConverterFactory 13 | import retrofit2.converter.scalars.ScalarsConverterFactory 14 | import java.net.CookieManager 15 | import java.net.CookiePolicy 16 | 17 | /** 18 | * @author Aleksandar Gotev 19 | */ 20 | class App : Application() { 21 | 22 | companion object { 23 | const val baseAPIUrl = "https://www.gotev.net/cookiedemo/" 24 | const val webViewUrl = "https://www.gotev.net/cookiedemo/home.php" 25 | const val cookieStoreName = "myCookies" 26 | const val username = "userdemo" 27 | 28 | lateinit var cookieManager: WebKitSyncCookieManager 29 | lateinit var cookieAPI: CookieAPI 30 | } 31 | 32 | private fun createCookieStore(name: String, persistent: Boolean) = if (persistent) { 33 | SharedPreferencesCookieStore(this, name) 34 | } else { 35 | InMemoryCookieStore(name) 36 | } 37 | 38 | override fun onCreate() { 39 | super.onCreate() 40 | 41 | cookieManager = WebKitSyncCookieManager( 42 | store = createCookieStore(name = cookieStoreName, persistent = true), 43 | cookiePolicy = CookiePolicy.ACCEPT_ALL, 44 | onWebKitCookieManagerError = { exception -> 45 | // This gets invoked when there's internal webkit cookie manager exceptions 46 | Log.e("COOKIE-STORE", "WebKitSyncCookieManager error", exception) 47 | } 48 | ) 49 | 50 | // Setup for HttpURLConnection 51 | CookieManager.setDefault(cookieManager) 52 | 53 | // Setup for OkHttp 54 | val okHttpClient = OkHttpClient.Builder() 55 | .cookieJar(JavaNetCookieJar(cookieManager)) 56 | .addNetworkInterceptor(ChuckerInterceptor.Builder(this).build()) 57 | .build() 58 | 59 | cookieAPI = Retrofit.Builder() 60 | .baseUrl(baseAPIUrl) 61 | .addConverterFactory(ScalarsConverterFactory.create()) 62 | .addConverterFactory(GsonConverterFactory.create()) 63 | .client(okHttpClient) 64 | .build() 65 | .create(CookieAPI::class.java) 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /example/app/src/main/java/net/gotev/cookiestoredemo/CookieAPI.kt: -------------------------------------------------------------------------------- 1 | package net.gotev.cookiestoredemo 2 | 3 | import retrofit2.http.Body 4 | import retrofit2.http.GET 5 | import retrofit2.http.POST 6 | 7 | data class LoginPayload(val username: String) 8 | 9 | interface CookieAPI { 10 | @POST("login.php") 11 | suspend fun login(@Body payload: LoginPayload) 12 | 13 | @GET("home.php") 14 | suspend fun home(): String 15 | } 16 | -------------------------------------------------------------------------------- /example/app/src/main/java/net/gotev/cookiestoredemo/MainActivity.kt: -------------------------------------------------------------------------------- 1 | package net.gotev.cookiestoredemo 2 | 3 | import android.os.Bundle 4 | import android.util.Log 5 | import android.webkit.WebView 6 | import android.webkit.WebViewClient 7 | import android.widget.Button 8 | import android.widget.Toast 9 | import androidx.appcompat.app.AppCompatActivity 10 | import kotlinx.coroutines.MainScope 11 | import kotlinx.coroutines.launch 12 | 13 | /** 14 | * This is only to show the cookie store functionality with a WebView in the simplest way 15 | * possible to make you understand it. Don't take this as a production example! 16 | */ 17 | class MainActivity : AppCompatActivity() { 18 | private val scope = MainScope() 19 | 20 | override fun onCreate(savedInstanceState: Bundle?) { 21 | super.onCreate(savedInstanceState) 22 | setContentView(R.layout.activity_main) 23 | 24 | // login sends back a cookie 25 | findViewById