What is stratification

In the evolution of app architecture, whether it’s MVC,MVP,MVVM, the concept of layering and decoupling is always running through the architecture. So how does this delamination and decoupling manifest itself? In simple terms, my layer receives input from the upper layer, and whatever I do with the upper layer, I will eventually give you an output/return value, and you don’t care what I do with it. As long as there is input, there will be output, usually through a simple method call.

Then, what is the most reasonable encapsulation for the network layer commonly used in APP?

Our slogan is: One line of code to complete a network request!

It’s pretty simple. Look at the interface documentation and you’ll see how to do it: just pass those parameters and return the json or something. By turning the interface document into a method we call, the interface between the network layer and the upper layer can be said to be designed.

The most common character stream requests:

What does the interface document say :(baidu pictures randomly find a)

Therefore, our network layer should encapsulate a method like this:

# # to:

Request mode, URL path, request parameters Key and value Note: For multiple POST request parameters key-value, some interfaces are defined in Map format, and some in Json format. It’s essentially the same thing, Posting a string (string stream) on the requestBody, except that the former is a=4&t=5 and the latter is a JSON form. Generally speaking, the former is more common, after all, parameter splicing form is consistent with GET request, server side processing is more convenient.

Output/return:

In the case of returning character stream data, it can be reduced to returning a String object, depending on the situation.

A common one in apps is to return a string in JSON format. Of course, the general app needs to be parsed javabean, so the network framework interface should be able to return a parsed Javabean directly.

Of course, taking a step further, most canonical apis (look at the major API markets, such as aggregation apis) return json formats with the following characteristics:

Status code is commonly three fields, respectively, a prompt information, and one for carrying data fields. (for example: {” code “: 0,” MSG “:” login succeeds “and” data “: {… }}). Fields that carry data can carry any type of data, including NULL, numbers, strings,jsonObject, and JsonArray. Here, I refer to this three-field JSON as “standard-format JSON.”

Encapsulated method:

getString(String url, Map map, MyNetListener listener)// Get request, return string, get the string
postString( String url,  Map map,  MyNetListener listener)

getCommonJson(String url, Map map, Class clazz, MyNetListener listener)// Get request, return a JSON, parse the entire JSON into a Javabean
postCommonJson(String url, Map map, Class clazz, MyNetListener listener)

getStandardJson(String url, Map map, Class clazz, MyNetListener listener)// Get request, return json in standard format
postStandardJson(String url, Map map, Class clazz, MyNetListener listener) // A post request that returns a standard-format JSON, directly parses the Javabeans that return the data field via the clazz passed in

// If the argument is issued as json, then call setParamsAsJson().Copy the code

# Upload and download

Download:

Usually a GET request, passed in the URL. Request parameters are optional. The final download results in a file (the path can be specified in advance) with scheduled callbacks during the download. Note: I don’t need to know the details of your network stream, breakpoint download, shard and multithreaded download.

download(String url, String savedpath, MyNetListener callback)Copy the code

Upload a POST request, pass in the URL, request parameters, file key name, file address, return a result (success or failure), and have a progress callback during upload. Similarly, the upper layer does not need to know the details of header Settings, breakpoint uploads, shard uploads, etc. Note: HTTP supports multiple file uploads.

upLoad(String url, Map<String.String> params,Map<String.String> files, MyNetListener callback)Copy the code

Student: You said it’s also very common to pull web images and display them in imageView? That’s the picture loading framework, not the web framework. Recommend fresco, and this FrescoUtils of mine.

A mind map overview of the above API

Basic API. JPG

Data returned: Uniform callback

Callbacks take the form of abstract classes, not interfaces

public void onPreExecute() {}// The beginning of unification
public void onFinish(){}// The end of unification

public  void onEmpty(){}// When the content is empty -- typically used when returning an empty jsonArray ([]).


// There are several cases of success:
public abstract void onSuccess(T response,String resonseStr);/ / the main callback

public  void onSuccessArr(List<T> response,String resonseStr){}// Main callback, overwrite if needed

public  void onSuccessObj(T response,String responseStr,String data,int code,String msg){
        onSuccess(response,responseStr);
}

public  void onSuccessArr(List<T> response, String responseStr, String data, int code, String msg){
    onSuccessArr(response,responseStr);
}

// Failed callback

public void onError(String msgCanShow) {}/ / the main callback

 public void onUnFound() {
    onError("This content was not found");
}
public    void onUnlogin(){
    onError("You are not logged in.");
}


 public void onCodeError(String msgCanShow,String hiddenMsg,int code) {
    if (TextUtils.isEmpty(msgCanShow)){
        onError("Error code :"+code);
    }else{ onError(msgCanShow); }}// Schedule callback
public void onProgressChange(long fileSize, long downloadedSize) {}Copy the code

Customize some parameters of the request

There’s nothing to say. Just look at the picture. Clear and clear, okay

Api.jpg for custom Settings

A sample request

            Map map8 = new HashMap<>();
            map8.put("versionName"."1.0.0");
            map8.put("appType".0);
            MyNetApi.postStandardJson("http://app.xxtt.com:9090/app/appVersion/getLatestVersion",
                    map8, VersionInfo.class, new MyNetListener<VersionInfo>() {
                        @Override
                        public void onSuccess(VersionInfo response, String resonseStr) {
                            Logger.e(resonseStr);
                        }

                        @Override
                        public void onError(String msgCanShow) {
                            super.onError(msgCanShow);
                            Logger.e(msgCanShow);
                        }
                    })
                    .setParamsAsJson()
                    .setIsAppendToken(false)
                    .setCustomCodeValue(1.2.3)
                    .start();Copy the code

code

Github.com/hss01248/Ne…

# Attached picture: Overall hierarchy diagram

Ps. Yes, I didn’t use Rxjava because I’m used to the callback mode, where the code is aggregated.