The Network request framework used in the android project and how to configure the interface URL and androidurl
Network requests are indispensable in our project. Many companies use some good open-source frameworks for network requests. volley is used in our project, now let's talk about the basic usage of volley. If you want to know more about it, you should check its source code. Now I am posting code to talk about its usage,
First, use a class to encapsulate its basic configuration information. If you need to change it later, you can directly modify it here. android is best to separate each function, such modifications will not cause other bugs, especially when new employees enter the project team, and assigning tasks is easy to communicate,
ProtocolManager. java it is a singleton
Key code
private ProtocolManager(Context context){ initLoadBitmapConfig(context); mQueue = Volley.newRequestQueue(context);}
We only need to do this when calling the interface:
Map <String, String> param = new HashMap <String, String> (); param. put ("checksum", 0 + ""); ProtocolManager. getInstance (). request (ProtocolEnum. URL_CONSTANCE_CONF_REGIONS, param, new RequestListener () {@ Overridepublic void onRequestSucess (String response) {if (! TextUtils. isEmpty (response) {AllProvinceInfo provinceInfo = JsonHelper. json2Bean (response, AllProvinceInfo. class); if (provinceInfo! = Null & provinceInfo. getRet () = 1) {provinces = provinceInfo. getItems (); if (provinces! = Null & provinces. size ()> 0) {/*** cache the requested json data to the SD card */DataManager. getInstance (UIUtils. getContext ()). saveCacheStr (CACHE_AREA, response); mHandler. sendEmptyMessage (AREA_CODE_SUCCESS);} else {mHandler. sendEmptyMessage (AREA_CODE_EMPTY) ;}}@ Overridepublic void onRequestFiled (String errorMsg) {mHandler. sendEmptyMessage (AREA_CODE_FAIAL );}});
Method in request
public void request(ProtocolEnum protocolEnum,final Map<String,String> params,final RequestListener listener){int type = protocolEnum.type;String url = protocolEnum.value;switch (type) {case ConfigManager.REQ_POST:requestPost(url, params,listener, false);break;case ConfigManager.REQ_GET:requestGet(url, params,listener, false);break;}}
The first parameter is an enumeration that contains the url address and request method.
ProtocolEnum. java
Public enum ProtocolEnum {URL_PROFILE_INTRODUCTION_GET ("user/profile/introduction", ConfigManager. REQ_GET); // drop-down personal profile public String value; public int type; private ProtocolEnum (String value, int type) {this. value = value; this. type = type ;}}
This is how to manage the request URL, and finally there will be a success or failure callback in the Volley request to put the json data, so we will add an interface later, as long as copy, change the returned model object, which greatly improves the development efficiency.