volley 获取cookie总结

时间:2022-12-29 13:23:04
1.获取服务器返回的cookie值,重写request中的parseNetworkResponse方法就可以了
StringRequest request= new StringRequest(Method.POST, url,
this, this) {

@Override
protected Response<String> parseNetworkResponse(
NetworkResponse response) {
// TODO Auto-generated method stub
try {

Map<String, String> responseHeaders = response.headers;
String rawCookies = responseHeaders.get("Set-Cookie");
String dataString = new String(response.data, "UTF-8");
return Response.success(dataString,HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
}
}

};

2.有时服务器会返回多个 Set-Cookie 值,而Volley默认只取第一个,如果有需求,就要自己修改Volley的代码啦,HurlStack(sdk_int>9会走这里)里面的performRequest,默认解析header方式如下,

多个值的话只需要拿到header.getValue().get(1)等等,具体需求可以自行修改。

Header h = new BasicHeader(header.getKey(), header.getValue().get(0));
response.addHeader(h);

3.给服务器上传Cookie值,如下(因为该类实现了response和error接口,所以参数直接写的this)


	StringRequest request= new StringRequest(Method.POST, url,
this, this) {
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap localHashMap = new HashMap();
localHashMap.put("Cookie", "你的cookie值");
return localHashMap;
}
//设置post参数
protected Map<String, String> getParams() {
if(params==null){
return new HashMap<String, String>();
}
return params;
}
                        //设置编码格式			@Override			protected Response<String> parseNetworkResponse(					NetworkResponse response) {				// TODO Auto-generated method stub				try {					String dataString = new String(response.data, "UTF-8");					return Response.success(dataString,HttpHeaderParser.parseCacheHeaders(response));				} catch (UnsupportedEncodingException e) {					return Response.error(new ParseError(e));				} 			}		};