Android volley添加Cookie

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

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

HurlStack  performRequest方法中

HashMap map = new HashMap();
        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 mHeaders=new HashMap(1);

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

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

    @Override
    public Map getHeaders() throws AuthFailureError {
        return mHeaders;
    }

}

搞定。



你可能感兴趣的:(Android volley添加Cookie)