Refer directly to volley’s JsonRequest and JsonObjectRequest code
Java BeanRequest inherits Request and uses generics. The reflection mechanism is used to obtain the generic Type Type, and the data returned by the interface (String Type) is converted into the Bean we need using FastJSON. Generics inherit from BaseBeans, which contain code and MSG. The BaseBean holds the general data returned by the interface, and can be added to it if there are others. This implements a data type that directly returns the required entity class.
import com.alibaba.fastjson.JSON; import com.android.volley.AuthFailureError; import com.android.volley.Cache; import com.android.volley.NetworkResponse; import com.android.volley.ParseError; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.toolbox.HttpHeaderParser; import com.hongxue.volley.bean.BaseBean; import java.io.UnsupportedEncodingException; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.HashMap; import java.util.Map; public class BeanRequest extends Request { protected static final String PROTOCOL_CHARSET = "utf-8"; private final SuccessListener mSuccessListener; private Map mPostParamMap; public static abstract class SuccessListener { private final Type type; Protected SuccessListener() {// Use reflection to get the Type of the genericSuperClass. Type superClass = getClass().getGenericSuperClass (); type = ((ParameterizedType) superClass).getActualTypeArguments()[0]; } public Type getType() { return type; } public abstract void onResponse(T response); } public BeanRequest(int method, String url, Map postParamMap, SuccessListener successListener, Response.ErrorListener errorListener) { super(method, url, errorListener); mSuccessListener = successListener; if (postParamMap ! MPostParamMap = new HashMap<>(postParammap.size ()); for (Map.Entry entry : postParamMap.entrySet()) { mPostParamMap.put(entry.getKey(), String.valueOf(entry.getValue())); }} /** * Post uses getParams() to pass parameters to the parent. */ @override protected Map getParams() throws AuthFailureError {return mPostParamMap; } @Override protected Response parseNetworkResponse(NetworkResponse response) { try { String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET)); Type type = mSuccessListener.getType(); T bean = JSON.parseObject(jsonString, type); / / used here fastjson directly convert the String into the Bean Cache. The Entry Entry. = HttpHeaderParser parseCacheHeaders (response); return Response.success(bean, entry); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return Response.error(new ParseError(e)); } } @Override protected void deliverResponse(T response) { mSuccessListener.onResponse(response); // callback}}Copy the code
BaseBean: Common network requests return code and MSG
public class BaseBean { private String code; private String msg; public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; }}Copy the code
Encapsulate your own HttpClient
public class HxHttpClient { private static RequestQueue requestQueue; private final Context context; private HxHttpClient(Context context) { this.context = context; } public synchronized static HxHttpClient newInstance(Context context) { if (requestQueue == null) { HTTPSTrustManager.allowAllSSL(); / / jump over HTTPS authentication, if use HTTP requests can be ignored requestQueue = Volley. NewRequestQueue (context) getApplicationContext ()); } return new HxHttpClient(context); } public RequestQueue getRequestQueue() { return requestQueue; } public BeanRequest request(BaseApi api, BeanRequest.SuccessListener successListener, Response.ErrorListener errorListener) { String url = api.getUrl(); TreeMap params = api.getParams(); if (api.requestMethod() == BaseApi.Method.POST) { return post(url, params, successListener, errorListener); } else { if (! params.isEmpty()) { url += "?" + mapToQueryString(params); } return get(url, successListener, errorListener); } } public BeanRequest post(String url, Map postParamMap, BeanRequest.SuccessListener successListener, Response.ErrorListener errorListener) { BeanRequest request = new BeanRequest<>(Request.Method.POST, url, postParamMap, successListener, errorHandler(errorListener)); addRequest(request); return request; } public BeanRequest get(String url, BeanRequest.SuccessListener successListener, Response.ErrorListener errorListener) { BeanRequest request = new BeanRequest(Request.Method.GET, url, null, successListener, errorHandler(errorListener)); addRequest(request); return request; } private void addRequest(BeanRequest request) { requestQueue.add(request); } public Response.ErrorListener errorHandler(final Response.ErrorListener errorListener) { return new ErrorListener() {@override public void onErrorResponse(VolleyError Error) {error = new VolleyError(" dear, Your network is not running properly. ", error); if (errorListener ! = null) { errorListener.onErrorResponse(error); }}}; } /** * private String mapToQueryString(Map Params) {StringBuilder encodedParams = new StringBuilder(); try { for (Map.Entry entry : params.entrySet()) { if (entry.getValue() == null || entry.getValue() instanceof File) continue; encodedParams.append(URLEncoder.encode(entry.getKey(), "UTF-8")); encodedParams.append('='); encodedParams.append(URLEncoder.encode(String.valueOf(entry.getValue()), "UTF-8")); encodedParams.append('&'); } return encodedParams.toString(); } catch (UnsupportedEncodingException uee) { throw new RuntimeException("Encoding not supported: UTF-8", uee); }}}Copy the code
BaseApi
import com.hongxue.volley.constants.HttpConstant; import java.lang.reflect.Field; import java.util.TreeMap; public abstract class BaseApi { public enum Method { GET, POST, } protected abstract String getPath(); public abstract Method requestMethod(); public String getUrl() { return HttpConstant.API_URL + getPath(); } public TreeMap getParams() {TreeMap params = new TreeMap(); Class clazz = getClass(); Field[] field = clazz.getDeclaredFields(); //getDeclaredFields() returns all fields in the Class, including private fields. Getimagelistinfoapi.java try {for (Field f: Field) {f.setaccessible (true); if (f.get(this) ! = null) { params.put(f.getName(), f.get(this)); } } } catch (IllegalArgumentException | IllegalAccessException e) { e.printStackTrace(); } return params; }}Copy the code
GetImageInfoApi
public class GetImageListInfoApi extends BaseApi{ private String type; @override public Method requestMethod() {return method.post; } @override protected String getPath() {return "API/interface name "; } public void setType(String type) { this.type = type; }}Copy the code
Get picture information
private void getImageListInfo() { GetImageListInfoApi api = new GetImageListInfoApi(); api.setType("1"); HxHttpClient.newInstance(MainActivity.this).request(api, New BeanRequest. SuccessListener () {@ Override public void onResponse (ImageListBean response) {/ / returns the ImageListBean directly ArrayList list = response.getDataList(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } } ); }Copy the code
ImageListBean
public class ImageListBean extends BaseBean { ArrayList dataList; public ArrayList getDataList() { return dataList; } public void setDataList(ArrayList dataList) { this.dataList = dataList; }}Copy the code
ImageBean
public class ImageBean { public String name; Public String imageUrl; Public String getName() {return name; } public void setName(String name) { this.name = name; } public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; }}Copy the code
Summary: Basically, we use reflection and FastJSON to return the type of entity class we need