在Volley请求session时,非常的麻烦,而且持久有问题,这可能是我自己这边对Volley的不熟悉,不能做到持久,我这边努力。
好了 下面上代码,Volley的session请求:
1:创建一个类,名字随意,比如我这边的
public class Contant { public static volatile String cookie = null; }就这样一行代码,然后再Volley请求重写的 new Response. ErrorListener
后面重写parseNetworkResponse 方法
我这边是做的获取验证码请求session,如我的代码 :
//添加请求的session @Override protected Response<String> parseNetworkResponse(NetworkResponse response) { Response<String> r = super.parseNetworkResponse(response); Map<String,String> head = response.headers; String cookies = head.get("Set-Cookie"); Contant.cookie = cookies.substring(0,cookies.indexOf(";")); return r; }然后就是新的Volley请求了,在新的Volley请求 重写的 getParams 方法后重写 getHeaders 方法,如我的代码
//获取session进行验证 @Override public Map<String, String> getHeaders() throws AuthFailureError { if (Contant.cookie != null && Contant.cookie.length() > 0) { HashMap<String, String> headers = new HashMap<String, String>(); headers.put("cookie", Contant.cookie_123); Log.d("调试", "headers--" + headers); return headers; }else { return super.getHeaders(); } }这就是Volley请求session的全部过程,对于我这种新手而言够用了。
不过我发现Volley对于session的保持不能做到,在又开始进行新的Volley请求时,没有进行session的获取,直接用获取验证码的session进行验证就是错误的,可能是我这边的问题,不过对于一般的请求够用了。
如有不对的地方,请指出,望能和你们共同进步!
转载请注明出处