Search code examples
javatomcatjava-mesession-cookieshttpconnection

HttpConnection maintaining Session


I'm consuming some web services done in java using a Rest architecture, my client it's a mobile application that uses HttpConnection to retrieve the data. In order to control authentication and authorization I'm using cookies, managed by a @SessionScoped class, however I don't know how to make the session persist through requests. The problem basically is that I inject the Session manager in other services that are @RequestScoped, however since the session is not persisted I always retrieve differente instances for the @SessionScoped class, thus deleting all the cookies or records I had before. Looking at the request headers I noticed the cookie JSESSIONID, I think this is sent by tomcat in order to persist session, so tried already to send the same cookie in the next request, however I got no results.


Solution

  • The comments were right... to persist a session you just have to send the JSESSIONID cookie back to server in the next request, the problem in this case was that HttpConnection in JavaME only has the setRequestProperty method to include a header value, now if you set the same value two times it overwrites the last one. Since I was using a custom cookie and the JSessionID cookie, I setted them in the following way:

    connection.setRequestProperty("Cookie","sessionId="+ApplicationPreferences.getIn‌​stance().getSessionCookieHeader()); 
    connection.setRequestProperty("Cookie","JSESSIONID="+ApplicationPreferences‌​.getInstance().getJavaSessionCookieHeader());
    

    When the correct way to do it is concatenate the cookie strings and then setting a Cookie header with them all:

    String myCookies="sessionId="+ApplicationPreferences.getInstance().getSessionCookieHead‌​er()+";"+"JSESSIONID="+ApplicationPreferences.getInstance().getJavaSessionCookieHeade‌​r();