如何管理与Android应用程序会话应用程序、Android

2023-09-06 23:30:15 作者:呼吸很暧昧╯

我有我的多部分邮寄到Servlet的Andr​​oid应用程序。但我需要每5分钟一次限制呼叫。随着网络的形式,我可以使用Cookie。对于Android应用程序不会这样的。我怎样才能使它工作?

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?

推荐答案

要维护HTTP会话,你可以按照下面的方法服务器(假设你正在使用的HttpClient通讯):

To maintain http session with the server you can follow the following approach (Assuming you are using HttpClient for communication):

每当服务器启动一个新的会话它发送一个cookie名称设置Cookie 与包含可用于与服务器的会话ID的jessionid值。因此,在您code,每次你做服务器的网络电话给你,检查该cookie的响应。如果这个cookie是present然后检查是否也有jessionid。下面code,可用于检查并解析设置Cookie标头的jessionid。

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) {
    }

}

存储解析的ID在以后可以访问的一些地方。我通常在该领域我的网络经理答店jessionid创建一个静态字段。

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.

现在无论你正在网络请求时,然后设置所需的jessionid饼干为做以下code:

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);
        }

    }

使得调用HttpClient的execute方法之前调用此方法。

call this method before making call to HttpClient execute method..

注:我只用了基于Java的服务器上测试它

Note: I have tested it only with the java based server.

 
精彩推荐
图片推荐