How to manage sessions with Android Application

后端 未结 2 1415
抹茶落季
抹茶落季 2020-12-20 05:53

I have an Android application where I send Multipart post to a Servlet. But i need to restrict calls to once per 5 mins. With a web form, I can use cookies. For android appl

相关标签:
2条回答
  • 2020-12-20 06:23

    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.

    0 讨论(0)
  • 2020-12-20 06:47

    Have you tried using:

    1. SharedPreferences, the much easier one, and
    2. AccountManager
    0 讨论(0)
提交回复
热议问题