Android Volley 的post请求自定义 和 volley 的cookies 使用

android的网络请求有不少第三方框架,其中volley因为其高的定制性、稳定性以及速度快获得了你们普遍的使用以及研究,这里我只是说一下我对这个框架下post请求使用的心得体会。 一.cookies的使用 cookies,token,seesion这些均可以理解为咱们请求登录接口后,后台根据用户信息生成一串字符串,而后每次请求接口后会读取这串字符串,就能够识别为那个用户,而且根据用户信息作接下来的逻辑判断。 首先自定义一个MyPostRequest 继承 Request 而后重写getHeaders()方法android

/**
	 * 在heard里面加入cookies
	 * */
	@Override
	public Map<String, String> getHeaders() throws AuthFailureError {
		if (cookies!=null && cookies.length()>1) {
			HashMap<String, String> headers = new HashMap<String, String>();
			headers.put("cookie",cookies);
			Log.d("Volley", "headers----------------" + headers);
			return headers;
		}else {
			return super.getHeaders();
		}
	}
复制代码

cookie为取到的cookie值缓存起来json

获取cookie数组

/**
	 * 对请求的结果进行处理
	 * */
	@Override
	protected Response<RequestCall> parseNetworkResponse(
			NetworkResponse response) {
			if (cookies==null || DtdApplication.cookies.length()<1) {
				Map<String, String> responseHeaders = response.headers;
				String rawCookies = responseHeaders.get("Set-Cookie");
				if (rawCookies!=null) {
	cookies=rawCookies.substring(0,rawCookies.indexOf(";"));
					
				}
			}
			}
复制代码

这个方法里去cookie值 2、BodyContentType缓存

@Override
	public String getBodyContentType() {
		return "application/json; charset=" + getParamsEncoding();
	}

复制代码

这个方法能够设置contenttype,contenttype为请求heard里面的头部分,用来识别数据的格式bash

三。定义参数为object类型服务器

@Override
	public byte[] getBody() throws AuthFailureError {
		Map<String, Object> params = parms;
        if (params != null && params.size() > 0) {
            try {
				return JsonUtils.toJson(params).getBytes(getParamsEncoding());
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
        }
        return null;
	}
复制代码

从手机端到服务器传递的之最后都会转化成byte[],因此咱们之object转成byte数组,而后后台能够识别就能够自,治理我转化成json。cookie

4、设置时间间隔和重复请求网络

/**
	 * 重复请求次数时间设置
	 * */
	@Override
	public RetryPolicy getRetryPolicy() {
		RetryPolicy retryPolicy = new DefaultRetryPolicy(1000*3, 0, 1.0f);  
		return retryPolicy; 
	}
复制代码

这个方法用来设置请求过时时间,第一个参数为时间,第二个为重复请求次数app

5、最后在说下Response parseNetworkResponse方法 这个方法为请求返回后的方法 其中response里面放的是请求返回的数据 response.data放的是请求返回的体,是body,为byte数组 response.headers 为请求头,存放contenttype、cookies等一些heard信息框架

相关文章
相关标签/搜索