首页 > 代码库 > Android volley添加Cookie

Android volley添加Cookie

Volley 默认是不支持Cookie的,如何添加Cookie,很是头疼。

看源码后发现HttpStack的子类中都有添加Header的代码。

HurlStack  performRequest方法中

HashMap<String, String> map = new HashMap<String, String>();
        map.putAll(request.getHeaders());
        map.putAll(additionalHeaders);
        if (mUrlRewriter != null) {
            String rewritten = mUrlRewriter.rewriteUrl(url);
            if (rewritten == null) {
                throw new IOException("URL blocked by rewriter: " + url);
            }
            url = rewritten;
        }
        URL parsedUrl = new URL(url);
        HttpURLConnection connection = openConnection(parsedUrl, request);
        for (String headerName : map.keySet()) {
            connection.addRequestProperty(headerName, map.get(headerName));
        }

HttpClientStack  performRequest方法中

addHeaders(httpRequest, request.getHeaders());

看到什么端倪了吧,对 request.getHeaders()可以设置Cookie

所以我们只要继承Request,实现request中的getHeaders()方法就行了。

下面是我继承JsonObjectRequest实现的方法

import java.util.HashMap;
import java.util.Map;
import org.json.JSONObject;
import com.android.volley.AuthFailureError;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.JsonObjectRequest;

public class CookieRequest extends JsonObjectRequest {
    private Map<String, String> mHeaders=new HashMap<String, String>(1);

    public CookieRequest(String url, JSONObject jsonRequest, Listener<JSONObject> listener,
                                   ErrorListener errorListener) {
        super(url, jsonRequest, listener, errorListener);
    }

    public CookieRequest(int method, String url, JSONObject jsonRequest, Listener<JSONObject> listener,
                                   ErrorListener errorListener) {
        super(method, url, jsonRequest, listener, errorListener);
    }
    
    public void setCookie(String cookie){
        mHeaders.put("Cookie", cookie);
    }

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

}

搞定。