Android中Volley发送带有Cookie信息的请求

来源:互联网 发布:淘宝的宝贝卖点填什么 编辑:程序博客网 时间:2024/06/04 19:04

说明:通过Volley请求取到Cookie信息,并放到全局请求队列中发送出去,可以发送携带Cookie请求,服务器端可从Session中获取到。可以用来实现面再次登录或者请求被登录拦截器拦截导致请求失败。下面的只是在获取了服务器的Session以后,然后向服务器请求的实现,如果你还不会获取Session,请先看另一篇博文《Android的Volley框架实现获取cookie并同步到Webview的实现》。学会了取到SessionID,才能把它放入请求中发送出去。

方法一、要发送Session,就要在请求队列RequestQueue加入cookieStore ,优点:你可以将下面代码放单独在一个类中,供全局重复使用:

/** * volley全局Application *  * @see:获得全局请求队列,进行网络交互 *  */public class VolleyApplication extends Application {private static RequestQueue queues;@Overridepublic void onCreate() {    super.onCreate();    //请求加入cookie    DefaultHttpClient httpclient = new DefaultHttpClient();            CookieStore cookieStore = new BasicCookieStore();            httpclient.setCookieStore(cookieStore);            HttpStack httpStack = new HttpClientStack(httpclient);            //新建请求队列    queues = Volley.newRequestQueue(getApplicationContext(),httpStack);}public static RequestQueue getHttpQueues() {return queues;}}

发送带Session的请求,只需要将Request加入请求队列中即可:

private boolean sendRequestByVolleyPost(final Context context, final String url,final Map<String, String> params) {StringRequest request = new StringRequest(Method.POST, url, new Listener<String>() {@Overridepublic void onResponse(String str) {}}, new ErrorListener() {@Overridepublic void onErrorResponse(VolleyError error) {Toast.makeText(context, "服务器连接失败", Toast.LENGTH_SHORT).show();}}) {@Overrideprotected Map<String, String> getParams() throws AuthFailureError {return params;}};// 设置请求的Tag标签,可以在全局请求队列中通过Tag标签进行请求的查找request.setTag("CustomMenu");VolleyApplication.getHttpQueues().add(request);return true;}


方法二、除了上面的方法,如果只需要发送一次带cookie的请求,不用将cookie加在全局队列了,只需:

1.在Volley的getHeaders()方法中加入Cookie信息。(此处用了一个getSettingNote()方法来取存储好的cookie信息,点击:查看具体实现)

private boolean sendRequestByVolleyPost(final Context context, final String url,final Map<String, String> params) {StringRequest request = new StringRequest(Method.POST, url, new Listener<String>() {@Overridepublic void onResponse(String str) {}}, new ErrorListener() {@Overridepublic void onErrorResponse(VolleyError error) {Toast.makeText(context, "服务器连接失败", Toast.LENGTH_SHORT).show();}}) {@Overridepublic Map<String, String> getHeaders() throws AuthFailureError {HashMap<String, String> map = new HashMap<String, String>();map.put("Cookie",CommonUtil.getSettingNote(ModifyPwdActivity.this, "CookieSetting", "cookies"));// 关键:向请求头部添加Cookiereturn map;}};// 设置请求的Tag标签,可以在全局请求队列中通过Tag标签进行请求的查找request.setTag("CustomMenu");queue = Volley.newRequestQueue(getApplicationContext());queue.add(request);return true;}


1 0
原创粉丝点击