牛骨文教育服务平台(让学习变的简单)
博文笔记

Android HTTP保存sessionid

创建时间:2017-09-19 投稿人: 浏览次数:806

sessionid包含在cookies里面,而cookies在header里,所以我们需要先从header里拿到cookies,然后再拿到sessionid。


下面给出保存cookies的方法:

/**
 * 保存Cookie
 *
 * @param httpResponse
 */
@SuppressWarnings("unused")
public static HashMap<String, String> SaveCookies(HttpResponse httpResponse) {
    Header[] headers = httpResponse.getHeaders("Set-Cookie");
    String headerstr = headers.toString();
    if (headers == null) {
        return null;
    } else {
        for (int i = 0; i < headers.length; i++) {
            String cookie = headers[i].getValue();
            String[] cookievalues = cookie.split(";");
            for (int j = 0; j < cookievalues.length; j++) {
                String[] keyPair = cookievalues[j].split("=");
                String key = keyPair[0].trim();
                String value = keyPair.length > 1 ? keyPair[1].trim() : "";
                CookieContiner.put(key, value);
                Log.e("CookieContiner", "SaveCookies: key=" + key + ",value=" + value);
            }
        }
        return CookieContiner;
    }
}

以上,我们就保存了header中的cookies信息。

然后我们通过以下代码拿到sessionid:

// 获取sessionid,并保存SharedPreferences
HashMap<String, String> Cookie = SaveCookies(response);
sessionId = Cookie.get("JSESSIONID");

拿到的是String哦!


那么问题来了,怎么为http请求设置sessionid呢?请看代码:

httpPost.setHeader("Cookie", "JSESSIONID=" + sessionId);


突然想到前几天有童鞋说http乱码问题,在这里说一下,乱码问题一般都是因为编码不一致造成的,由于很多编码格式不支持中文,而utf-8支持,所以大多数程序都会使用utf-8格式的编码。为http的header设置编码格式应该就是能解决:

httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");








声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。