Retrofit2: how to save cookies from response












0















I need to add some authorization information from cookie in response to next requests.



It works in postman - I make authorization request, then second request, which works fine. But if I delete cookies - second request returns error and I have to do authorization request again.



But in my application this second request always returns the same error. I tried to find needed cookie by using interceptor, but I hadn't found it



val client = OkHttpClient.Builder()
.addInterceptor(OAuthInterceptor())

private class OAuthInterceptor : Interceptor {
override fun intercept(chain: Chain): Response {
val request = chain.request()
com.app.logic.toLog("${chain.proceed(request).header("set-cookie")} ") // it's not that cookie what I looking for
val headers = chain.proceed(request).headers()
headers.names().forEach {
val s = headers.get(it)
com.app.logic.toLog("$it -> $s")
}
return chain + (Session.authConsumer?.let { consumer ->
consumer.sign(request).unwrap() as Request
} ?: request)
}
}


Does anybody know what else could I try?










share|improve this question





























    0















    I need to add some authorization information from cookie in response to next requests.



    It works in postman - I make authorization request, then second request, which works fine. But if I delete cookies - second request returns error and I have to do authorization request again.



    But in my application this second request always returns the same error. I tried to find needed cookie by using interceptor, but I hadn't found it



    val client = OkHttpClient.Builder()
    .addInterceptor(OAuthInterceptor())

    private class OAuthInterceptor : Interceptor {
    override fun intercept(chain: Chain): Response {
    val request = chain.request()
    com.app.logic.toLog("${chain.proceed(request).header("set-cookie")} ") // it's not that cookie what I looking for
    val headers = chain.proceed(request).headers()
    headers.names().forEach {
    val s = headers.get(it)
    com.app.logic.toLog("$it -> $s")
    }
    return chain + (Session.authConsumer?.let { consumer ->
    consumer.sign(request).unwrap() as Request
    } ?: request)
    }
    }


    Does anybody know what else could I try?










    share|improve this question



























      0












      0








      0








      I need to add some authorization information from cookie in response to next requests.



      It works in postman - I make authorization request, then second request, which works fine. But if I delete cookies - second request returns error and I have to do authorization request again.



      But in my application this second request always returns the same error. I tried to find needed cookie by using interceptor, but I hadn't found it



      val client = OkHttpClient.Builder()
      .addInterceptor(OAuthInterceptor())

      private class OAuthInterceptor : Interceptor {
      override fun intercept(chain: Chain): Response {
      val request = chain.request()
      com.app.logic.toLog("${chain.proceed(request).header("set-cookie")} ") // it's not that cookie what I looking for
      val headers = chain.proceed(request).headers()
      headers.names().forEach {
      val s = headers.get(it)
      com.app.logic.toLog("$it -> $s")
      }
      return chain + (Session.authConsumer?.let { consumer ->
      consumer.sign(request).unwrap() as Request
      } ?: request)
      }
      }


      Does anybody know what else could I try?










      share|improve this question
















      I need to add some authorization information from cookie in response to next requests.



      It works in postman - I make authorization request, then second request, which works fine. But if I delete cookies - second request returns error and I have to do authorization request again.



      But in my application this second request always returns the same error. I tried to find needed cookie by using interceptor, but I hadn't found it



      val client = OkHttpClient.Builder()
      .addInterceptor(OAuthInterceptor())

      private class OAuthInterceptor : Interceptor {
      override fun intercept(chain: Chain): Response {
      val request = chain.request()
      com.app.logic.toLog("${chain.proceed(request).header("set-cookie")} ") // it's not that cookie what I looking for
      val headers = chain.proceed(request).headers()
      headers.names().forEach {
      val s = headers.get(it)
      com.app.logic.toLog("$it -> $s")
      }
      return chain + (Session.authConsumer?.let { consumer ->
      consumer.sign(request).unwrap() as Request
      } ?: request)
      }
      }


      Does anybody know what else could I try?







      android cookies kotlin retrofit2 okhttp






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 22 '18 at 13:06









      Hossam Hassan

      2601319




      2601319










      asked Nov 22 '18 at 12:18









      Andrey TurkovskyAndrey Turkovsky

      2,7202930




      2,7202930
























          2 Answers
          2






          active

          oldest

          votes


















          1














          You can use this this gist on how to intercept cookies when you receive them and send them back in your request in header.






          share|improve this answer
























          • Thanks, I think it can help. But in this solution I need Context and I need to use shared preferences. I've found easier way for solving this

            – Andrey Turkovsky
            Nov 26 '18 at 7:42











          • You can always use application context.

            – karandeep singh
            Nov 26 '18 at 7:43






          • 1





            Yes, I can. But I would prefer to avoid using context and prefs for this. As I said - there is another way without them

            – Andrey Turkovsky
            Nov 26 '18 at 7:45



















          0














          So, finally I've found solution for working with cookies



          val client = OkHttpClient.Builder()
          .cookieJar(UvCookieJar())

          private class UvCookieJar : CookieJar {

          private val cookies = mutableListOf<Cookie>()

          override fun saveFromResponse(url: HttpUrl, cookieList: List<Cookie>) {
          cookies.clear()
          cookies.addAll(cookieList)
          }

          override fun loadForRequest(url: HttpUrl): List<Cookie> =
          cookies
          }





          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53430866%2fretrofit2-how-to-save-cookies-from-response%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1














            You can use this this gist on how to intercept cookies when you receive them and send them back in your request in header.






            share|improve this answer
























            • Thanks, I think it can help. But in this solution I need Context and I need to use shared preferences. I've found easier way for solving this

              – Andrey Turkovsky
              Nov 26 '18 at 7:42











            • You can always use application context.

              – karandeep singh
              Nov 26 '18 at 7:43






            • 1





              Yes, I can. But I would prefer to avoid using context and prefs for this. As I said - there is another way without them

              – Andrey Turkovsky
              Nov 26 '18 at 7:45
















            1














            You can use this this gist on how to intercept cookies when you receive them and send them back in your request in header.






            share|improve this answer
























            • Thanks, I think it can help. But in this solution I need Context and I need to use shared preferences. I've found easier way for solving this

              – Andrey Turkovsky
              Nov 26 '18 at 7:42











            • You can always use application context.

              – karandeep singh
              Nov 26 '18 at 7:43






            • 1





              Yes, I can. But I would prefer to avoid using context and prefs for this. As I said - there is another way without them

              – Andrey Turkovsky
              Nov 26 '18 at 7:45














            1












            1








            1







            You can use this this gist on how to intercept cookies when you receive them and send them back in your request in header.






            share|improve this answer













            You can use this this gist on how to intercept cookies when you receive them and send them back in your request in header.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 25 '18 at 15:28









            karandeep singhkarandeep singh

            1,3611718




            1,3611718













            • Thanks, I think it can help. But in this solution I need Context and I need to use shared preferences. I've found easier way for solving this

              – Andrey Turkovsky
              Nov 26 '18 at 7:42











            • You can always use application context.

              – karandeep singh
              Nov 26 '18 at 7:43






            • 1





              Yes, I can. But I would prefer to avoid using context and prefs for this. As I said - there is another way without them

              – Andrey Turkovsky
              Nov 26 '18 at 7:45



















            • Thanks, I think it can help. But in this solution I need Context and I need to use shared preferences. I've found easier way for solving this

              – Andrey Turkovsky
              Nov 26 '18 at 7:42











            • You can always use application context.

              – karandeep singh
              Nov 26 '18 at 7:43






            • 1





              Yes, I can. But I would prefer to avoid using context and prefs for this. As I said - there is another way without them

              – Andrey Turkovsky
              Nov 26 '18 at 7:45

















            Thanks, I think it can help. But in this solution I need Context and I need to use shared preferences. I've found easier way for solving this

            – Andrey Turkovsky
            Nov 26 '18 at 7:42





            Thanks, I think it can help. But in this solution I need Context and I need to use shared preferences. I've found easier way for solving this

            – Andrey Turkovsky
            Nov 26 '18 at 7:42













            You can always use application context.

            – karandeep singh
            Nov 26 '18 at 7:43





            You can always use application context.

            – karandeep singh
            Nov 26 '18 at 7:43




            1




            1





            Yes, I can. But I would prefer to avoid using context and prefs for this. As I said - there is another way without them

            – Andrey Turkovsky
            Nov 26 '18 at 7:45





            Yes, I can. But I would prefer to avoid using context and prefs for this. As I said - there is another way without them

            – Andrey Turkovsky
            Nov 26 '18 at 7:45













            0














            So, finally I've found solution for working with cookies



            val client = OkHttpClient.Builder()
            .cookieJar(UvCookieJar())

            private class UvCookieJar : CookieJar {

            private val cookies = mutableListOf<Cookie>()

            override fun saveFromResponse(url: HttpUrl, cookieList: List<Cookie>) {
            cookies.clear()
            cookies.addAll(cookieList)
            }

            override fun loadForRequest(url: HttpUrl): List<Cookie> =
            cookies
            }





            share|improve this answer




























              0














              So, finally I've found solution for working with cookies



              val client = OkHttpClient.Builder()
              .cookieJar(UvCookieJar())

              private class UvCookieJar : CookieJar {

              private val cookies = mutableListOf<Cookie>()

              override fun saveFromResponse(url: HttpUrl, cookieList: List<Cookie>) {
              cookies.clear()
              cookies.addAll(cookieList)
              }

              override fun loadForRequest(url: HttpUrl): List<Cookie> =
              cookies
              }





              share|improve this answer


























                0












                0








                0







                So, finally I've found solution for working with cookies



                val client = OkHttpClient.Builder()
                .cookieJar(UvCookieJar())

                private class UvCookieJar : CookieJar {

                private val cookies = mutableListOf<Cookie>()

                override fun saveFromResponse(url: HttpUrl, cookieList: List<Cookie>) {
                cookies.clear()
                cookies.addAll(cookieList)
                }

                override fun loadForRequest(url: HttpUrl): List<Cookie> =
                cookies
                }





                share|improve this answer













                So, finally I've found solution for working with cookies



                val client = OkHttpClient.Builder()
                .cookieJar(UvCookieJar())

                private class UvCookieJar : CookieJar {

                private val cookies = mutableListOf<Cookie>()

                override fun saveFromResponse(url: HttpUrl, cookieList: List<Cookie>) {
                cookies.clear()
                cookies.addAll(cookieList)
                }

                override fun loadForRequest(url: HttpUrl): List<Cookie> =
                cookies
                }






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 26 '18 at 7:44









                Andrey TurkovskyAndrey Turkovsky

                2,7202930




                2,7202930






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53430866%2fretrofit2-how-to-save-cookies-from-response%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    MongoDB - Not Authorized To Execute Command

                    How to fix TextFormField cause rebuild widget in Flutter

                    in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith