Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
427 views
in Technique[技术] by (71.8m points)

cookies - How to manage sessions with Android Application

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 application it does not work that way. How can I make it work?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...