【问题标题】:Android ksoap2 Session cookies managmentAndroid ksoap2 会话 cookie 管理
【发布时间】:2012-03-09 18:54:45
【问题描述】:

我的应用程序假设连接一个 Web 服务并激活他的一些功能。 首先,应用程序激活一个“登录”函数,该函数将用户名和密码作为参数,该函数在数据库中搜索用户名和密码,如果我登录或未登录,则返回我。并为我创建一个会话变量,例如:

Session["Username"] = User.Username;

Session["FullName"] = User.FullName;

还有更多...

我想激活另一个网络服务功能 - UpdateProfile 这会改变我在数据库中的个人资料值。

所以,我的应用程序有一个包含一些私有类的类(asynctasks) 每个 asynctask 都负责 web 服务中的一个功能。

例如 - 登录异步任务:

private class LoginAsyncTask extends AsyncTask<String, String, User>
{

    private String METHODNAME = "Login";
    private String SOAPACTION = "http://tempuri.org/Login";

还有更多...

在这个登录异步任务中,我像这样解析返回的 cookie:

cookies is a HashMap<String, String>();

    try
    {

        //respHeaders = trans.call(SOAPACTION, envelope, null);
        reshttpHeaders = trans.call(SOAPACTION, envelope, null);

    }
    catch (Exception e)
    {
        //connection error.
        e.printStackTrace();
        return null;
    }
   cookies.clear();
        if (reshttpHeaders!=null) {
            for (int i = 0; i < reshttpHeaders.size(); i++) {
                HeaderProperty hp = (HeaderProperty)reshttpHeaders.get(i);
                String key = hp.getKey();
                String value = hp.getValue();
                if (key!=null && value!=null) {
                    if (key.equalsIgnoreCase("set-cookie")){
                        String cookieString = value.substring(0,value.indexOf(";") );

                        cookies.put(cookieString.substring(0, cookieString.indexOf("=")),cookieString.substring(cookieString.indexOf("=")+1) );
                        break;
                    }
                }
            }

        }

然后,在另一个名为 UpdateProfileAsynctask 的异步任务中 我像这样发送这个cookie:

        List<HeaderProperty> httpHeaders = new ArrayList<HeaderProperty>();
        for (String cookie:cookies.keySet()) {
            httpHeaders.add(new HeaderProperty("Cookie", cookie + "=" + cookies.get(cookie)));
        }

        try
        {

            //trans.call(SOAPACTION, envelope, reqHeaders);
            trans.call(SOAPACTION, envelope, httpHeaders);
        }

当我尝试用 wireshark 捕获这个数据包时,我看到我得到的 cookie 是: 设置 Cookie:ASP.NET_SessionId=kmwn4l2qzc0k1anfk1du4ty1;路径=/; HttpOnly\r\n

我发送的 cookie 是: Cookie:ASP.NET_SessionId=kmwn4l2qzc0k1anfk1du4ty1\r\n

问题是网络服务不认识我(第二次请求在 20 分钟内)。

这部分代码在webservice中运行:

if (Session["Username"] == null)
    return "Cant Update profile now, Your connection seems to be timeout";

我一直收到这条消息。但有时它的工作原理很奇怪:/

谢谢。

【问题讨论】:

    标签: java android .net web-services ksoap2


    【解决方案1】:

    我在阅读您的问题后解决了我的问题,谢谢。 我的代码如下:

    HeaderProperty headerPropertySessionId = new HeaderProperty("Cookie", "key1=value1"); 列表 headerPropertyList = new ArrayList(); headerPropertyList.add(headerPropertySessionId);

    【讨论】: