当前位置: 代码迷 >> Android >> cookie持久化保存的有关问题
  详细解决方案

cookie持久化保存的有关问题

热度:66   发布时间:2016-04-28 03:39:02.0
cookie持久化保存的问题
最近在做一个项目,先登录到服务器,获取cookie,再次访问的时候通过这个cookie访问,但是存过cookie之后下次访问服务器的时候,一直返回login first。代码如下,一个是登录的方法,一个是登录时附上cookie的方法。哪位前辈能指导下~ 感激不尽!

// 处理Login的访问
@SuppressWarnings({ "rawtypes", "unchecked" })
public static String doLoginPost(String urlAddress, List params,
ApplicationUtils app, SharedPreferences sp) {
HttpPost httpPost = new HttpPost(urlAddress);

HttpEntity he;
try {
he = new UrlEncodedFormEntity(params, "utf-8");
httpPost.setEntity(he);

} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}

DefaultHttpClient hc = new DefaultHttpClient();
try {
HttpResponse ht = hc.execute(httpPost);
// app.setCookies(hc.getCookieStore());

List<Cookie> cookies = hc.getCookieStore().getCookies();
System.out.println("cookies = " + hc.getCookieStore().getCookies());
if (cookies.isEmpty()) {
System.out.println("cookies is none");
} else {
for (int i = 0; i < cookies.size(); i++) {
System.out.println(cookies.get(i).getName() + "="
+ cookies.get(i).getValue());
System.out.println(cookies.size());
}
// 牬?乩吹腸ookie只包含两个值
Editor ed = sp.edit();
ed.putString("cookie_token", cookies.get(0).toString());
ed.putString("cookie_sessionid", cookies.get(1).toString());
ed.commit();

}

// 连接成功
if (ht.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity het = ht.getEntity();
InputStream is = het.getContent();
BufferedReader br = new BufferedReader(
new InputStreamReader(is));
String response = "";
String readLine = null;
while ((readLine = br.readLine()) != null) {
// response = br.readLine();
response = response + readLine;
}
is.close();
br.close();

// String str = EntityUtils.toString(he);
System.out.println("response" + response);
return response;
} else {
return "error";
}
} catch (ClientProtocolException e) {
e.printStackTrace();
return "exception";
} catch (IOException e) {
e.printStackTrace();
return "exception";
}
}

// 附加cookie的访问
@SuppressWarnings({ "rawtypes", "unchecked" })
public static String doCookiePost(String urlAddress, List params,
ApplicationUtils app, SharedPreferences sp) {
HttpPost httpPost = new HttpPost(urlAddress);

httpPost.setHeader("cookie",
"sessionid = " + sp.getString("cookie_sessionid", "") + ";"
+ "csrftoken = " + sp.getString("cookie_token", ""));
// httpPost.setHeader("cookie",
// "sessionid = " + sp.getString("cookie_sessionid", ""));
System.out
.println("cookie_token = " + sp.getString("cookie_token", ""));
System.out.println("cookie_sessionid = "
+ sp.getString("cookie_sessionid", ""));
System.out.println("sessionid =" + sp.getString("cookie_sessionid", "")
+ ";" + "csrftoken = " + sp.getString("cookie_token", ""));

HttpEntity he;
try {
he = new UrlEncodedFormEntity(params, "utf-8");
httpPost.setEntity(he);

} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}

DefaultHttpClient hc = new DefaultHttpClient();
// hc.setCookieStore(app.getCookies());
try {
// 得到服务器端的响应
HttpResponse ht = hc.execute(httpPost);

// 连接成功
if (ht.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity het = ht.getEntity();
InputStream is = het.getContent();
BufferedReader br = new BufferedReader(
new InputStreamReader(is));
String response = "";
String readLine = null;
while ((readLine = br.readLine()) != null) {
// response = br.readLine();
response = response + readLine;
}
is.close();
br.close();

// String str = EntityUtils.toString(he);
System.out.println("response" + response);
return response;
} else {
return "error";
}
} catch (ClientProtocolException e) {
e.printStackTrace();
return "exception";
} catch (IOException e) {
e.printStackTrace();
return "exception";
}
}

------解决思路----------------------
存读cookies的方法
/**
 * 将cookies 以StringBuffer类型保存到 SharedPreferences里
 * 
 * @param sb
 */
private static void SaveCookies(StringBuffer sb) {
SharedPreferences settings = context.getSharedPreferences("sessionId",
0);
SharedPreferences.Editor editor = settings.edit();
String cookies = sb.toString();
editor.putString("cookies", cookies);
editor.commit();
}

/** 从SharedPreferences读取cookies **/
private static String LoadCookies() {
SharedPreferences settings = context.getSharedPreferences("sessionId",
0);
String cookies = settings.getString("cookies", "");
if (!"".equals(cookies)) {
return cookies;
}
return "";
}


请求需要存下cookies的时候
HttpPost hp = new HttpPost(url);
if (values != null) {
hp.setEntity(new UrlEncodedFormEntity(values, HTTP.UTF_8));
}
HttpClient client = getHttpClient();

HttpResponse response = client.execute(hp);

List<Cookie> cookies = ((AbstractHttpClient) client).getCookieStore()
.getCookies();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < cookies.size(); i++) {
Cookie cookie = cookies.get(i);
String cookieName = cookie.getName();
String cookieValue = cookie.getValue();
if (!TextUtils.isEmpty(cookieName)
&& !TextUtils.isEmpty(cookieValue)) {
sb.append(cookieName + "=");
sb.append(cookieValue + ";");
}
}
SaveCookies(sb);


需要带上cookies请求的时候
HttpPost hp = new HttpPost(url);
HttpEntity entity = new UrlEncodedFormEntity(values, HTTP.UTF_8);
hp.setEntity(entity);
HttpClient client = getHttpClient();
hp.setHeader("Cookie", LoadCookies());
HttpResponse response = client.execute(hp);
  相关解决方案