gpt4 book ai didi

android - 通过 JsonObjectRequest 将 session cookie 与 android volley 库一起使用

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:47:00 25 4
gpt4 key购买 nike

如何通过 volley 库使用 session cookie 处理这样的请求?

JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {

@Override
public void onResponse(JSONObject response) {
//Response
}
}, new Response.ErrorListener() {

@Override
public void onErrorResponse(VolleyError error) {
//Error
}
});
queue.add(jsObjRequest);

谢谢

最佳答案

这是我使用 Volley 和 JsonObjectRequest 保存 cookie 的方式

我的想法是捕获随我的 Json 请求返回的 Set-Cookie header ,然后将其保存在首选项中

请求

            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;
}

关于android - 通过 JsonObjectRequest 将 session cookie 与 android volley 库一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17324804/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com