5

如何通过 volley 库使用会话 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);

谢谢

4

3 回答 3

3

这是我使用带有 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;
    }
于 2015-09-22T01:16:24.343 回答
1
    BasicHttpParams mHttpParams = new BasicHttpParams();

    // Set the timeout in milliseconds until a connection is established.
    // The default value is zero, that means the timeout is not used.
    int timeoutConnection = 15000;
    HttpConnectionParams.setConnectionTimeout(mHttpParams, timeoutConnection);
    // Set the default socket timeout (SO_TIMEOUT)
    // in milliseconds which is the timeout for waiting for data.
    int timeoutSocket = 20000;
    HttpConnectionParams.setSoTimeout(mHttpParams, timeoutSocket);

    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    final SSLSocketFactory sslSocketFactory = SSLSocketFactory.getSocketFactory();
    sslSocketFactory.setHostnameVerifier(SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    registry.register(new Scheme("https", sslSocketFactory, 443));

    /*ClientConnectionManager cm = new ThreadSafeClientConnManager(mHttpParams, registry);*/
    DefaultHttpClient defaultHttpClient = new DefaultHttpClient(/*cm,*/ mHttpParams);

    RequestQueue requestQueue = Volley.newRequestQueue(mContext.getApplicationContext(),new HttpClientStack(defaultHttpClient));
于 2013-07-30T12:53:55.117 回答
1

我使用 Volley Android Library 因为它就像 iOS 中的 AFNetworking。以前更容易和更快。关于登录成功时的 Cookies Session。我配置:

CookieManager cookieManage = new CookieManager();
CookieHandler.setDefault(cookieManage);

它运行成功。但是,CookieManage 只是在更大的 8 版本SDK 中执行。

喜欢:在 AndroidManifest.xml

<uses-sdk
    android:minSdkVersion="9"
    android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET"/>

希望它可以帮助你!谢谢。

于 2013-11-06T02:11:34.510 回答