微博开发api限制太多,准备直接爬网页数据了,然而微博基本是用cookies当token,于是需要改一改volley请求
(android用cookies真的麻烦,python一个session就解决了,甚至想直接内嵌py代码)
- 很简单,在想读取cookies的
StringRequest
中,重写一下parseNetworkResponse
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
HashMap<String, String> cookieMap = new HashMap<>();
for (int i = 0, n = response.allHeaders.size(); i < n; i++){
Header h = response.allHeaders.get(i);
if (h.getName().equalsIgnoreCase("Set-Cookie")){
if (h.getValue() != null){
String firstItem = h.getValue().substring(0, h.getValue().indexOf(';'));
String []cookiePair = firstItem.split("=");
if (cookiePair.length == 2){
cookieMap.put(cookiePair[0], cookiePair[1]);
}
}
}
}
if (response.statusCode == 200){
Log.i("Login","登录成功");
}else {
Log.e("Login","登录失败!!");
}
// Cookie保存
StringBuilder stringBuilder = new StringBuilder();
for (Map.Entry<String, String> entry : cookieMap.entrySet()){
stringBuilder.append(entry.getKey()).append("=").append(entry.getValue()).append(";");
}
// 这里写了个putCookies的方法来保存cookies
if(!putCookies(context, stringBuilder.toString())){
Log.e("LoginCookies","保存cookies失败");
}
return super.parseNetworkResponse(response);
}
里面stringbuilder中cookies格式为cookie1=value1;cookie2=value2;cookie3=value3;
- 使用的时候重写getHeaders:
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
return LoginUtils.getCookies(getApplicationContext());
}
return中就是需要加入的cookies,数据格式为map<String, String>
, LoginUtils.getCookies
如下
public static Map<String, String> getCookies(Context context) {
SharedPreferences sp = context.getSharedPreferences("Cookies", Context.MODE_PRIVATE);
String cookies = sp.getString("cookies", "");
if (!cookies.equals("")){
Log.i("Login", "getCookies");
Map<String, String> map = new HashMap<String, String>();
map.put("cookie", cookies);
return map;
}else {
Log.e("Login", "Cookies不存在");
return null;
}
}
即在volley里使用cookies的方法为,将cookies
以map<K,V>
形式加入到headers中,其中K一般为cookie
, 而V可包括多条cookies, 格式为:cookie1=value1;cookie2=value2;cookie3=value3;