To maintain http session with the server you can follow the following approach (Assuming you are using HttpClient for communication):
Every time server starts a new session it sends one cookie names Set-Cookie
with the value that contain the jessionid that can be used as the session ID with server. So in your code every time you make a network call to you server, check for this cookie in the response. If this cookie is present then check if it also has jessionid. following code can be used to check and parse the jessionid from the Set-Cookie header.
HttpResponse response = httpClient.execute(get);
switch (response.getStatusLine().getStatusCode()) {
case 200:
parseSessionID(response);
//process the response
break;
}
private void parseSessionID(HttpResponse response) {
try {
Header header = response.getFirstHeader("Set-Cookie");
String value = header.getValue();
if (value.contains("JSESSIONID")) {
int index = value.indexOf("JSESSIONID=");
int endIndex = value.indexOf(";", index);
String sessionID = value.substring(
index + "JSESSIONID=".length(), endIndex);
Logger.d(this, "id " + sessionID);
if (sessionID != null) {
classStaticVariable= sessionID;
}
}
} catch (Exception e) {
}
}
Store the parsed id in some place where it can be accessed later. I normally create a static field in my network manager ans store jessionid in that field.
Now when ever you are making network request then set the cookie required for jessionid as done in the following code:
private void setDefaultHeaders(HttpUriRequest httpRequest, Request request) {
if (classStaticVariable!= null) {
httpRequest.setHeader("Cookie", "JSESSIONID=" + classStaticVariable);
}
}
call this method before making call to HttpClient execute method..
Note: I have tested it only with the java based server.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…