Android network request has a lot of third-party frameworks, volley because of its high customization, stability and speed has been widely used and studied, here I just say my experience on the use of POST requests under this framework. The use of cookies, tokens and seesion can be understood as a string of strings generated by the background according to user information after we request to log in to the interface. Then the background will read this string of strings after each request to the interface, so that we can identify the user and make the following logical judgment according to the user information. Start with a custom MyPostRequest inheritance Request and override the getHeaders() method

@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 {
			returnsuper.getHeaders(); }}Copy the code

Cookie Is cached for the fetched cookie value

To get a 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(";")); }}}Copy the code

In this method the cookie value is 2, BodyContentType

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

Copy the code

This method sets the contentType, which is the header of the heard request to identify the format of the data

3. Define the parameter as object

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

From the mobile end to the server will be converted into byte[], so our object into byte array, and then the background can recognize it can be converted into JSON.

Set the interval and repeat requests

** / @override public RetryPolicygetRetryPolicy() {RetryPolicy RetryPolicy = new DefaultRetryPolicy(1000*3, 0, 1.0f);return retryPolicy; 
	}
Copy the code

This method is used to set the request expiration time. The first parameter is time and the second parameter is the number of repeated requests

Response parseNetworkResponse method is the method after the request is returned. In Response, the data returned by the request is put in the response.data is the body returned by the request, which is the body. Is the byte array Response. headers is the request header and stores some heard information such as contentType and cookies