我需要从服务器响应中获取 cookie。对于网络调用,我使用的是 volley 库。

getRequest(String url, Response.Listener<JSONObject> responseListener, Response.ErrorListener errorListener) {
        try {

            JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET, url, null, responseListener
                    , errorListener) {
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    return getAuthHeader(context);
                }
            };
            RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
            req.setRetryPolicy(policy);
            req.setShouldCache(false);
            addToRequestQueue(req);
        } catch (Exception e) {
            e.printStackTrace();
        }

public static Map<String, String> getAuthHeader(Context context) {
        Map<String, String> headerMap = new HashMap<>();

        headerMap.put("token", auth);
        headerMap.put("Api-key", API_KEY);
        headerMap.put("Content-Type", CONTENT_TYPE);

        return headerMap;
    }

最佳答案

StringRequest req = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                     Log.i("response",response);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                     Log.i("error",error.getMessage());
                    }
                }){

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                return getAuthHeader(context);
            }

            @Override
            protected Response<String> parseNetworkResponse(NetworkResponse response) {
                // since we don't know which of the two underlying network vehicles
                // will Volley use, we have to handle and store session cookies manually
                Log.i("response",response.headers.toString());
                Map<String, String> responseHeaders = response.headers;
                String rawCookies = responseHeaders.get("Set-Cookie");
                Log.i("cookies",rawCookies);
                return super.parseNetworkResponse(response);
            }

        };

关于android - 如何从 Volley 响应中获取 cookie,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38591983/

10-10 17:06