volley 獲取cookie總結

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));
				} 
			}

		};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章