xutils 2.x(2.6)中的session获得和cookieStore使用

来源:互联网 发布:mac word选项 编辑:程序博客网 时间:2024/06/10 15:55

xutils框架是如今使用比较广泛的android开源框架,我对其也情有独钟,对于框架模块,我想大家都很熟悉了,就不多说了。我今天主要主要说下xutils2.6中如何为http请求设置cookiesession,当时这个问题纠结了很久,试了多次,问了不少人,上网搜索,结果越来越模糊,最终通过认真阅读源代码,终于清楚如何使用了,现在和大家分享一下自己的心得,也希望大家对开源框架的学习要认真阅读源代码。

     不多说了,大家看示例。

     程序设计到​​三个类,

    1.MyApplication(扩展应用)定义保存的Cookie和会话的全局变量

    2.LoginActivity演示获得的cookiesession

    3.GetDataActivity演示设置的cookie和session

[java] view plain copy
  1. import com.lidroid.xutils.util.PreferencesCookieStore;  
  2. import android.app.Application;  
  3. public class MyApplication extends Application{  
  4.       
  5.     /** 
  6.      * 用PreferencesCookieStore 持久化cookie到本地  
  7.      *   类的定义:public class PreferencesCookieStore implements CookieStore 
  8.      *   其内部用SharedPreferences保存,操作内部已封装 
  9.      * 位置:com.lidroid.xutils.util.PreferencesCookieStore; 
  10.      *  
  11.      * 特别注意:PreferencesCookieStore 这个类在xutils 2.6中才出现,以前的版本没有 
  12.      *          xutils 3.x 版本中也没有这个类 
  13.      *          在xutils 2.6 以前版本要么自己参照PreferencesCookieStore源码,保存cookie到本地 
  14.      *          或者自己用SharedPreferences保存sessionid 到本地,sessionid就是一个字符串,用 
  15.      *          SharedPreferences保存很简单,就不介绍了 
  16.      *           
  17.      * 注:sessionid  实际是保存在cookie中 
  18.      *       向服务器可以提交cookie 或 sessionid 
  19.      *       提交cookie :调用方法 public HttpUtils configCookieStore(CookieStore cookieStore);  
  20.      *       提交sessionid : RequestParams public void addHeader(String name, String value); 
  21.      *                       或setHeader(String name, String value); 
  22.      */  
  23.     public static PreferencesCookieStore presCookieStore;  
  24.     public static String jsessionid = ""//保存sessionid  
  25.   
  26.     public void onCreate() {          
  27.         /* 
  28.          * 程序启动,调用这个构造函数 
  29.          * 在构造函数中 PreferencesCookieStore内部从本地 
  30.          * 取出cookie,保存在PreferencesCookieStore 中的队列中 
  31.          * 如果本地没有,PreferencesCookieStore  public List<Cookie> getCookies(); 
  32.          * 返回的 List<Cookie> 长度为0 
  33.          *  
  34.          */  
  35.         presCookieStore = new PreferencesCookieStore(getApplicationContext());  
  36.   
  37.     }  
  38.   
  39. }  


[java] view plain copy
  1. import java.util.List;  
  2. import org.apache.http.client.CookieStore;  
  3. import org.apache.http.cookie.Cookie;  
  4. import org.apache.http.impl.client.DefaultHttpClient;  
  5. import com.lidroid.xutils.HttpUtils;  
  6. import com.lidroid.xutils.exception.HttpException;  
  7. import com.lidroid.xutils.http.RequestParams;  
  8. import com.lidroid.xutils.http.ResponseInfo;  
  9. import com.lidroid.xutils.http.callback.RequestCallBack;  
  10. import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;  
  11.   
  12. public class LoginActivity {      
  13.     /** 
  14.      * 登陆 后获得cookie sessionid 
  15.      * 这儿只是演示如何获得cookie和seesionid 
  16.      * 因此 url,RequestParams 直接用null,大家注意 
  17.      * 
  18.      */  
  19.     public void login(){          
  20.         final HttpUtils http = new HttpUtils();  
  21.         String url = null;  
  22.         RequestParams params = null;          
  23.         http.send(HttpMethod.POST, url,params, new RequestCallBack<String>() {  
  24.               
  25.             @Override  
  26.             public void onFailure(HttpException arg0, String arg1) {  
  27.             }  
  28.   
  29.             @Override  
  30.             public void onSuccess(ResponseInfo<String> arg0) {                  
  31.                 /* 
  32.                  * 得到cookie seesionid 并持久化到本地的核心代码 
  33.                  */  
  34.                 DefaultHttpClient defaultHttpClient = (DefaultHttpClient) http.getHttpClient();  
  35.                 CookieStore cookieStore = defaultHttpClient.getCookieStore();  
  36.                 List<Cookie> cookies = cookieStore.getCookies();  
  37.                 for (Cookie cookie : cookies) {  
  38.                     if ("JSESSIONID".equals(cookie.getName())) {  
  39.                         MyApplication.jsessionid = cookie.getValue(); //得到sessionid  
  40.                     }  
  41.                     MyApplication.presCookieStore.addCookie(cookie); //将cookie保存在本地  
  42.                 }                 
  43.             }         
  44.         });  
  45.           
  46.     }  
  47.   
  48. }  


