Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7048333
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T02:52:46+00:00 2026-05-28T02:52:46+00:00

I need use cookies on an https connection from an android native app. I

  • 0

I need use cookies on an https connection from an android native app.
I am using RestTemplate.

Checking other threads
(eg. Setting Security cookie using RestTemplate)
I was able to handle cookies within an http connection:

restTemplate.setRequestFactory(new YourClientHttpRequestFactory());

where YourClientHttpRequestFactory extends SimpleClientHttpRequestFactory

this works fine on http but not on https.

On the other hand I was able to sort out the https problem of Android trusting the SSL certificate:

restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory(HttpUtils.getNewHttpClient()));

where HttpUtils is described here:
http://www.makeurownrules.com/secure-rest-web-service-mobile-application-android.html

My problem is that I need to use a single implementation of ClientHttpRequestFactory.
So I have 3 options:

1) find a way to handle https using SimpleClientHttpRequestFactory

2) find a way to handle cookies using HttpComponentsClientHttpRequestFactory

3) use another approach

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T02:52:46+00:00Added an answer on May 28, 2026 at 2:52 am

    I had the same problem. Here is my solution:

    First, I handled SSL the same way you did (I used Bob Lee’s method).

    Cookies are a different story. The way I’ve handled cookies in the past without RestTemplate (i.e. just using Apache’s HttpClient class directly) is to pass an instance of HttpContext into HttpClient’s execute method. Let’s take a step back…

    HttpClient has a number of overloaded execute methods, one of which is:

    execute(HttpUriRequest request, HttpContext context)
    

    The instance of HttpContext can have a reference to a CookieStore. When you create an instance of HttpContext, provide a CookieStore (either a new one, or one you saved from a previous request):

        private HttpContext createHttpContext() {
    
        CookieStore cookieStore = (CookieStore) StaticCacheHelper.retrieveObjectFromCache(COOKIE_STORE);
        if (cookieStore == null) {
            Log.d(getClass().getSimpleName(), "Creating new instance of a CookieStore");
            // Create a local instance of cookie store
            cookieStore = new BasicCookieStore();
        } 
    
        // Create local HTTP context
        HttpContext localContext = new BasicHttpContext();
        // Bind custom cookie store to the local context
        localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
        return localContext;
    }
    

    Of course, you can add cookies to the instance of CookieStore before sending the request if you like. Now when you call the execute method, use that instance of HttpContext:

    HttpResponse response = httpClient.execute(httpRequester, localContext);
    

    (where httpRequester is an instance of HttpPost, HttpGet, etc.)

    If you need to resend any cookies on subsequent requests, make sure you store the cookies somewhere:

    StaticCacheHelper.storeObjectInCache(COOKIE_STORE, localContext.getAttribute(ClientContext.COOKIE_STORE), MAX_MILLISECONDS_TO_LIVE_IN_CACHE);
    

    The StaticCacheHelper class that is used in this code is just a custom class that can store data in a static Map:

    public class StaticCacheHelper {
    
    private static final int TIME_TO_LIVE = 43200000; // 12 hours
    
    private static Map<String, Element> cacheMap = new HashMap<String, Element>();
    
    /**
     * Retrieves an item from the cache. If found, the method compares
     * the object's expiration date to the current time and only returns
     * the object if the expiration date has not passed.
     * 
     * @param cacheKey
     * @return
     */
    public static Object retrieveObjectFromCache(String cacheKey) {
        Element e = cacheMap.get(cacheKey);
        Object o = null;
        if (e != null) {
            Date now = new Date();
            if (e.getExpirationDate().after(now)) {
                o = e.getObject();
            } else {
                removeCacheItem(cacheKey);
            }
        }
        return o;
    }
    
    /**
     * Stores an object in the cache, wrapped by an Element object.
     * The Element object has an expiration date, which will be set to 
     * now + this class' TIME_TO_LIVE setting.
     * 
     * @param cacheKey
     * @param object
     */
    public static void storeObjectInCache(String cacheKey, Object object) {
        Date expirationDate = new Date(System.currentTimeMillis() + TIME_TO_LIVE);
        Element e = new Element(object, expirationDate);
        cacheMap.put(cacheKey, e);
    }
    
    /**
     * Stores an object in the cache, wrapped by an Element object.
     * The Element object has an expiration date, which will be set to 
     * now + the timeToLiveInMilliseconds value that is passed into the method.
     * 
     * @param cacheKey
     * @param object
     * @param timeToLiveInMilliseconds
     */
    public static void storeObjectInCache(String cacheKey, Object object, int timeToLiveInMilliseconds) {
        Date expirationDate = new Date(System.currentTimeMillis() + timeToLiveInMilliseconds);
        Element e = new Element(object, expirationDate);
        cacheMap.put(cacheKey, e);
    }
    
    public static void removeCacheItem(String cacheKey) {
        cacheMap.remove(cacheKey);
    }
    
    public static void clearCache() {
        cacheMap.clear();
    }
    
    static class Element {
    
        private Object object;
        private Date expirationDate;
    
        /**
         * @param object
         * @param key
         * @param expirationDate
         */
        private Element(Object object, Date expirationDate) {
            super();
            this.object = object;
            this.expirationDate = expirationDate;
        }
        /**
         * @return the object
         */
        public Object getObject() {
            return object;
        }
        /**
         * @param object the object to set
         */
        public void setObject(Object object) {
            this.object = object;
        }
        /**
         * @return the expirationDate
         */
        public Date getExpirationDate() {
            return expirationDate;
        }
        /**
         * @param expirationDate the expirationDate to set
         */
        public void setExpirationDate(Date expirationDate) {
            this.expirationDate = expirationDate;
        }
    }
    }
    

    BUT!!!! As of 01/2012 The RestTemplate in Spring Android doesn’t give you access to add an HttpContext to the execution of the request!! This is being fixed in Spring Framework 3.1.0.RELEASE and that fix is scheduled to be migrated into Spring Android 1.0.0.RC1.

    So, when we get Spring Android 1.0.0.RC1, we should be able to add the context as described in the above example. Until then, we have to add/pull the cookies from the request/response headers using a ClientHttpRequestInterceptor.

    public class MyClientHttpRequestInterceptor implements
        ClientHttpRequestInterceptor {
    
    private static final String SET_COOKIE = "set-cookie";
    private static final String COOKIE = "cookie";
    private static final String COOKIE_STORE = "cookieStore";
    
    /* (non-Javadoc)
     * @see org.springframework.http.client.ClientHttpRequestInterceptor#intercept(org.springframework.http.HttpRequest, byte[], org.springframework.http.client.ClientHttpRequestExecution)
     */
    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] byteArray,
            ClientHttpRequestExecution execution) throws IOException {
    
        Log.d(getClass().getSimpleName(), ">>> entering intercept");
        List<String> cookies = request.getHeaders().get(COOKIE);
        // if the header doesn't exist, add any existing, saved cookies
        if (cookies == null) {
            List<String> cookieStore = (List<String>) StaticCacheHelper.retrieveObjectFromCache(COOKIE_STORE);
            // if we have stored cookies, add them to the headers
            if (cookieStore != null) {
                for (String cookie : cookieStore) {
                    request.getHeaders().add(COOKIE, cookie);
                }
            }
        }
        // execute the request
        ClientHttpResponse response = execution.execute(request, byteArray);
        // pull any cookies off and store them
        cookies = response.getHeaders().get(SET_COOKIE);
        if (cookies != null) {
            for (String cookie : cookies) {
                Log.d(getClass().getSimpleName(), ">>> response cookie = " + cookie);
            }
            StaticCacheHelper.storeObjectInCache(COOKIE_STORE, cookies);
        }
        Log.d(getClass().getSimpleName(), ">>> leaving intercept");
        return response;
    }
    
    }
    

    The intercepter intercepts the request, looks in the cache to see if there are any cookies to add to the request, then executes the request, then pulls any cookies off the response and stores them for future use.

    Add the interceptor to the request template:

    restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory(HttpClientHelper.createDefaultHttpClient(GET_SERVICE_URL)));
    ClientHttpRequestInterceptor[] interceptors = {new MyClientHttpRequestInterceptor()};
    restTemplate.setInterceptors(interceptors);
    

    And there you go! I’ve tested that and it works. That should hold you over until Spring Android 1.0.0.RC1 when we can use the HttpContext directly with RestTemplate.

    Hopes this helps others!!

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I need to use NSImage which appears need to be imported from <AppKit/AppKit.h> .
I need to use sendmail from Macs in an office. At the moment, I
I need to execute parallel HTTP requests using Libcurl. From what I understand I
Need to use own imaged markers instead built-in pins. I have several questions. 1.
I need to use sed to convert all occurences of ##XXX## to ${XXX} .
I need to use an alias in the WHERE clause, but It keeps telling
I need to use a many to many relationship in my project and since
I need to use a byte array as a profile property in a website.
I need to use a datetime.strptime on the text which looks like follows. Some
I need to use the ReSharper Unit Test Runner to run my MSTest Unit

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.