标签:
思路很简单,每次请求获取到服务器返回的response就解析头部获取cookie并保存,发送请求的时候就从本地读取cookie添加到头部发送给服务器
第一步,解析http response头部的cookie并保存,自定义一个Request并重写其parseNetworkResponse方法
/** * 解析数据,保存Cookie * @param response * @return */ @Override protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) { try { JSONObject jsonObject; /*将response构造成JSONObject返回给调用者*/ if (response.data.length != 0) { String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); jsonObject = new JSONObject(jsonString); } else { jsonObject = new JSONObject(); } /*获取数据头*/ mHeader = response.headers.toString(); /*通过正则表达式提取Cookie(JSESSIONID)*/ Pattern pattern = Pattern.compile("Set-Cookie=.*?;"); Matcher matcher = pattern.matcher(mHeader); if (matcher.find()) { cookieFromResp = matcher.group(); /*获取数据头中键为Set-Cookie的值即获取Cookie*/ cookieFromResp = cookieFromResp.substring(11, cookieFromResp.length() - 1); DLog.v("Cookie: " + cookieFromResp); } /*将Cookie保存到本地,下次请求数据的时候再把本地保存的Cookie发送给服务器*/ if(!TextUtils.isEmpty(cookieFromResp)){ CookieUtils.saveSessionID(App.getContext(),cookieFromResp); } return Response.success(jsonObject, HttpHeaderParser.parseCacheHeaders(response)); } catch (UnsupportedEncodingException e) { return Response.error(new ParseError(e)); } catch (JSONException je) { return Response.error(new ParseError(je)); } }第二步,发送请求的时候,从本地读取Cookie,添加到http request的头部,发送给服务器,重写getHeaders()即可
/** * 设置header,自动发送本地保存的Cookie * @return * @throws AuthFailureError */ @Override public Map<String, String> getHeaders() throws AuthFailureError { headerMap.put("Accept", "application/json"); headerMap.put("Content-Type", "application/json; charset=UTF-8"); String cookie=CookieUtils.loadSessionID(App.getContext()); DLog.d(cookie); /*将本地保存的Cookie发送给服务器*/ if(!TextUtils.isEmpty(cookie)){ headerMap.put("Cookie", CookieUtils.loadSessionID(App.getContext())); } return headerMap; }经过上边两个方法的重写就已经实现了Cookie的自动保存和自动发送
经过封装的完整的Request代码如下:
public class JsonObjectRequest extends JsonRequest<JSONObject > { private String mHeader; private String cookieFromResp = ""; Map<String, String> headerMap = new HashMap<>(); public JsonObjectRequest(int method, String url, JSONObject jsonRequest, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) { super( method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener, errorListener); } public JsonObjectRequest(String url, JSONObject jsonRequest, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) { this( jsonRequest == null ? Request.Method.GET : Request.Method.POST, url, jsonRequest, listener, errorListener); } /** * 解析数据,保存Cookie * @param response * @return */ @Override protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) { try { JSONObject jsonObject; /*将response构造成JSONObject返回给调用者*/ if (response.data.length != 0) { String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); jsonObject = new JSONObject(jsonString); } else { jsonObject = new JSONObject(); } /*获取数据头*/ mHeader = response.headers.toString(); /*通过正则表达式提取Cookie(JSESSIONID)*/ Pattern pattern = Pattern.compile("Set-Cookie=.*?;"); Matcher matcher = pattern.matcher(mHeader); if (matcher.find()) { cookieFromResp = matcher.group(); /*获取数据头中键为Set-Cookie的值即获取Cookie*/ cookieFromResp = cookieFromResp.substring(11, cookieFromResp.length() - 1); DLog.v("Cookie: " + cookieFromResp); } /*将Cookie保存到本地,下次请求数据的时候再把本地保存的Cookie发送给服务器*/ if(!TextUtils.isEmpty(cookieFromResp)){ CookieUtils.saveSessionID(App.getContext(),cookieFromResp); } return Response.success(jsonObject, HttpHeaderParser.parseCacheHeaders(response)); } catch (UnsupportedEncodingException e) { return Response.error(new ParseError(e)); } catch (JSONException je) { return Response.error(new ParseError(je)); } } /** * 设置超时 * @return */ @Override public RetryPolicy getRetryPolicy() { RetryPolicy retryPolicy= new DefaultRetryPolicy(5000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT); return retryPolicy; } /** * 设置header,自动发送本地保存的Cookie * @return * @throws AuthFailureError */ @Override public Map<String, String> getHeaders() throws AuthFailureError { headerMap.put("Accept", "application/json"); headerMap.put("Content-Type", "application/json; charset=UTF-8"); String cookie=CookieUtils.loadSessionID(App.getContext()); DLog.d(cookie); /*将本地保存的Cookie发送给服务器*/ if(!TextUtils.isEmpty(cookie)){ headerMap.put("Cookie", CookieUtils.loadSessionID(App.getContext())); } return headerMap; } //将Cookie加入数据头 public void setCookie(String cookie) { headerMap.put("Cookie", cookie); } }
封装Volley使Volley的每个请求都自动保存和发送Cookie
标签:
原文地址:http://blog.csdn.net/wangshihui512/article/details/51350646