[java] view plain copy
  1. import com.lidroid.xutils.HttpUtils;  
  2. import com.lidroid.xutils.exception.HttpException;  
  3. import com.lidroid.xutils.http.RequestParams;  
  4. import com.lidroid.xutils.http.ResponseInfo;  
  5. import com.lidroid.xutils.http.callback.RequestCallBack;  
  6. import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;  
  7.   
  8. /** 
  9.  * 从服务器获取数据前 添加cookie 
  10.  * 或sessionid 
  11.  *  
  12.  * @author Administrator 
  13.  * 
  14.  */  
  15. public class GetDataActivity {  
  16.       
  17.     public void getData() {  
  18.         final HttpUtils http = new HttpUtils();  
  19.         String url = null;    
  20.         /* 
  21.          * get无参请求添加cookie 
  22.          * get 含参请求可以添加cookie或session 
  23.          * post请求可以添加cookie或session 
  24.          */  
  25.         http.configCookieStore(MyApplication.presCookieStore);   
  26.         http.send(HttpMethod.GET, url,  new RequestCallBack<String>() {  
  27.             @Override  
  28.             public void onFailure(HttpException arg0, String arg1) {}  
  29.             @Override  
  30.             public void onSuccess(ResponseInfo<String> arg0) {}  
  31.   
  32.         });  
  33.           
  34.         /* 
  35.          * seesionid字段在不同服务器开发语言中不同 
  36.          * java中“JSESSIONID”,php中“PSESSIONID” 其他请自己查阅资料 
  37.          * 这儿用java示例 
  38.          *  
  39.          * setHeader 和addHeader的区别: 
  40.          *   setHeader 未设置时,添加;已设置,重新赋值 
  41.          *   addHeader 未设置时,添加;已设置,仍保持以前的值不变 
  42.          */  
  43.         RequestParams params = new RequestParams();  
  44.         params.setHeader("Cookie""JSESSIONID="+MyApplication.jsessionid); //设置头信息  
  45.         http.send(HttpMethod.GET, url,  new RequestCallBack<String>() {  
  46.             @Override  
  47.             public void onFailure(HttpException arg0, String arg1) {}  
  48.             @Override  
  49.             public void onSuccess(ResponseInfo<String> arg0) {}  
  50.   
  51.         });       
  52.     }  
  53. }  

如果存在不足,请大家多多指教,共同进步!

参考Xutils2.6源代码

1.HttpUtils

