android DefaultHttpClient设置setCookieStore

android DefaultHttpClient设置setCookieStore

第一步:设置CookieStoreUtils的工具类
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.http.client.CookieStore;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.cookie.BasicClientCookie;

import android.app.Activity;
import android.content.SharedPreferences;

import com.google.gson.Gson;

public class CookieStoreUtils {

	@SuppressWarnings("unchecked")
	public static CookieStore initCookieStore(CookieStore cookieStore){
		SharedPreferences mySharedPreferences = MyApplication.mInstance.getSharedPreferences(
				"cookies", Activity.MODE_PRIVATE);
		Map<String, String> map = (Map<String, String>) mySharedPreferences.getAll();
		if (map != null) {
			Iterator<String> it = map.keySet().iterator();
			Gson gson = new Gson();
			while (it.hasNext()) {
				String key = it.next();
				String jsonCookie = map.get(key);
				if (jsonCookie != null) {		
					BasicClientCookie cookie = gson.fromJson(jsonCookie, BasicClientCookie.class);	
					cookieStore.addCookie(cookie);
				}
			}
		}
		return cookieStore;
	}
	
	public static void saveCookies(List<Cookie> cookies){
		SharedPreferences mySharedPreferences = MyApplication.mInstance.getSharedPreferences("cookies", Activity.MODE_PRIVATE);
		SharedPreferences.Editor editor = mySharedPreferences.edit();
		Gson gson = new Gson();
		for(Cookie cookie:cookies){
			editor.putString(cookie.getName(), gson.toJson(cookie));// JSON转换成String类型
		}
		editor.commit();
	}

}

第二步:
private static CookieStore cookieStore = null;
	/*
	 * POST方式,查询从URL得到的字符串
	 */
	public static String queryStringForPost(String url, List<NameValuePair> params) {
		DefaultHttpClient client = new DefaultHttpClient();
	    if(cookieStore==null){
	    	cookieStore = CookieStoreUtils.initCookieStore(client.getCookieStore());
	    }
		client.setCookieStore(cookieStore);	
		// 获取HttpPost对象
		HttpPost httpPost = new HttpPost(url);
		String result = "isError";

		HttpResponse httpResponse = null;
		try {
			// 设置HttpPost请求参数
			httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
			httpResponse = client.execute(httpPost);

			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				result = EntityUtils.toString(httpResponse.getEntity());
				if (result.equals("{\"data\":null}") || result.equals("{\"data\":[]}")) {// 如果后台数据为空
					return "isNull";// 返回为空的结果
				}
			}
			//保存cookie到本地
     		CookieStoreUtils.saveCookies(cookieStore.getCookies());
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return result;
	}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值