Reputation: 800
I am developing server client application on android and i am using session on server side of application but sometimes i lost my session on server. Ps: i use https connection on server.
I am using these to hold session:
I use only https certificate:
schemeRegistry.register(new Scheme("https", sslSocketFactory, 443)); ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
I save my cookies after all http requests:
private void createSessionCookie(){
List<Cookie> cookies = httpclient.getCookieStore().getCookies();
if (! cookies.isEmpty()){
CookieSyncManager.createInstance(ctx);
CookieManager cookieManager = CookieManager.getInstance();
//sync all the cookies in the httpclient with the webview by generating cookie string
for (Cookie cookie : cookies){
Cookie sessionInfo = cookie;
String cookieString = sessionInfo.getName() + "=" + sessionInfo.getValue() + "; domain=" + sessionInfo.getDomain();
cookieManager.setCookie(UrlConstants.SERVICE_PRE_URL, cookieString);
CookieSyncManager.getInstance().sync();
}
}
}
Even though i am doing these, i lose session. Please help me to solve this problem, Thanks for any advice Best Regards.
Upvotes: 1
Views: 975
Reputation: 23498
You should not do anything with cookies manually, just create static CookieStore
somewhere, assign it to the HttpContext
, and use that context in your requests. Cookies will be saved and restored automagically.
These are your class members:
private static CookieStore cookieStore = new BasicCookieStore();
private HttpClient httpclient = new DefaultHttpClient();
private HttpPost post = new HttpPost("your url here");
And this part goes into the member function, which does the request:
HttpContext ctx = new BasicHttpContext();
ctx.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
HttpResponse result = httpclient.execute(post,ctx);
Upvotes: 3