[java] view plain copy
  1. package com.lidroid.xutils;  
  2.   
  3. import android.text.TextUtils;  
  4. import com.lidroid.xutils.exception.HttpException;  
  5. import com.lidroid.xutils.http.*;  
  6. import com.lidroid.xutils.http.callback.HttpRedirectHandler;  
  7. import com.lidroid.xutils.http.callback.RequestCallBack;  
  8. import com.lidroid.xutils.http.client.DefaultSSLSocketFactory;  
  9. import com.lidroid.xutils.http.client.HttpRequest;  
  10. import com.lidroid.xutils.http.client.RetryHandler;  
  11. import com.lidroid.xutils.http.client.entity.GZipDecompressingEntity;  
  12. import com.lidroid.xutils.task.PriorityExecutor;  
  13. import com.lidroid.xutils.util.OtherUtils;  
  14. import org.apache.http.*;  
  15. import org.apache.http.client.CookieStore;  
  16. import org.apache.http.client.HttpClient;  
  17. import org.apache.http.client.protocol.ClientContext;  
  18. import org.apache.http.conn.params.ConnManagerParams;  
  19. import org.apache.http.conn.params.ConnPerRouteBean;  
  20. import org.apache.http.conn.scheme.PlainSocketFactory;  
  21. import org.apache.http.conn.scheme.Scheme;  
  22. import org.apache.http.conn.scheme.SchemeRegistry;  
  23. import org.apache.http.conn.ssl.SSLSocketFactory;  
  24. import org.apache.http.impl.client.DefaultHttpClient;  
  25. import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;  
  26. import org.apache.http.params.BasicHttpParams;  
  27. import org.apache.http.params.HttpConnectionParams;  
  28. import org.apache.http.params.HttpParams;  
  29. import org.apache.http.params.HttpProtocolParams;  
  30. import org.apache.http.protocol.BasicHttpContext;  
  31. import org.apache.http.protocol.HTTP;  
  32. import org.apache.http.protocol.HttpContext;  
  33.   
  34. import java.io.File;  
  35. import java.io.IOException;  
  36.   
  37. public class HttpUtils {  
  38.   
  39.     public final static HttpCache sHttpCache = new HttpCache();  
  40.   
  41.     private final DefaultHttpClient httpClient;  
  42.     private final HttpContext httpContext = new BasicHttpContext();  
  43.   
  44.     private HttpRedirectHandler httpRedirectHandler;  
  45.   
  46.     public HttpUtils() {  
  47.         this(HttpUtils.DEFAULT_CONN_TIMEOUT, null);  
  48.     }  
  49.   
  50.     public HttpUtils(int connTimeout) {  
  51.         this(connTimeout, null);  
  52.     }  
  53.   
  54.     public HttpUtils(String userAgent) {  
  55.         this(HttpUtils.DEFAULT_CONN_TIMEOUT, userAgent);  
  56.     }  
  57.   
  58.     public HttpUtils(int connTimeout, String userAgent) {  
  59.         HttpParams params = new BasicHttpParams();  
  60.   
  61.         ConnManagerParams.setTimeout(params, connTimeout);  
  62.         HttpConnectionParams.setSoTimeout(params, connTimeout);  
  63.         HttpConnectionParams.setConnectionTimeout(params, connTimeout);  
  64.   
  65.         if (TextUtils.isEmpty(userAgent)) {  
  66.             userAgent = OtherUtils.getUserAgent(null);  
  67.         }  
  68.         HttpProtocolParams.setUserAgent(params, userAgent);  
  69.   
  70.         ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(10));  
  71.         ConnManagerParams.setMaxTotalConnections(params, 10);  
  72.   
  73.         HttpConnectionParams.setTcpNoDelay(params, true);  
  74.         HttpConnectionParams.setSocketBufferSize(params, 1024 * 8);  
  75.         HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);  
  76.   
  77.         SchemeRegistry schemeRegistry = new SchemeRegistry();  
  78.         schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));  
  79.         schemeRegistry.register(new Scheme("https", DefaultSSLSocketFactory.getSocketFactory(), 443));  
  80.   
  81.         httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager(params, schemeRegistry), params);  
  82.   
  83.         httpClient.setHttpRequestRetryHandler(new RetryHandler(DEFAULT_RETRY_TIMES));  
  84.   
  85.         httpClient.addRequestInterceptor(new HttpRequestInterceptor() {  
  86.             @Override  
  87.             public void process(org.apache.http.HttpRequest httpRequest, HttpContext httpContext) throws org.apache.http.HttpException, IOException {  
  88.                 if (!httpRequest.containsHeader(HEADER_ACCEPT_ENCODING)) {  
  89.                     httpRequest.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);  
  90.                 }  
  91.             }  
  92.         });  
  93.   
  94.         httpClient.addResponseInterceptor(new HttpResponseInterceptor() {  
  95.             @Override  
  96.             public void process(HttpResponse response, HttpContext httpContext) throws org.apache.http.HttpException, IOException {  
  97.                 final HttpEntity entity = response.getEntity();  
  98.                 if (entity == null) {  
  99.                     return;  
  100.                 }  
  101.                 final Header encoding = entity.getContentEncoding();  
  102.                 if (encoding != null) {  
  103.                     for (HeaderElement element : encoding.getElements()) {  
  104.                         if (element.getName().equalsIgnoreCase("gzip")) {  
  105.                             response.setEntity(new GZipDecompressingEntity(response.getEntity()));  
  106.                             return;  
  107.                         }  
  108.                     }  
  109.                 }  
  110.             }  
  111.         });  
  112.     }  
  113.   
  114.     // ************************************    default settings & fields ****************************  
  115.   
  116.     private String responseTextCharset = HTTP.UTF_8;  
  117.   
  118.     private long currentRequestExpiry = HttpCache.getDefaultExpiryTime();  
  119.   
  120.     private final static int DEFAULT_CONN_TIMEOUT = 1000 * 15// 15s  
  121.   
  122.     private final static int DEFAULT_RETRY_TIMES = 3;  
  123.   
  124.     private static final String HEADER_ACCEPT_ENCODING = "Accept-Encoding";  
  125.     private static final String ENCODING_GZIP = "gzip";  
  126.   
  127.     private final static int DEFAULT_POOL_SIZE = 3;  
  128.     private final static PriorityExecutor EXECUTOR = new PriorityExecutor(DEFAULT_POOL_SIZE);  
  129.   
  130.     public HttpClient getHttpClient() {  
  131.         return this.httpClient;  
  132.     }  
  133.   
  134.     // ***************************************** config *******************************************  
  135.   
  136.     public HttpUtils configResponseTextCharset(String charSet) {  
  137.         if (!TextUtils.isEmpty(charSet)) {  
  138.             this.responseTextCharset = charSet;  
  139.         }  
  140.         return this;  
  141.     }  
  142.   
  143.     public HttpUtils configHttpRedirectHandler(HttpRedirectHandler httpRedirectHandler) {  
  144.         this.httpRedirectHandler = httpRedirectHandler;  
  145.         return this;  
  146.     }  
  147.   
  148.     public HttpUtils configHttpCacheSize(int httpCacheSize) {  
  149.         sHttpCache.setCacheSize(httpCacheSize);  
  150.         return this;  
  151.     }  
  152.   
  153.     public HttpUtils configDefaultHttpCacheExpiry(long defaultExpiry) {  
  154.         HttpCache.setDefaultExpiryTime(defaultExpiry);  
  155.         currentRequestExpiry = HttpCache.getDefaultExpiryTime();  
  156.         return this;  
  157.     }  
  158.   
  159.     public HttpUtils configCurrentHttpCacheExpiry(long currRequestExpiry) {  
  160.         this.currentRequestExpiry = currRequestExpiry;  
  161.         return this;  
  162.     }  
  163.   
  164.     public HttpUtils configCookieStore(CookieStore cookieStore) {  
  165.         httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);  
  166.         return this;  
  167.     }  
  168.   
  169.     public HttpUtils configUserAgent(String userAgent) {  
  170.         HttpProtocolParams.setUserAgent(this.httpClient.getParams(), userAgent);  
  171.         return this;  
  172.     }  
  173.   
  174.     public HttpUtils configTimeout(int timeout) {  
  175.         final HttpParams httpParams = this.httpClient.getParams();  
  176.         ConnManagerParams.setTimeout(httpParams, timeout);  
  177.         HttpConnectionParams.setConnectionTimeout(httpParams, timeout);  
  178.         return this;  
  179.     }  
  180.   
  181.     public HttpUtils configSoTimeout(int timeout) {  
  182.         final HttpParams httpParams = this.httpClient.getParams();  
  183.         HttpConnectionParams.setSoTimeout(httpParams, timeout);  
  184.         return this;  
  185.     }  
  186.   
  187.     public HttpUtils configRegisterScheme(Scheme scheme) {  
  188.         this.httpClient.getConnectionManager().getSchemeRegistry().register(scheme);  
  189.         return this;  
  190.     }  
  191.   
  192.     public HttpUtils configSSLSocketFactory(SSLSocketFactory sslSocketFactory) {  
  193.         Scheme scheme = new Scheme("https", sslSocketFactory, 443);  
  194.         this.httpClient.getConnectionManager().getSchemeRegistry().register(scheme);  
  195.         return this;  
  196.     }  
  197.   
  198.     public HttpUtils configRequestRetryCount(int count) {  
  199.         this.httpClient.setHttpRequestRetryHandler(new RetryHandler(count));  
  200.         return this;  
  201.     }  
  202.   
  203.     public HttpUtils configRequestThreadPoolSize(int threadPoolSize) {  
  204.         HttpUtils.EXECUTOR.setPoolSize(threadPoolSize);  
  205.         return this;  
  206.     }  
  207.   
  208.     // ***************************************** send request *******************************************  
  209.   
  210.     public <T> HttpHandler<T> send(HttpRequest.HttpMethod method, String url,  
  211.                                    RequestCallBack<T> callBack) {  
  212.         return send(method, url, null, callBack);  
  213.     }  
  214.   
  215.     public <T> HttpHandler<T> send(HttpRequest.HttpMethod method, String url, RequestParams params,  
  216.                                    RequestCallBack<T> callBack) {  
  217.         if (url == nullthrow new IllegalArgumentException("url may not be null");  
  218.   
  219.         HttpRequest request = new HttpRequest(method, url);  
  220.         return sendRequest(request, params, callBack);  
  221.     }  
  222.   
  223.     public ResponseStream sendSync(HttpRequest.HttpMethod method, String url) throws HttpException {  
  224.         return sendSync(method, url, null);  
  225.     }  
  226.   
  227.     public ResponseStream sendSync(HttpRequest.HttpMethod method, String url, RequestParams params) throws HttpException {  
  228.         if (url == nullthrow new IllegalArgumentException("url may not be null");  
  229.   
  230.         HttpRequest request = new HttpRequest(method, url);  
  231.         return sendSyncRequest(request, params);  
  232.     }  
  233.   
  234.     // ***************************************** download *******************************************  
  235.   
  236.     public HttpHandler<File> download(String url, String target,  
  237.                                       RequestCallBack<File> callback) {  
  238.         return download(HttpRequest.HttpMethod.GET, url, target, nullfalsefalse, callback);  
  239.     }  
  240.   
  241.     public HttpHandler<File> download(String url, String target,  
  242.                                       boolean autoResume, RequestCallBack<File> callback) {  
  243.         return download(HttpRequest.HttpMethod.GET, url, target, null, autoResume, false, callback);  
  244.     }  
  245.   
  246.     public HttpHandler<File> download(String url, String target,  
  247.                                       boolean autoResume, boolean autoRename, RequestCallBack<File> callback) {  
  248.         return download(HttpRequest.HttpMethod.GET, url, target, null, autoResume, autoRename, callback);  
  249.     }  
  250.   
  251.     public HttpHandler<File> download(String url, String target,  
  252.                                       RequestParams params, RequestCallBack<File> callback) {  
  253.         return download(HttpRequest.HttpMethod.GET, url, target, params, falsefalse, callback);  
  254.     }  
  255.   
  256.     public HttpHandler<File> download(String url, String target,  
  257.                                       RequestParams params, boolean autoResume, RequestCallBack<File> callback) {  
  258.         return download(HttpRequest.HttpMethod.GET, url, target, params, autoResume, false, callback);  
  259.     }  
  260.   
  261.     public HttpHandler<File> download(String url, String target,  
  262.                                       RequestParams params, boolean autoResume, boolean autoRename, RequestCallBack<File> callback) {  
  263.         return download(HttpRequest.HttpMethod.GET, url, target, params, autoResume, autoRename, callback);  
  264.     }  
  265.   
  266.     public HttpHandler<File> download(HttpRequest.HttpMethod method, String url, String target,  
  267.                                       RequestParams params, RequestCallBack<File> callback) {  
  268.         return download(method, url, target, params, falsefalse, callback);  
  269.     }  
  270.   
  271.     public HttpHandler<File> download(HttpRequest.HttpMethod method, String url, String target,  
  272.                                       RequestParams params, boolean autoResume, RequestCallBack<File> callback) {  
  273.         return download(method, url, target, params, autoResume, false, callback);  
  274.     }  
  275.   
  276.     public HttpHandler<File> download(HttpRequest.HttpMethod method, String url, String target,  
  277.                                       RequestParams params, boolean autoResume, boolean autoRename, RequestCallBack<File> callback) {  
  278.   
  279.         if (url == nullthrow new IllegalArgumentException("url may not be null");  
  280.         if (target == nullthrow new IllegalArgumentException("target may not be null");  
  281.   
  282.         HttpRequest request = new HttpRequest(method, url);  
  283.   
  284.         HttpHandler<File> handler = new HttpHandler<File>(httpClient, httpContext, responseTextCharset, callback);  
  285.   
  286.         handler.setExpiry(currentRequestExpiry);  
  287.         handler.setHttpRedirectHandler(httpRedirectHandler);  
  288.   
  289.         if (params != null) {  
  290.             request.setRequestParams(params, handler);  
  291.             handler.setPriority(params.getPriority());  
  292.         }  
  293.         handler.executeOnExecutor(EXECUTOR, request, target, autoResume, autoRename);  
  294.         return handler;  
  295.     }  
  296.   
  297.     ////////////////////////////////////////////////////////////////////////////////////////////////  
  298.     private <T> HttpHandler<T> sendRequest(HttpRequest request, RequestParams params, RequestCallBack<T> callBack) {  
  299.   
  300.         HttpHandler<T> handler = new HttpHandler<T>(httpClient, httpContext, responseTextCharset, callBack);  
  301.   
  302.         handler.setExpiry(currentRequestExpiry);  
  303.         handler.setHttpRedirectHandler(httpRedirectHandler);  
  304.         request.setRequestParams(params, handler);  
  305.   
  306.         if (params != null) {  
  307.             handler.setPriority(params.getPriority());  
  308.         }  
  309.         handler.executeOnExecutor(EXECUTOR, request);  
  310.         return handler;  
  311.     }  
  312.   
  313.     private ResponseStream sendSyncRequest(HttpRequest request, RequestParams params) throws HttpException {  
  314.   
  315.         SyncHttpHandler handler = new SyncHttpHandler(httpClient, httpContext, responseTextCharset);  
  316.   
  317.         handler.setExpiry(currentRequestExpiry);  
  318.         handler.setHttpRedirectHandler(httpRedirectHandler);  
  319.         request.setRequestParams(params);  
  320.   
  321.         return handler.sendRequest(request);  
  322.     }  
  323. }  


2.PreferencesCookieStore

[java] view plain copy
  1. package com.lidroid.xutils.util;  
  2.   
  3. import android.content.Context;  
  4. import android.content.SharedPreferences;  
  5. import android.text.TextUtils;  
  6. import org.apache.http.client.CookieStore;  
  7. import org.apache.http.cookie.Cookie;  
  8. import org.apache.http.impl.cookie.BasicClientCookie;  
  9.   
  10. import java.io.*;  
  11. import java.util.ArrayList;  
  12. import java.util.Date;  
  13. import java.util.List;  
  14. import java.util.concurrent.ConcurrentHashMap;  
  15.   
  16. /** 
  17.  * A CookieStore impl, it's save cookie to SharedPreferences. 
  18.  * 
  19.  * @author michael yang 
  20.  */  
  21. public class PreferencesCookieStore implements CookieStore {  
  22.   
  23.     private static final String COOKIE_PREFS = "CookiePrefsFile";  
  24.     private static final String COOKIE_NAME_STORE = "names";  
  25.     private static final String COOKIE_NAME_PREFIX = "cookie_";  
  26.   
  27.     private final ConcurrentHashMap<String, Cookie> cookies;  
  28.     private final SharedPreferences cookiePrefs;  
  29.   
  30.     /** 
  31.      * Construct a persistent cookie store. 
  32.      */  
  33.     public PreferencesCookieStore(Context context) {  
  34.         cookiePrefs = context.getSharedPreferences(COOKIE_PREFS, Context.MODE_PRIVATE);  
  35.         cookies = new ConcurrentHashMap<String, Cookie>();  
  36.   
  37.         // Load any previously stored cookies into the store  
  38.         String storedCookieNames = cookiePrefs.getString(COOKIE_NAME_STORE, null);  
  39.         if (storedCookieNames != null) {  
  40.             String[] cookieNames = TextUtils.split(storedCookieNames, ",");  
  41.             for (String name : cookieNames) {  
  42.                 String encodedCookie = cookiePrefs.getString(COOKIE_NAME_PREFIX + name, null);  
  43.                 if (encodedCookie != null) {  
  44.                     Cookie decodedCookie = decodeCookie(encodedCookie);  
  45.                     if (decodedCookie != null) {  
  46.                         cookies.put(name, decodedCookie);  
  47.                     }  
  48.                 }  
  49.             }  
  50.   
  51.             // Clear out expired cookies  
  52.             clearExpired(new Date());  
  53.         }  
  54.     }  
  55.   
  56.     @Override  
  57.     public void addCookie(Cookie cookie) {  
  58.         String name = cookie.getName();  
  59.   
  60.         // Save cookie into local store, or remove if expired  
  61.         if (!cookie.isExpired(new Date())) {  
  62.             cookies.put(name, cookie);  
  63.         } else {  
  64.             cookies.remove(name);  
  65.         }  
  66.   
  67.         // Save cookie into persistent store  
  68.         SharedPreferences.Editor editor = cookiePrefs.edit();  
  69.         editor.putString(COOKIE_NAME_STORE, TextUtils.join(",", cookies.keySet()));  
  70.         editor.putString(COOKIE_NAME_PREFIX + name, encodeCookie(new SerializableCookie(cookie)));  
  71.         editor.commit();  
  72.     }  
  73.   
  74.     @Override  
  75.     public void clear() {  
  76.         // Clear cookies from persistent store  
  77.         SharedPreferences.Editor editor = cookiePrefs.edit();  
  78.         for (String name : cookies.keySet()) {  
  79.             editor.remove(COOKIE_NAME_PREFIX + name);  
  80.         }  
  81.         editor.remove(COOKIE_NAME_STORE);  
  82.         editor.commit();  
  83.   
  84.         // Clear cookies from local store  
  85.         cookies.clear();  
  86.     }  
  87.   
  88.     @Override  
  89.     public boolean clearExpired(Date date) {  
  90.         boolean clearedAny = false;  
  91.         SharedPreferences.Editor editor = cookiePrefs.edit();  
  92.   
  93.         for (ConcurrentHashMap.Entry<String, Cookie> entry : cookies.entrySet()) {  
  94.             String name = entry.getKey();  
  95.             Cookie cookie = entry.getValue();  
  96.             if (cookie.getExpiryDate() == null || cookie.isExpired(date)) {  
  97.                 // Remove the cookie by name  
  98.                 cookies.remove(name);  
  99.   
  100.                 // Clear cookies from persistent store  
  101.                 editor.remove(COOKIE_NAME_PREFIX + name);  
  102.   
  103.                 // We've cleared at least one  
  104.                 clearedAny = true;  
  105.             }  
  106.         }  
  107.   
  108.         // Update names in persistent store  
  109.         if (clearedAny) {  
  110.             editor.putString(COOKIE_NAME_STORE, TextUtils.join(",", cookies.keySet()));  
  111.         }  
  112.         editor.commit();  
  113.   
  114.         return clearedAny;  
  115.     }  
  116.   
  117.     @Override  
  118.     public List<Cookie> getCookies() {  
  119.         return new ArrayList<Cookie>(cookies.values());  
  120.     }  
  121.   
  122.     public Cookie getCookie(String name) {  
  123.         return cookies.get(name);  
  124.     }  
  125.   
  126.   
  127.     protected String encodeCookie(SerializableCookie cookie) {  
  128.         ByteArrayOutputStream os = new ByteArrayOutputStream();  
  129.         try {  
  130.             ObjectOutputStream outputStream = new ObjectOutputStream(os);  
  131.             outputStream.writeObject(cookie);  
  132.         } catch (Throwable e) {  
  133.             return null;  
  134.         }  
  135.   
  136.         return byteArrayToHexString(os.toByteArray());  
  137.     }  
  138.   
  139.     protected Cookie decodeCookie(String cookieStr) {  
  140.         byte[] bytes = hexStringToByteArray(cookieStr);  
  141.         ByteArrayInputStream is = new ByteArrayInputStream(bytes);  
  142.         Cookie cookie = null;  
  143.         try {  
  144.             ObjectInputStream ois = new ObjectInputStream(is);  
  145.             cookie = ((SerializableCookie) ois.readObject()).getCookie();  
  146.         } catch (Throwable e) {  
  147.             LogUtils.e(e.getMessage(), e);  
  148.         }  
  149.   
  150.         return cookie;  
  151.     }  
  152.   
  153.     // Using some super basic byte array <-> hex conversions so we don't have  
  154.     // to rely on any large Base64 libraries. Can be overridden if you like!  
  155.     protected String byteArrayToHexString(byte[] b) {  
  156.         StringBuffer sb = new StringBuffer(b.length * 2);  
  157.         for (byte element : b) {  
  158.             int v = element & 0xff;  
  159.             if (v < 16) {  
  160.                 sb.append('0');  
  161.             }  
  162.             sb.append(Integer.toHexString(v));  
  163.         }  
  164.         return sb.toString().toUpperCase();  
  165.     }  
  166.   
  167.     protected byte[] hexStringToByteArray(String s) {  
  168.         int len = s.length();  
  169.         byte[] data = new byte[len / 2];  
  170.         for (int i = 0; i < len; i += 2) {  
  171.             data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16));  
  172.         }  
  173.         return data;  
  174.     }  
  175.   
  176.   
  177.     public class SerializableCookie implements Serializable {  
  178.         private static final long serialVersionUID = 6374381828722046732L;  
  179.   
  180.         private transient final Cookie cookie;  
  181.         private transient BasicClientCookie clientCookie;  
  182.   
  183.         public SerializableCookie(Cookie cookie) {  
  184.             this.cookie = cookie;  
  185.         }  
  186.   
  187.         public Cookie getCookie() {  
  188.             Cookie bestCookie = cookie;  
  189.             if (clientCookie != null) {  
  190.                 bestCookie = clientCookie;  
  191.             }  
  192.             return bestCookie;  
  193.         }  
  194.   
  195.         private void writeObject(ObjectOutputStream out) throws IOException {  
  196.             out.writeObject(cookie.getName());  
  197.             out.writeObject(cookie.getValue());  
  198.             out.writeObject(cookie.getComment());  
  199.             out.writeObject(cookie.getDomain());  
  200.             out.writeObject(cookie.getExpiryDate());  
  201.             out.writeObject(cookie.getPath());  
  202.             out.writeInt(cookie.getVersion());  
  203.             out.writeBoolean(cookie.isSecure());  
  204.         }  
  205.   
  206.         private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {  
  207.             String name = (String) in.readObject();  
  208.             String value = (String) in.readObject();  
  209.             clientCookie = new BasicClientCookie(name, value);  
  210.             clientCookie.setComment((String) in.readObject());  
  211.             clientCookie.setDomain((String) in.readObject());  
  212.             clientCookie.setExpiryDate((Date) in.readObject());  
  213.             clientCookie.setPath((String) in.readObject());  
  214.             clientCookie.setVersion(in.readInt());  
  215.             clientCookie.setSecure(in.readBoolean());  
  216.         }  
  217.     }  
  218. }  

3.RequestParams

[java] view plain copy
  1. package com.lidroid.xutils.http;  
  2.   
  3. import android.text.TextUtils;  
  4. import com.lidroid.xutils.http.client.entity.BodyParamsEntity;  
  5. import com.lidroid.xutils.http.client.multipart.HttpMultipartMode;  
  6. import com.lidroid.xutils.http.client.multipart.MultipartEntity;  
  7. import com.lidroid.xutils.http.client.multipart.content.ContentBody;  
  8. import com.lidroid.xutils.http.client.multipart.content.FileBody;  
  9. import com.lidroid.xutils.http.client.multipart.content.InputStreamBody;  
  10. import com.lidroid.xutils.http.client.multipart.content.StringBody;  
  11. import com.lidroid.xutils.util.LogUtils;  
  12. import com.lidroid.xutils.task.Priority;  
  13. import org.apache.http.Header;  
  14. import org.apache.http.HttpEntity;  
  15. import org.apache.http.NameValuePair;  
  16. import org.apache.http.message.BasicHeader;  
  17. import org.apache.http.message.BasicNameValuePair;  
  18. import org.apache.http.protocol.HTTP;  
  19.   
  20. import java.io.File;  
  21. import java.io.InputStream;  
  22. import java.io.UnsupportedEncodingException;  
  23. import java.nio.charset.Charset;  
  24. import java.util.ArrayList;  
  25. import java.util.HashMap;  
  26. import java.util.List;  
  27. import java.util.concurrent.ConcurrentHashMap;  
  28.   
  29.   
  30. public class RequestParams {  
  31.   
  32.     private String charset = HTTP.UTF_8;  
  33.   
  34.     private List<HeaderItem> headers;  
  35.     private List<NameValuePair> queryStringParams;  
  36.     private HttpEntity bodyEntity;  
  37.     private List<NameValuePair> bodyParams;  
  38.     private HashMap<String, ContentBody> fileParams;  
  39.   
  40.     private Priority priority;  
  41.   
  42.     public RequestParams() {  
  43.     }  
  44.   
  45.     public RequestParams(String charset) {  
  46.         if (!TextUtils.isEmpty(charset)) {  
  47.             this.charset = charset;  
  48.         }  
  49.     }  
  50.   
  51.     public Priority getPriority() {  
  52.         return priority;  
  53.     }  
  54.   
  55.     public void setPriority(Priority priority) {  
  56.         this.priority = priority;  
  57.     }  
  58.   
  59.     public String getCharset() {  
  60.         return charset;  
  61.     }  
  62.   
  63.     public void setContentType(String contentType) {  
  64.         this.setHeader("Content-Type", contentType);  
  65.     }  
  66.   
  67.     /** 
  68.      * Adds a header to this message. The header will be appended to the end of the list. 
  69.      * 
  70.      * @param header 
  71.      */  
  72.     public void addHeader(Header header) {  
  73.         if (this.headers == null) {  
  74.             this.headers = new ArrayList<HeaderItem>();  
  75.         }  
  76.         this.headers.add(new HeaderItem(header));  
  77.     }  
  78.   
  79.     /** 
  80.      * Adds a header to this message. The header will be appended to the end of the list. 
  81.      * 
  82.      * @param name 
  83.      * @param value 
  84.      */  
  85.     public void addHeader(String name, String value) {  
  86.         if (this.headers == null) {  
  87.             this.headers = new ArrayList<HeaderItem>();  
  88.         }  
  89.         this.headers.add(new HeaderItem(name, value));  
  90.     }  
  91.   
  92.     /** 
  93.      * Adds all the headers to this message. 
  94.      * 
  95.      * @param headers 
  96.      */  
  97.     public void addHeaders(List<Header> headers) {  
  98.         if (this.headers == null) {  
  99.             this.headers = new ArrayList<HeaderItem>();  
  100.         }  
  101.         for (Header header : headers) {  
  102.             this.headers.add(new HeaderItem(header));  
  103.         }  
  104.     }  
  105.   
  106.     /** 
  107.      * Overwrites the first header with the same name. 
  108.      * The new header will be appended to the end of the list, if no header with the given name can be found. 
  109.      * 
  110.      * @param header 
  111.      */  
  112.     public void setHeader(Header header) {  
  113.         if (this.headers == null) {  
  114.             this.headers = new ArrayList<HeaderItem>();  
  115.         }  
  116.         this.headers.add(new HeaderItem(header, true));  
  117.     }  
  118.   
  119.     /** 
  120.      * Overwrites the first header with the same name. 
  121.      * The new header will be appended to the end of the list, if no header with the given name can be found. 
  122.      * 
  123.      * @param name 
  124.      * @param value 
  125.      */  
  126.     public void setHeader(String name, String value) {  
  127.         if (this.headers == null) {  
  128.             this.headers = new ArrayList<HeaderItem>();  
  129.         }  
  130.         this.headers.add(new HeaderItem(name, value, true));  
  131.     }  
  132.   
  133.     /** 
  134.      * Overwrites all the headers in the message. 
  135.      * 
  136.      * @param headers 
  137.      */  
  138.     public void setHeaders(List<Header> headers) {  
  139.         if (this.headers == null) {  
  140.             this.headers = new ArrayList<HeaderItem>();  
  141.         }  
  142.         for (Header header : headers) {  
  143.             this.headers.add(new HeaderItem(header, true));  
  144.         }  
  145.     }  
  146.   
  147.     public void addQueryStringParameter(String name, String value) {  
  148.         if (queryStringParams == null) {  
  149.             queryStringParams = new ArrayList<NameValuePair>();  
  150.         }  
  151.         queryStringParams.add(new BasicNameValuePair(name, value));  
  152.     }  
  153.   
  154.     public void addQueryStringParameter(NameValuePair nameValuePair) {  
  155.         if (queryStringParams == null) {  
  156.             queryStringParams = new ArrayList<NameValuePair>();  
  157.         }  
  158.         queryStringParams.add(nameValuePair);  
  159.     }  
  160.   
  161.     public void addQueryStringParameter(List<NameValuePair> nameValuePairs) {  
  162.         if (queryStringParams == null) {  
  163.             queryStringParams = new ArrayList<NameValuePair>();  
  164.         }  
  165.         if (nameValuePairs != null && nameValuePairs.size() > 0) {  
  166.             for (NameValuePair pair : nameValuePairs) {  
  167.                 queryStringParams.add(pair);  
  168.             }  
  169.         }  
  170.     }  
  171.   
  172.     public void addBodyParameter(String name, String value) {  
  173.         if (bodyParams == null) {  
  174.             bodyParams = new ArrayList<NameValuePair>();  
  175.         }  
  176.         bodyParams.add(new BasicNameValuePair(name, value));  
  177.     }  
  178.   
  179.     public void addBodyParameter(NameValuePair nameValuePair) {  
  180.         if (bodyParams == null) {  
  181.             bodyParams = new ArrayList<NameValuePair>();  
  182.         }  
  183.         bodyParams.add(nameValuePair);  
  184.     }  
  185.   
  186.     public void addBodyParameter(List<NameValuePair> nameValuePairs) {  
  187.         if (bodyParams == null) {  
  188.             bodyParams = new ArrayList<NameValuePair>();  
  189.         }  
  190.         if (nameValuePairs != null && nameValuePairs.size() > 0) {  
  191.             for (NameValuePair pair : nameValuePairs) {  
  192.                 bodyParams.add(pair);  
  193.             }  
  194.         }  
  195.     }  
  196.   
  197.     public void addBodyParameter(String key, File file) {  
  198.         if (fileParams == null) {  
  199.             fileParams = new HashMap<String, ContentBody>();  
  200.         }  
  201.         fileParams.put(key, new FileBody(file));  
  202.     }  
  203.   
  204.     public void addBodyParameter(String key, File file, String mimeType) {  
  205.         if (fileParams == null) {  
  206.             fileParams = new HashMap<String, ContentBody>();  
  207.         }  
  208.         fileParams.put(key, new FileBody(file, mimeType));  
  209.     }  
  210.   
  211.     public void addBodyParameter(String key, File file, String mimeType, String charset) {  
  212.         if (fileParams == null) {  
  213.             fileParams = new HashMap<String, ContentBody>();  
  214.         }  
  215.         fileParams.put(key, new FileBody(file, mimeType, charset));  
  216.     }  
  217.   
  218.     public void addBodyParameter(String key, File file, String fileName, String mimeType, String charset) {  
  219.         if (fileParams == null) {  
  220.             fileParams = new HashMap<String, ContentBody>();  
  221.         }  
  222.         fileParams.put(key, new FileBody(file, fileName, mimeType, charset));  
  223.     }  
  224.   
  225.     public void addBodyParameter(String key, InputStream stream, long length) {  
  226.         if (fileParams == null) {  
  227.             fileParams = new HashMap<String, ContentBody>();  
  228.         }  
  229.         fileParams.put(key, new InputStreamBody(stream, length));  
  230.     }  
  231.   
  232.     public void addBodyParameter(String key, InputStream stream, long length, String fileName) {  
  233.         if (fileParams == null) {  
  234.             fileParams = new HashMap<String, ContentBody>();  
  235.         }  
  236.         fileParams.put(key, new InputStreamBody(stream, length, fileName));  
  237.     }  
  238.   
  239.     public void addBodyParameter(String key, InputStream stream, long length, String fileName, String mimeType) {  
  240.         if (fileParams == null) {  
  241.             fileParams = new HashMap<String, ContentBody>();  
  242.         }  
  243.         fileParams.put(key, new InputStreamBody(stream, length, fileName, mimeType));  
  244.     }  
  245.   
  246.     public void setBodyEntity(HttpEntity bodyEntity) {  
  247.         this.bodyEntity = bodyEntity;  
  248.         if (bodyParams != null) {  
  249.             bodyParams.clear();  
  250.             bodyParams = null;  
  251.         }  
  252.         if (fileParams != null) {  
  253.             fileParams.clear();  
  254.             fileParams = null;  
  255.         }  
  256.     }  
  257.   
  258.     /** 
  259.      * Returns an HttpEntity containing all request parameters 
  260.      */  
  261.     public HttpEntity getEntity() {  
  262.   
  263.         if (bodyEntity != null) {  
  264.             return bodyEntity;  
  265.         }  
  266.   
  267.         HttpEntity result = null;  
  268.   
  269.         if (fileParams != null && !fileParams.isEmpty()) {  
  270.   
  271.             MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.STRICT, null, Charset.forName(charset));  
  272.   
  273.             if (bodyParams != null && !bodyParams.isEmpty()) {  
  274.                 for (NameValuePair param : bodyParams) {  
  275.                     try {  
  276.                         multipartEntity.addPart(param.getName(), new StringBody(param.getValue()));  
  277.                     } catch (UnsupportedEncodingException e) {  
  278.                         LogUtils.e(e.getMessage(), e);  
  279.                     }  
  280.                 }  
  281.             }  
  282.   
  283.             for (ConcurrentHashMap.Entry<String, ContentBody> entry : fileParams.entrySet()) {  
  284.                 multipartEntity.addPart(entry.getKey(), entry.getValue());  
  285.             }  
  286.   
  287.             result = multipartEntity;  
  288.         } else if (bodyParams != null && !bodyParams.isEmpty()) {  
  289.             result = new BodyParamsEntity(bodyParams, charset);  
  290.         }  
  291.   
  292.         return result;  
  293.     }  
  294.   
  295.     public List<NameValuePair> getQueryStringParams() {  
  296.         return queryStringParams;  
  297.     }  
  298.   
  299.     public List<HeaderItem> getHeaders() {  
  300.         return headers;  
  301.     }  
  302.   
  303.     public class HeaderItem {  
  304.         public final boolean overwrite;  
  305.         public final Header header;  
  306.   
  307.         public HeaderItem(Header header) {  
  308.             this.overwrite = false;  
  309.             this.header = header;  
  310.         }  
  311.   
  312.         public HeaderItem(Header header, boolean overwrite) {  
  313.             this.overwrite = overwrite;  
  314.             this.header = header;  
  315.         }  
  316.   
  317.         public HeaderItem(String name, String value) {  
  318.             this.overwrite = false;  
  319.             this.header = new BasicHeader(name, value);  
  320.         }  
  321.   
  322.         public HeaderItem(String name, String value, boolean overwrite) {  
  323.             this.overwrite = overwrite;  
  324.             this.header = new BasicHeader(name, value);  
  325.         }  
  326.     }  
0 0
原创粉丝点击