RestTemplate client with cookies











up vote
11
down vote

favorite
5












I'm writing a simple client in Java to allow reusable use of proprietary virus scanning software accessible through a RESTful API. To upload a file for scanning the API requires a POST for Connect, followed by a POST for Publishing the file to the server. In the response to the Connect POST there are cookies set by the server which need to be present in the subsequent POST for publishing the file. I'm currently using Spring RestTemplate in my client.



My question is how do I access the cookies in the response to forward back to the server with the subsequent POST? I can see that they are present in the header that is returned but there are no methods on the ResponseEntity to access them.










share|improve this question




























    up vote
    11
    down vote

    favorite
    5












    I'm writing a simple client in Java to allow reusable use of proprietary virus scanning software accessible through a RESTful API. To upload a file for scanning the API requires a POST for Connect, followed by a POST for Publishing the file to the server. In the response to the Connect POST there are cookies set by the server which need to be present in the subsequent POST for publishing the file. I'm currently using Spring RestTemplate in my client.



    My question is how do I access the cookies in the response to forward back to the server with the subsequent POST? I can see that they are present in the header that is returned but there are no methods on the ResponseEntity to access them.










    share|improve this question


























      up vote
      11
      down vote

      favorite
      5









      up vote
      11
      down vote

      favorite
      5






      5





      I'm writing a simple client in Java to allow reusable use of proprietary virus scanning software accessible through a RESTful API. To upload a file for scanning the API requires a POST for Connect, followed by a POST for Publishing the file to the server. In the response to the Connect POST there are cookies set by the server which need to be present in the subsequent POST for publishing the file. I'm currently using Spring RestTemplate in my client.



      My question is how do I access the cookies in the response to forward back to the server with the subsequent POST? I can see that they are present in the header that is returned but there are no methods on the ResponseEntity to access them.










      share|improve this question















      I'm writing a simple client in Java to allow reusable use of proprietary virus scanning software accessible through a RESTful API. To upload a file for scanning the API requires a POST for Connect, followed by a POST for Publishing the file to the server. In the response to the Connect POST there are cookies set by the server which need to be present in the subsequent POST for publishing the file. I'm currently using Spring RestTemplate in my client.



      My question is how do I access the cookies in the response to forward back to the server with the subsequent POST? I can see that they are present in the header that is returned but there are no methods on the ResponseEntity to access them.







      java spring http cookies resttemplate






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 17 at 18:19









      Michael Lihs

      2,33642244




      2,33642244










      asked Apr 4 '14 at 4:03









      Tom

      1,51742447




      1,51742447
























          4 Answers
          4






          active

          oldest

          votes

















          up vote
          8
          down vote



          accepted










          RestTemplate has a method in which you can define Interface ResponseExtractor<T>, this interface is used to obtain the headers of the response, once you have them you could send it back using HttpEntity and added again.



           .add("Cookie", "SERVERID=c52");


          Try something like this.



          String cookieHeader = null;

          new ResponseExtractor<T>(){
          T extractData(ClientHttpResponse response) {
          response.getHeaders();
          }
          }


          Then



            HttpHeaders headers = new HttpHeaders();
          headers.add("Cookie", cookieHeader );

          ResponseEntity<byte> response = restTemplate.exchange("http://example.com/file/123",
          GET,
          new HttpEntity<String>(headers),
          byte.class);


          Also read this post






          share|improve this answer























          • So in other words I just treat them like any other header? I wasn't sure if there was a special way to handle them with the RestTemplate where they get automatically added to the subsequent responses or something.
            – Tom
            Apr 4 '14 at 13:36










          • Yes you are right and I don't think make this automatically can be achieve with the resttemplate as it is. You should take the headers and re send them, if you can achieve automatically don't forget to tell me your trick =)
            – Koitoer
            Apr 4 '14 at 16:09


















          up vote
          3
          down vote













          You need to use exchange method of RestTemplate of Java Spring framework.



          Read this tutorial: http://codeflex.co/java-rest-client-get-cookie/






          share|improve this answer






























            up vote
            2
            down vote













            Small update to handle sessions in a complete test with 'java.net.HttpCookie' Object.



            @Thanks Shedon



            import java.io.IOException;
            import java.net.HttpCookie;
            import java.net.URI;
            import java.util.ArrayList;
            import java.util.List;
            import org.springframework.http.HttpHeaders;
            import org.springframework.http.HttpMethod;
            import org.springframework.http.client.ClientHttpRequest;
            import org.springframework.http.client.ClientHttpRequestFactory;
            import org.springframework.http.client.ClientHttpResponse;
            import org.springframework.stereotype.Component;
            import org.springframework.web.client.RequestCallback;
            import org.springframework.web.client.ResponseExtractor;
            import org.springframework.web.client.RestClientException;
            import org.springframework.web.client.RestTemplate;

            /**
            * @link https://stackoverflow.com/questions/22853321/resttemplate-client-with-cookies
            */
            @Component
            public class RestTemplateWithCookies extends RestTemplate {

            private final List<HttpCookie> cookies = new ArrayList<>();

            public RestTemplateWithCookies() {
            }

            public RestTemplateWithCookies(ClientHttpRequestFactory requestFactory) {
            super(requestFactory);
            }

            public synchronized List<HttpCookie> getCoookies() {
            return cookies;
            }

            public synchronized void resetCoookies() {
            cookies.clear();
            }

            private void processHeaders(HttpHeaders headers) {
            final List<String> cooks = headers.get("Set-Cookie");
            if (cooks != null && !cooks.isEmpty()) {
            cooks.stream().map((c) -> HttpCookie.parse(c)).forEachOrdered((cook) -> {
            cook.forEach((a) -> {
            HttpCookie cookieExists = cookies.stream().filter(x -> a.getName().equals(x.getName())).findAny().orElse(null);
            if (cookieExists != null) {
            cookies.remove(cookieExists);
            }
            cookies.add(a);
            });
            });
            }
            }

            @Override
            protected <T extends Object> T doExecute(URI url, HttpMethod method, final RequestCallback requestCallback, final ResponseExtractor<T> responseExtractor) throws RestClientException {
            final List<HttpCookie> cookies = getCoookies();

            return super.doExecute(url, method, new RequestCallback() {
            @Override
            public void doWithRequest(ClientHttpRequest chr) throws IOException {
            if (cookies != null) {
            StringBuilder sb = new StringBuilder();
            for (HttpCookie cookie : cookies) {
            sb.append(cookie.getName()).append(cookie.getValue()).append(";");
            }
            chr.getHeaders().add("Cookie", sb.toString());
            }
            requestCallback.doWithRequest(chr);
            }

            }, new ResponseExtractor<T>() {
            @Override
            public T extractData(ClientHttpResponse chr) throws IOException {
            processHeaders(chr.getHeaders());
            return responseExtractor.extractData(chr);
            }
            });
            }

            }





            share|improve this answer




























              up vote
              1
              down vote













              i've wrote a simple class that extends RestTemplate and handles cookies.



              import java.io.IOException;
              import java.net.URI;
              import java.util.List;
              import org.springframework.http.HttpHeaders;
              import org.springframework.http.HttpMethod;
              import org.springframework.http.client.ClientHttpRequest;
              import org.springframework.http.client.ClientHttpRequestFactory;
              import org.springframework.http.client.ClientHttpResponse;
              import org.springframework.web.client.RequestCallback;
              import org.springframework.web.client.ResponseExtractor;
              import org.springframework.web.client.RestClientException;
              import org.springframework.web.client.RestTemplate;

              public class RestTemplateWithCookies extends RestTemplate {

              private List<String> cookies = null;

              public RestTemplateWithCookies() {
              }

              public RestTemplateWithCookies(ClientHttpRequestFactory requestFactory) {
              super(requestFactory);
              }

              private synchronized List<String> getCoookies() {
              return cookies;
              }

              private synchronized void setCoookies(List<String> cookies) {
              this.cookies = cookies;
              }

              public synchronized void resetCoookies() {
              this.cookies = null;
              }

              private void processHeaders(HttpHeaders headers) {
              final List<String> cookies = headers.get("Set-Cookie");
              if (cookies != null && !cookies.isEmpty()) {
              setCoookies(cookies);
              }
              }

              @Override
              protected <T extends Object> T doExecute(URI url, HttpMethod method, final RequestCallback requestCallback, final ResponseExtractor<T> responseExtractor) throws RestClientException {
              final List<String> cookies = getCoookies();

              return super.doExecute(url, method, new RequestCallback() {
              @Override
              public void doWithRequest(ClientHttpRequest chr) throws IOException {
              if(cookies != null) {
              for(String cookie : cookies) {
              chr.getHeaders().add("Cookie", cookie);
              }
              }
              requestCallback.doWithRequest(chr);
              }

              }, new ResponseExtractor<T>() {
              @Override
              public T extractData(ClientHttpResponse chr) throws IOException {
              processHeaders(chr.getHeaders());
              return responseExtractor.extractData(chr);
              }
              });
              }

              }





              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',
                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%2f22853321%2fresttemplate-client-with-cookies%23new-answer', 'question_page');
                }
                );

                Post as a guest















                Required, but never shown

























                4 Answers
                4






                active

                oldest

                votes








                4 Answers
                4






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes








                up vote
                8
                down vote



                accepted










                RestTemplate has a method in which you can define Interface ResponseExtractor<T>, this interface is used to obtain the headers of the response, once you have them you could send it back using HttpEntity and added again.



                 .add("Cookie", "SERVERID=c52");


                Try something like this.



                String cookieHeader = null;

                new ResponseExtractor<T>(){
                T extractData(ClientHttpResponse response) {
                response.getHeaders();
                }
                }


                Then



                  HttpHeaders headers = new HttpHeaders();
                headers.add("Cookie", cookieHeader );

                ResponseEntity<byte> response = restTemplate.exchange("http://example.com/file/123",
                GET,
                new HttpEntity<String>(headers),
                byte.class);


                Also read this post






                share|improve this answer























                • So in other words I just treat them like any other header? I wasn't sure if there was a special way to handle them with the RestTemplate where they get automatically added to the subsequent responses or something.
                  – Tom
                  Apr 4 '14 at 13:36










                • Yes you are right and I don't think make this automatically can be achieve with the resttemplate as it is. You should take the headers and re send them, if you can achieve automatically don't forget to tell me your trick =)
                  – Koitoer
                  Apr 4 '14 at 16:09















                up vote
                8
                down vote



                accepted










                RestTemplate has a method in which you can define Interface ResponseExtractor<T>, this interface is used to obtain the headers of the response, once you have them you could send it back using HttpEntity and added again.



                 .add("Cookie", "SERVERID=c52");


                Try something like this.



                String cookieHeader = null;

                new ResponseExtractor<T>(){
                T extractData(ClientHttpResponse response) {
                response.getHeaders();
                }
                }


                Then



                  HttpHeaders headers = new HttpHeaders();
                headers.add("Cookie", cookieHeader );

                ResponseEntity<byte> response = restTemplate.exchange("http://example.com/file/123",
                GET,
                new HttpEntity<String>(headers),
                byte.class);


                Also read this post






                share|improve this answer























                • So in other words I just treat them like any other header? I wasn't sure if there was a special way to handle them with the RestTemplate where they get automatically added to the subsequent responses or something.
                  – Tom
                  Apr 4 '14 at 13:36










                • Yes you are right and I don't think make this automatically can be achieve with the resttemplate as it is. You should take the headers and re send them, if you can achieve automatically don't forget to tell me your trick =)
                  – Koitoer
                  Apr 4 '14 at 16:09













                up vote
                8
                down vote



                accepted







                up vote
                8
                down vote



                accepted






                RestTemplate has a method in which you can define Interface ResponseExtractor<T>, this interface is used to obtain the headers of the response, once you have them you could send it back using HttpEntity and added again.



                 .add("Cookie", "SERVERID=c52");


                Try something like this.



                String cookieHeader = null;

                new ResponseExtractor<T>(){
                T extractData(ClientHttpResponse response) {
                response.getHeaders();
                }
                }


                Then



                  HttpHeaders headers = new HttpHeaders();
                headers.add("Cookie", cookieHeader );

                ResponseEntity<byte> response = restTemplate.exchange("http://example.com/file/123",
                GET,
                new HttpEntity<String>(headers),
                byte.class);


                Also read this post






                share|improve this answer














                RestTemplate has a method in which you can define Interface ResponseExtractor<T>, this interface is used to obtain the headers of the response, once you have them you could send it back using HttpEntity and added again.



                 .add("Cookie", "SERVERID=c52");


                Try something like this.



                String cookieHeader = null;

                new ResponseExtractor<T>(){
                T extractData(ClientHttpResponse response) {
                response.getHeaders();
                }
                }


                Then



                  HttpHeaders headers = new HttpHeaders();
                headers.add("Cookie", cookieHeader );

                ResponseEntity<byte> response = restTemplate.exchange("http://example.com/file/123",
                GET,
                new HttpEntity<String>(headers),
                byte.class);


                Also read this post







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Nov 19 at 8:18









                Michael Lihs

                2,33642244




                2,33642244










                answered Apr 4 '14 at 4:59









                Koitoer

                12k34260




                12k34260












                • So in other words I just treat them like any other header? I wasn't sure if there was a special way to handle them with the RestTemplate where they get automatically added to the subsequent responses or something.
                  – Tom
                  Apr 4 '14 at 13:36










                • Yes you are right and I don't think make this automatically can be achieve with the resttemplate as it is. You should take the headers and re send them, if you can achieve automatically don't forget to tell me your trick =)
                  – Koitoer
                  Apr 4 '14 at 16:09


















                • So in other words I just treat them like any other header? I wasn't sure if there was a special way to handle them with the RestTemplate where they get automatically added to the subsequent responses or something.
                  – Tom
                  Apr 4 '14 at 13:36










                • Yes you are right and I don't think make this automatically can be achieve with the resttemplate as it is. You should take the headers and re send them, if you can achieve automatically don't forget to tell me your trick =)
                  – Koitoer
                  Apr 4 '14 at 16:09
















                So in other words I just treat them like any other header? I wasn't sure if there was a special way to handle them with the RestTemplate where they get automatically added to the subsequent responses or something.
                – Tom
                Apr 4 '14 at 13:36




                So in other words I just treat them like any other header? I wasn't sure if there was a special way to handle them with the RestTemplate where they get automatically added to the subsequent responses or something.
                – Tom
                Apr 4 '14 at 13:36












                Yes you are right and I don't think make this automatically can be achieve with the resttemplate as it is. You should take the headers and re send them, if you can achieve automatically don't forget to tell me your trick =)
                – Koitoer
                Apr 4 '14 at 16:09




                Yes you are right and I don't think make this automatically can be achieve with the resttemplate as it is. You should take the headers and re send them, if you can achieve automatically don't forget to tell me your trick =)
                – Koitoer
                Apr 4 '14 at 16:09












                up vote
                3
                down vote













                You need to use exchange method of RestTemplate of Java Spring framework.



                Read this tutorial: http://codeflex.co/java-rest-client-get-cookie/






                share|improve this answer



























                  up vote
                  3
                  down vote













                  You need to use exchange method of RestTemplate of Java Spring framework.



                  Read this tutorial: http://codeflex.co/java-rest-client-get-cookie/






                  share|improve this answer

























                    up vote
                    3
                    down vote










                    up vote
                    3
                    down vote









                    You need to use exchange method of RestTemplate of Java Spring framework.



                    Read this tutorial: http://codeflex.co/java-rest-client-get-cookie/






                    share|improve this answer














                    You need to use exchange method of RestTemplate of Java Spring framework.



                    Read this tutorial: http://codeflex.co/java-rest-client-get-cookie/







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Sep 22 '16 at 5:54









                    Yuri

                    7381122




                    7381122










                    answered Sep 22 '16 at 5:06









                    user5495300

                    1125




                    1125






















                        up vote
                        2
                        down vote













                        Small update to handle sessions in a complete test with 'java.net.HttpCookie' Object.



                        @Thanks Shedon



                        import java.io.IOException;
                        import java.net.HttpCookie;
                        import java.net.URI;
                        import java.util.ArrayList;
                        import java.util.List;
                        import org.springframework.http.HttpHeaders;
                        import org.springframework.http.HttpMethod;
                        import org.springframework.http.client.ClientHttpRequest;
                        import org.springframework.http.client.ClientHttpRequestFactory;
                        import org.springframework.http.client.ClientHttpResponse;
                        import org.springframework.stereotype.Component;
                        import org.springframework.web.client.RequestCallback;
                        import org.springframework.web.client.ResponseExtractor;
                        import org.springframework.web.client.RestClientException;
                        import org.springframework.web.client.RestTemplate;

                        /**
                        * @link https://stackoverflow.com/questions/22853321/resttemplate-client-with-cookies
                        */
                        @Component
                        public class RestTemplateWithCookies extends RestTemplate {

                        private final List<HttpCookie> cookies = new ArrayList<>();

                        public RestTemplateWithCookies() {
                        }

                        public RestTemplateWithCookies(ClientHttpRequestFactory requestFactory) {
                        super(requestFactory);
                        }

                        public synchronized List<HttpCookie> getCoookies() {
                        return cookies;
                        }

                        public synchronized void resetCoookies() {
                        cookies.clear();
                        }

                        private void processHeaders(HttpHeaders headers) {
                        final List<String> cooks = headers.get("Set-Cookie");
                        if (cooks != null && !cooks.isEmpty()) {
                        cooks.stream().map((c) -> HttpCookie.parse(c)).forEachOrdered((cook) -> {
                        cook.forEach((a) -> {
                        HttpCookie cookieExists = cookies.stream().filter(x -> a.getName().equals(x.getName())).findAny().orElse(null);
                        if (cookieExists != null) {
                        cookies.remove(cookieExists);
                        }
                        cookies.add(a);
                        });
                        });
                        }
                        }

                        @Override
                        protected <T extends Object> T doExecute(URI url, HttpMethod method, final RequestCallback requestCallback, final ResponseExtractor<T> responseExtractor) throws RestClientException {
                        final List<HttpCookie> cookies = getCoookies();

                        return super.doExecute(url, method, new RequestCallback() {
                        @Override
                        public void doWithRequest(ClientHttpRequest chr) throws IOException {
                        if (cookies != null) {
                        StringBuilder sb = new StringBuilder();
                        for (HttpCookie cookie : cookies) {
                        sb.append(cookie.getName()).append(cookie.getValue()).append(";");
                        }
                        chr.getHeaders().add("Cookie", sb.toString());
                        }
                        requestCallback.doWithRequest(chr);
                        }

                        }, new ResponseExtractor<T>() {
                        @Override
                        public T extractData(ClientHttpResponse chr) throws IOException {
                        processHeaders(chr.getHeaders());
                        return responseExtractor.extractData(chr);
                        }
                        });
                        }

                        }





                        share|improve this answer

























                          up vote
                          2
                          down vote













                          Small update to handle sessions in a complete test with 'java.net.HttpCookie' Object.



                          @Thanks Shedon



                          import java.io.IOException;
                          import java.net.HttpCookie;
                          import java.net.URI;
                          import java.util.ArrayList;
                          import java.util.List;
                          import org.springframework.http.HttpHeaders;
                          import org.springframework.http.HttpMethod;
                          import org.springframework.http.client.ClientHttpRequest;
                          import org.springframework.http.client.ClientHttpRequestFactory;
                          import org.springframework.http.client.ClientHttpResponse;
                          import org.springframework.stereotype.Component;
                          import org.springframework.web.client.RequestCallback;
                          import org.springframework.web.client.ResponseExtractor;
                          import org.springframework.web.client.RestClientException;
                          import org.springframework.web.client.RestTemplate;

                          /**
                          * @link https://stackoverflow.com/questions/22853321/resttemplate-client-with-cookies
                          */
                          @Component
                          public class RestTemplateWithCookies extends RestTemplate {

                          private final List<HttpCookie> cookies = new ArrayList<>();

                          public RestTemplateWithCookies() {
                          }

                          public RestTemplateWithCookies(ClientHttpRequestFactory requestFactory) {
                          super(requestFactory);
                          }

                          public synchronized List<HttpCookie> getCoookies() {
                          return cookies;
                          }

                          public synchronized void resetCoookies() {
                          cookies.clear();
                          }

                          private void processHeaders(HttpHeaders headers) {
                          final List<String> cooks = headers.get("Set-Cookie");
                          if (cooks != null && !cooks.isEmpty()) {
                          cooks.stream().map((c) -> HttpCookie.parse(c)).forEachOrdered((cook) -> {
                          cook.forEach((a) -> {
                          HttpCookie cookieExists = cookies.stream().filter(x -> a.getName().equals(x.getName())).findAny().orElse(null);
                          if (cookieExists != null) {
                          cookies.remove(cookieExists);
                          }
                          cookies.add(a);
                          });
                          });
                          }
                          }

                          @Override
                          protected <T extends Object> T doExecute(URI url, HttpMethod method, final RequestCallback requestCallback, final ResponseExtractor<T> responseExtractor) throws RestClientException {
                          final List<HttpCookie> cookies = getCoookies();

                          return super.doExecute(url, method, new RequestCallback() {
                          @Override
                          public void doWithRequest(ClientHttpRequest chr) throws IOException {
                          if (cookies != null) {
                          StringBuilder sb = new StringBuilder();
                          for (HttpCookie cookie : cookies) {
                          sb.append(cookie.getName()).append(cookie.getValue()).append(";");
                          }
                          chr.getHeaders().add("Cookie", sb.toString());
                          }
                          requestCallback.doWithRequest(chr);
                          }

                          }, new ResponseExtractor<T>() {
                          @Override
                          public T extractData(ClientHttpResponse chr) throws IOException {
                          processHeaders(chr.getHeaders());
                          return responseExtractor.extractData(chr);
                          }
                          });
                          }

                          }





                          share|improve this answer























                            up vote
                            2
                            down vote










                            up vote
                            2
                            down vote









                            Small update to handle sessions in a complete test with 'java.net.HttpCookie' Object.



                            @Thanks Shedon



                            import java.io.IOException;
                            import java.net.HttpCookie;
                            import java.net.URI;
                            import java.util.ArrayList;
                            import java.util.List;
                            import org.springframework.http.HttpHeaders;
                            import org.springframework.http.HttpMethod;
                            import org.springframework.http.client.ClientHttpRequest;
                            import org.springframework.http.client.ClientHttpRequestFactory;
                            import org.springframework.http.client.ClientHttpResponse;
                            import org.springframework.stereotype.Component;
                            import org.springframework.web.client.RequestCallback;
                            import org.springframework.web.client.ResponseExtractor;
                            import org.springframework.web.client.RestClientException;
                            import org.springframework.web.client.RestTemplate;

                            /**
                            * @link https://stackoverflow.com/questions/22853321/resttemplate-client-with-cookies
                            */
                            @Component
                            public class RestTemplateWithCookies extends RestTemplate {

                            private final List<HttpCookie> cookies = new ArrayList<>();

                            public RestTemplateWithCookies() {
                            }

                            public RestTemplateWithCookies(ClientHttpRequestFactory requestFactory) {
                            super(requestFactory);
                            }

                            public synchronized List<HttpCookie> getCoookies() {
                            return cookies;
                            }

                            public synchronized void resetCoookies() {
                            cookies.clear();
                            }

                            private void processHeaders(HttpHeaders headers) {
                            final List<String> cooks = headers.get("Set-Cookie");
                            if (cooks != null && !cooks.isEmpty()) {
                            cooks.stream().map((c) -> HttpCookie.parse(c)).forEachOrdered((cook) -> {
                            cook.forEach((a) -> {
                            HttpCookie cookieExists = cookies.stream().filter(x -> a.getName().equals(x.getName())).findAny().orElse(null);
                            if (cookieExists != null) {
                            cookies.remove(cookieExists);
                            }
                            cookies.add(a);
                            });
                            });
                            }
                            }

                            @Override
                            protected <T extends Object> T doExecute(URI url, HttpMethod method, final RequestCallback requestCallback, final ResponseExtractor<T> responseExtractor) throws RestClientException {
                            final List<HttpCookie> cookies = getCoookies();

                            return super.doExecute(url, method, new RequestCallback() {
                            @Override
                            public void doWithRequest(ClientHttpRequest chr) throws IOException {
                            if (cookies != null) {
                            StringBuilder sb = new StringBuilder();
                            for (HttpCookie cookie : cookies) {
                            sb.append(cookie.getName()).append(cookie.getValue()).append(";");
                            }
                            chr.getHeaders().add("Cookie", sb.toString());
                            }
                            requestCallback.doWithRequest(chr);
                            }

                            }, new ResponseExtractor<T>() {
                            @Override
                            public T extractData(ClientHttpResponse chr) throws IOException {
                            processHeaders(chr.getHeaders());
                            return responseExtractor.extractData(chr);
                            }
                            });
                            }

                            }





                            share|improve this answer












                            Small update to handle sessions in a complete test with 'java.net.HttpCookie' Object.



                            @Thanks Shedon



                            import java.io.IOException;
                            import java.net.HttpCookie;
                            import java.net.URI;
                            import java.util.ArrayList;
                            import java.util.List;
                            import org.springframework.http.HttpHeaders;
                            import org.springframework.http.HttpMethod;
                            import org.springframework.http.client.ClientHttpRequest;
                            import org.springframework.http.client.ClientHttpRequestFactory;
                            import org.springframework.http.client.ClientHttpResponse;
                            import org.springframework.stereotype.Component;
                            import org.springframework.web.client.RequestCallback;
                            import org.springframework.web.client.ResponseExtractor;
                            import org.springframework.web.client.RestClientException;
                            import org.springframework.web.client.RestTemplate;

                            /**
                            * @link https://stackoverflow.com/questions/22853321/resttemplate-client-with-cookies
                            */
                            @Component
                            public class RestTemplateWithCookies extends RestTemplate {

                            private final List<HttpCookie> cookies = new ArrayList<>();

                            public RestTemplateWithCookies() {
                            }

                            public RestTemplateWithCookies(ClientHttpRequestFactory requestFactory) {
                            super(requestFactory);
                            }

                            public synchronized List<HttpCookie> getCoookies() {
                            return cookies;
                            }

                            public synchronized void resetCoookies() {
                            cookies.clear();
                            }

                            private void processHeaders(HttpHeaders headers) {
                            final List<String> cooks = headers.get("Set-Cookie");
                            if (cooks != null && !cooks.isEmpty()) {
                            cooks.stream().map((c) -> HttpCookie.parse(c)).forEachOrdered((cook) -> {
                            cook.forEach((a) -> {
                            HttpCookie cookieExists = cookies.stream().filter(x -> a.getName().equals(x.getName())).findAny().orElse(null);
                            if (cookieExists != null) {
                            cookies.remove(cookieExists);
                            }
                            cookies.add(a);
                            });
                            });
                            }
                            }

                            @Override
                            protected <T extends Object> T doExecute(URI url, HttpMethod method, final RequestCallback requestCallback, final ResponseExtractor<T> responseExtractor) throws RestClientException {
                            final List<HttpCookie> cookies = getCoookies();

                            return super.doExecute(url, method, new RequestCallback() {
                            @Override
                            public void doWithRequest(ClientHttpRequest chr) throws IOException {
                            if (cookies != null) {
                            StringBuilder sb = new StringBuilder();
                            for (HttpCookie cookie : cookies) {
                            sb.append(cookie.getName()).append(cookie.getValue()).append(";");
                            }
                            chr.getHeaders().add("Cookie", sb.toString());
                            }
                            requestCallback.doWithRequest(chr);
                            }

                            }, new ResponseExtractor<T>() {
                            @Override
                            public T extractData(ClientHttpResponse chr) throws IOException {
                            processHeaders(chr.getHeaders());
                            return responseExtractor.extractData(chr);
                            }
                            });
                            }

                            }






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Sep 13 '17 at 19:35









                            GerardNorton

                            211




                            211






















                                up vote
                                1
                                down vote













                                i've wrote a simple class that extends RestTemplate and handles cookies.



                                import java.io.IOException;
                                import java.net.URI;
                                import java.util.List;
                                import org.springframework.http.HttpHeaders;
                                import org.springframework.http.HttpMethod;
                                import org.springframework.http.client.ClientHttpRequest;
                                import org.springframework.http.client.ClientHttpRequestFactory;
                                import org.springframework.http.client.ClientHttpResponse;
                                import org.springframework.web.client.RequestCallback;
                                import org.springframework.web.client.ResponseExtractor;
                                import org.springframework.web.client.RestClientException;
                                import org.springframework.web.client.RestTemplate;

                                public class RestTemplateWithCookies extends RestTemplate {

                                private List<String> cookies = null;

                                public RestTemplateWithCookies() {
                                }

                                public RestTemplateWithCookies(ClientHttpRequestFactory requestFactory) {
                                super(requestFactory);
                                }

                                private synchronized List<String> getCoookies() {
                                return cookies;
                                }

                                private synchronized void setCoookies(List<String> cookies) {
                                this.cookies = cookies;
                                }

                                public synchronized void resetCoookies() {
                                this.cookies = null;
                                }

                                private void processHeaders(HttpHeaders headers) {
                                final List<String> cookies = headers.get("Set-Cookie");
                                if (cookies != null && !cookies.isEmpty()) {
                                setCoookies(cookies);
                                }
                                }

                                @Override
                                protected <T extends Object> T doExecute(URI url, HttpMethod method, final RequestCallback requestCallback, final ResponseExtractor<T> responseExtractor) throws RestClientException {
                                final List<String> cookies = getCoookies();

                                return super.doExecute(url, method, new RequestCallback() {
                                @Override
                                public void doWithRequest(ClientHttpRequest chr) throws IOException {
                                if(cookies != null) {
                                for(String cookie : cookies) {
                                chr.getHeaders().add("Cookie", cookie);
                                }
                                }
                                requestCallback.doWithRequest(chr);
                                }

                                }, new ResponseExtractor<T>() {
                                @Override
                                public T extractData(ClientHttpResponse chr) throws IOException {
                                processHeaders(chr.getHeaders());
                                return responseExtractor.extractData(chr);
                                }
                                });
                                }

                                }





                                share|improve this answer

























                                  up vote
                                  1
                                  down vote













                                  i've wrote a simple class that extends RestTemplate and handles cookies.



                                  import java.io.IOException;
                                  import java.net.URI;
                                  import java.util.List;
                                  import org.springframework.http.HttpHeaders;
                                  import org.springframework.http.HttpMethod;
                                  import org.springframework.http.client.ClientHttpRequest;
                                  import org.springframework.http.client.ClientHttpRequestFactory;
                                  import org.springframework.http.client.ClientHttpResponse;
                                  import org.springframework.web.client.RequestCallback;
                                  import org.springframework.web.client.ResponseExtractor;
                                  import org.springframework.web.client.RestClientException;
                                  import org.springframework.web.client.RestTemplate;

                                  public class RestTemplateWithCookies extends RestTemplate {

                                  private List<String> cookies = null;

                                  public RestTemplateWithCookies() {
                                  }

                                  public RestTemplateWithCookies(ClientHttpRequestFactory requestFactory) {
                                  super(requestFactory);
                                  }

                                  private synchronized List<String> getCoookies() {
                                  return cookies;
                                  }

                                  private synchronized void setCoookies(List<String> cookies) {
                                  this.cookies = cookies;
                                  }

                                  public synchronized void resetCoookies() {
                                  this.cookies = null;
                                  }

                                  private void processHeaders(HttpHeaders headers) {
                                  final List<String> cookies = headers.get("Set-Cookie");
                                  if (cookies != null && !cookies.isEmpty()) {
                                  setCoookies(cookies);
                                  }
                                  }

                                  @Override
                                  protected <T extends Object> T doExecute(URI url, HttpMethod method, final RequestCallback requestCallback, final ResponseExtractor<T> responseExtractor) throws RestClientException {
                                  final List<String> cookies = getCoookies();

                                  return super.doExecute(url, method, new RequestCallback() {
                                  @Override
                                  public void doWithRequest(ClientHttpRequest chr) throws IOException {
                                  if(cookies != null) {
                                  for(String cookie : cookies) {
                                  chr.getHeaders().add("Cookie", cookie);
                                  }
                                  }
                                  requestCallback.doWithRequest(chr);
                                  }

                                  }, new ResponseExtractor<T>() {
                                  @Override
                                  public T extractData(ClientHttpResponse chr) throws IOException {
                                  processHeaders(chr.getHeaders());
                                  return responseExtractor.extractData(chr);
                                  }
                                  });
                                  }

                                  }





                                  share|improve this answer























                                    up vote
                                    1
                                    down vote










                                    up vote
                                    1
                                    down vote









                                    i've wrote a simple class that extends RestTemplate and handles cookies.



                                    import java.io.IOException;
                                    import java.net.URI;
                                    import java.util.List;
                                    import org.springframework.http.HttpHeaders;
                                    import org.springframework.http.HttpMethod;
                                    import org.springframework.http.client.ClientHttpRequest;
                                    import org.springframework.http.client.ClientHttpRequestFactory;
                                    import org.springframework.http.client.ClientHttpResponse;
                                    import org.springframework.web.client.RequestCallback;
                                    import org.springframework.web.client.ResponseExtractor;
                                    import org.springframework.web.client.RestClientException;
                                    import org.springframework.web.client.RestTemplate;

                                    public class RestTemplateWithCookies extends RestTemplate {

                                    private List<String> cookies = null;

                                    public RestTemplateWithCookies() {
                                    }

                                    public RestTemplateWithCookies(ClientHttpRequestFactory requestFactory) {
                                    super(requestFactory);
                                    }

                                    private synchronized List<String> getCoookies() {
                                    return cookies;
                                    }

                                    private synchronized void setCoookies(List<String> cookies) {
                                    this.cookies = cookies;
                                    }

                                    public synchronized void resetCoookies() {
                                    this.cookies = null;
                                    }

                                    private void processHeaders(HttpHeaders headers) {
                                    final List<String> cookies = headers.get("Set-Cookie");
                                    if (cookies != null && !cookies.isEmpty()) {
                                    setCoookies(cookies);
                                    }
                                    }

                                    @Override
                                    protected <T extends Object> T doExecute(URI url, HttpMethod method, final RequestCallback requestCallback, final ResponseExtractor<T> responseExtractor) throws RestClientException {
                                    final List<String> cookies = getCoookies();

                                    return super.doExecute(url, method, new RequestCallback() {
                                    @Override
                                    public void doWithRequest(ClientHttpRequest chr) throws IOException {
                                    if(cookies != null) {
                                    for(String cookie : cookies) {
                                    chr.getHeaders().add("Cookie", cookie);
                                    }
                                    }
                                    requestCallback.doWithRequest(chr);
                                    }

                                    }, new ResponseExtractor<T>() {
                                    @Override
                                    public T extractData(ClientHttpResponse chr) throws IOException {
                                    processHeaders(chr.getHeaders());
                                    return responseExtractor.extractData(chr);
                                    }
                                    });
                                    }

                                    }





                                    share|improve this answer












                                    i've wrote a simple class that extends RestTemplate and handles cookies.



                                    import java.io.IOException;
                                    import java.net.URI;
                                    import java.util.List;
                                    import org.springframework.http.HttpHeaders;
                                    import org.springframework.http.HttpMethod;
                                    import org.springframework.http.client.ClientHttpRequest;
                                    import org.springframework.http.client.ClientHttpRequestFactory;
                                    import org.springframework.http.client.ClientHttpResponse;
                                    import org.springframework.web.client.RequestCallback;
                                    import org.springframework.web.client.ResponseExtractor;
                                    import org.springframework.web.client.RestClientException;
                                    import org.springframework.web.client.RestTemplate;

                                    public class RestTemplateWithCookies extends RestTemplate {

                                    private List<String> cookies = null;

                                    public RestTemplateWithCookies() {
                                    }

                                    public RestTemplateWithCookies(ClientHttpRequestFactory requestFactory) {
                                    super(requestFactory);
                                    }

                                    private synchronized List<String> getCoookies() {
                                    return cookies;
                                    }

                                    private synchronized void setCoookies(List<String> cookies) {
                                    this.cookies = cookies;
                                    }

                                    public synchronized void resetCoookies() {
                                    this.cookies = null;
                                    }

                                    private void processHeaders(HttpHeaders headers) {
                                    final List<String> cookies = headers.get("Set-Cookie");
                                    if (cookies != null && !cookies.isEmpty()) {
                                    setCoookies(cookies);
                                    }
                                    }

                                    @Override
                                    protected <T extends Object> T doExecute(URI url, HttpMethod method, final RequestCallback requestCallback, final ResponseExtractor<T> responseExtractor) throws RestClientException {
                                    final List<String> cookies = getCoookies();

                                    return super.doExecute(url, method, new RequestCallback() {
                                    @Override
                                    public void doWithRequest(ClientHttpRequest chr) throws IOException {
                                    if(cookies != null) {
                                    for(String cookie : cookies) {
                                    chr.getHeaders().add("Cookie", cookie);
                                    }
                                    }
                                    requestCallback.doWithRequest(chr);
                                    }

                                    }, new ResponseExtractor<T>() {
                                    @Override
                                    public T extractData(ClientHttpResponse chr) throws IOException {
                                    processHeaders(chr.getHeaders());
                                    return responseExtractor.extractData(chr);
                                    }
                                    });
                                    }

                                    }






                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Mar 13 '17 at 8:19









                                    Shedon

                                    8018




                                    8018






























                                        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.





                                        Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                        Please pay close attention to the following guidance:


                                        • 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%2f22853321%2fresttemplate-client-with-cookies%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

                                        Costa Masnaga

                                        Fotorealismo

                                        Sidney Franklin