这是我使用带有 JsonObjectRequest 的 Volley 保存 cookie 的方式
这个想法是捕获随我的 Json 请求返回的 Set-Cookie 标头,然后将其保存在首选项中
要求
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST,
url,
(String)param,
requestFuture, requestFuture){
@Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded";
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Show.m("getHeaders");
Map<String,String> headers = new HashMap<String, String>();
headers.put("Accept","application/json");
if(!MyApplication.getCookie(context).equals("")){
String cookie = MyApplication.getCookie(context);
Show.m("Cookie to load from preferences: " + cookie);
headers.put("Cookie", cookie);
}
return headers;
}
@Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
Map headers = response.headers;
String cookie = (String)headers.get("Set-Cookie");
MyApplication.saveCookie(context, cookie);
Show.m("Cookie to save to preferences: " + cookie);
return super.parseNetworkResponse(response);
}
};
喜好
public static void saveCookie(Context context, String cookie) {
if (cookie == null) {
return;
}
// Save in the preferences
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
if (null == sharedPreferences) {
return;
}
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("cookie", cookie);
editor.commit();
}
public static String getCookie(Context context)
{
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
String cookie = sharedPreferences.getString("cookie", "");
if (cookie.contains("expires")) {
removeCookie(context);
return "";
}
return cookie;
}