码迷,mamicode.com
首页 > 移动开发 > 详细

Android-HttpURLConnection自动管理cookie

时间:2015-07-15 13:21:53      阅读:557      评论:0      收藏:0      [点我收藏+]

标签:

Volley那么好用的框架竟然没有内置对cookie的处理,自己搞一个!
public class MobCookieManager {//转载请标明出处:http://blog.csdn.net/goldenfish1919/article/details/46890245
	
	private MobCookieManager(){}
	
	/**
	 * 应用启动的时候调用,参考:{@link CookieManager#getInstance CookieManager.getInstance()}
	 * */
	public static void init(Context context){
		CookieSyncManager.createInstance(context);
	}
	
	public static String getCookie(String url){
		CookieManager cookieManager = CookieManager.getInstance();
		return cookieManager.getCookie(url);
	}
	
	/**
	 * http://stackoverflow.com/questions/16007084/does-android-webkit-cookiemanager-works-on-android-2-3-6
	 * */
	public static void setCookies(String url, Map<String, List<String>> headerFields) {
		if (null == headerFields) {
			return;
		}
		List<String> cookies = headerFields.get("Set-Cookie");
		if (null == cookies) {
			return;
		}
		CookieSyncManager.getInstance().startSync();
		for (String cookie : cookies) {
			setCookie(url, cookie);
		}
		CookieSyncManager.getInstance().sync();
	}
	
	private static void setCookie(String url, String cookie) {
		CookieManager cookieManager = CookieManager.getInstance();
		cookieManager.setAcceptCookie(true);

		if(cookie.indexOf("Expires") < 0){
			cookie = addExpireToCookie(cookie);
		}
		cookieManager.setCookie(url, cookie);
	}
	
	/**
	 * http://stackoverflow.com/questions/8547620/what-is-a-session-cookie
	 * */
	private static String addExpireToCookie(String cookie) {
		Date expireDate = new Date(new Date().getTime() + 24L*60*60*1000);
		String datestr =DateUtil.format(DateUtil.east8ToGmt(expireDate), DateUtil.FORMAT_GMT);
		String arr[] = cookie.split(";");
		StringBuilder sb = new StringBuilder();
		sb.append(arr[0]);
		sb.append("; ").append("Expires=").append(datestr);
		if(arr.length > 1){
			for(int i=1; i<arr.length; i++){
				sb.append(";").append(arr[i]);
			}
		}
		return sb.toString();
	}
	
}
</pre><pre name="code" class="java"><pre name="code" class="java">public class DateUtil {
	
	public static final String FORMAT_MDHM = "MM-dd HH:mm";
	public static final String FORMAT_YMD = "yyyy-MM-dd";
	public static final String FORMAT_YMDHM = "yyyy-MM-dd HH:mm";
	public static final String FORMAT_YMDHMS = "yyyy-MM-dd HH:mm:ss";
	public static final String FORMAT_GMT = "EEE, dd-MMM-yyyy HH:mm:ss 'GMT'";

	private static final String TAG = DateUtil.class.getSimpleName();
	private static final Locale DEFAULT_LOCALE = Locale.CHINA;
	
	private static ThreadLocal<Map<String, SimpleDateFormat>> threadLocal = new ThreadLocal<Map<String, SimpleDateFormat>>() {  
        protected synchronized Map<String, SimpleDateFormat> initialValue() {  
        	Map<String, SimpleDateFormat> map = new HashMap<String, SimpleDateFormat>();
        	map.put(FORMAT_MDHM, new SimpleDateFormat(FORMAT_MDHM, DEFAULT_LOCALE));
        	map.put(FORMAT_YMD, new SimpleDateFormat(FORMAT_YMD, DEFAULT_LOCALE));
        	map.put(FORMAT_YMDHM, new SimpleDateFormat(FORMAT_YMDHM, DEFAULT_LOCALE));
        	map.put(FORMAT_YMDHMS, new SimpleDateFormat(FORMAT_YMDHMS, DEFAULT_LOCALE));
        	map.put(FORMAT_GMT, new SimpleDateFormat(FORMAT_GMT, DEFAULT_LOCALE));
            return map;  
        }  
    };  
  
    private DateUtil(){}
    
    public static SimpleDateFormat getDateFormat(String format) {  
    	Map<String, SimpleDateFormat> map = (Map<String, SimpleDateFormat>) threadLocal.get();  
    	SimpleDateFormat sdf = map.get(format);
    	if(sdf != null){
    		return sdf;
    	}
		try{
			sdf = new SimpleDateFormat(format, DEFAULT_LOCALE);
			map.put(format, sdf);
		}catch(Exception e){
			MyLog.e(TAG, e);
		}
		return sdf;
    }  
  
    public static Date parse(String textDate, String format) { 
    	if(textDate == null || textDate.length() <= 0){
    		return null;
    	}
    	try{
    		SimpleDateFormat sdf = getDateFormat(format);
    		if(sdf == null){
    			return null;	
    		}
    		return sdf.parse(textDate);  
    	}catch(Exception e){
    		MyLog.e(TAG, e);
    		return null;
    	}
        
    }  
    
	public static String format(Date date, String format){
		if(date == null){
			return null;
		}
		SimpleDateFormat sdf = getDateFormat(format);
		if(sdf == null){
			return null;
		}
		return sdf.format(date);
	}
	
	public static Date east8ToGmt(Date src){
		if(src == null){
			return null;
		}
		TimeZone srcTimeZone = TimeZone.getTimeZone("GMT+8");  
	    TimeZone destTimeZone = TimeZone.getTimeZone("GMT");  
		long targetTime = src.getTime() - srcTimeZone.getRawOffset() + destTimeZone.getRawOffset();  
        return new Date(targetTime);
	}
	
}

注意:我们这里使用的android.webkit.CookieManager。


    
        

版权声明:本文为博主原创文章,未经博主允许不得转载。

Android-HttpURLConnection自动管理cookie

标签:

原文地址:http://blog.csdn.net/goldenfish1919/article/details/46890245

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!