cookie持久化保存的问题

coffeeRoy 2014-11-25 07:35:22
最近在做一个项目,先登录到服务器,获取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";
}
}
...全文
441 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
荔枝别闹了 2014-11-26
  • 打赏
  • 举报
回复
存读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);
coffeeRoy 2014-11-26
  • 打赏
  • 举报
回复
引用 1 楼 u012374885 的回复:
存读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);
非常感谢!

80,363

社区成员

发帖
与我相关
我的任务
社区描述
移动平台 Android
androidandroid-studioandroidx 技术论坛(原bbs)
社区管理员
  • Android
  • yechaoa
  • 失落夏天
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