使用Volley,如果响应有多个Cookie,我如何使用Session Cookie和StringRequest?

时间:2015-02-28 05:15:53

标签: android android-volley

如何使用StringRequest发送会话cookie以识别Web服务器的请求。如果有两个会话cookie来自服务器?

这是我的代码,

[1]发出新请求(StringRequest),代码snip let,

@Override
            public Map<String, String> getHeaders() throws AuthFailureError {                    
                Map<String, String> headers = super.getHeaders();
                if (headers == null || headers.equals(Collections.emptyMap())) {
                    headers = new HashMap<String, String>();
                }
                try {
                    addSessionCookie(headers);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return headers;
            }

            @Override
            protected Response<String> parseNetworkResponse(
                    NetworkResponse response) {
                // check session cookies :: custom method
                try {
                    checkSessionCookie(response.headers);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                return super.parseNetworkResponse(response);
            }

[2]获取会话cookie

// check session cookies
    public final void checkSessionCookie(Map<String, String> headers)
            throws Exception {
        if (headers.containsKey("Set-Cookie")
                && headers.get("Set-Cookie").startsWith("sessionid")) {
            String mycookie = headers.get("Set-Cookie");
            if (mycookie.length() > 0) {
                String[] splitCookie = mycookie.split(";");
                String[] splitSessionId = splitCookie[0].split("=");
                mycookie = splitSessionId[1];

            }
        }
    }

    // add session Cookie
    public final void addSessionCookie(Map<String, String> headers)
            throws Exception {
        if (mycookie.length() > 0) {
            StringBuilder builder = new StringBuilder();
            builder.append("sessionid");
            builder.append("=");
            builder.append(mycookie);
            if (headers.containsKey("Cookie")) {
                builder.append("; ");
                builder.append(headers.get("Cookie"));
            }
            headers.put("Cookie", builder.toString());
        }
    }

但是上面的代码不起作用,响应来了“授权错误”。

如何从响应中获取会话cookie(可能不止一个)并在新请求中设置,以验证用户?

1 个答案:

答案 0 :(得分:1)

这应该有效:

/**
 * Created by shaharb on 5/18/15.
 */
public class DStringRequest extends StringRequest {
    public DStringRequest(int method, String url, Response.Listener<String> listener, Response.ErrorListener errorListener) {
        super(method, url, listener, errorListener);
    }

    public DStringRequest(String url, Response.Listener<String> listener, Response.ErrorListener errorListener) {
        super(url, listener, errorListener);
    }

    /* (non-Javadoc)
         * @see com.android.volley.Request#getHeaders()
         */
    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        Map<String, String> headers = super.getHeaders();
        if (headers == null || headers.equals(Collections.emptyMap())) {
            headers = new HashMap<>();
        }
        // add the session cookie
        // try to get the cookie from the shared prefs
        String sessionId = Hawk.get("connect.sid", "");
        if (sessionId.length() > 0) {
            StringBuilder builder = new StringBuilder();
            builder.append("connect.sid");
            builder.append("=");
            builder.append(sessionId);
            if (headers.containsKey("Set-Cookie")) {
                builder.append("; ");
                builder.append(headers.get("Set-Cookie"));
            }
            headers.put("Set-Cookie", builder.toString());
        }

        return headers;
    }

    @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
        if (headers.containsKey("Set-Cookie")
                && headers.get("Set-Cookie").startsWith("connect.sid")) {
            String cookie = headers.get("Set-Cookie");
            if (cookie.length() > 0) {
                String[] splitCookie = cookie.split(";");
                String[] splitSessionId = splitCookie[0].split("=");
                cookie = splitSessionId[1];

                // Store is somewhare, shared prefs is ok
                Hawk.put("connect.sid", cookie);
            }
        }

        return super.parseNetworkResponse(response);
    }
}