码迷,mamicode.com
首页 > 移动开发 > 详细

Android volley添加Cookie

时间:2014-06-03 05:06:43      阅读:252      评论:0      收藏:0      [点我收藏+]

标签: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;
    }

}

搞定。





Android volley添加Cookie,布布扣,bubuko.com

Android volley添加Cookie

标签:android   volley   cookie   

原文地址:http://blog.csdn.net/aygxylxk/article/details/27539107

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!