Android--Android mainstream network framework

With the development of Android to the present, the network framework has been updated. At present, there are four major mature frameworks. This article briefly analyzes the implementation principles of the major frameworks. For specific usage, please refer to the link given in the article.

Android mainstream framework

Retrofit

Okhttp

Volley

AsyncHttpClient

Retrofit

Features

  • Dynamic proxy
  • Adapt conversion Call object
  • Function analysis, network request and data conversion

interface

 

public interface ApiService{
    
    // 与Rxjava结合使用
    @POST(NetUrl.HOME_URL)
    public Obserable<HttpResult<HomeResponse>> getHomeList(@BODY BodyRequest body);

    @GET(NetUrl.VERSION_URL)
    public Obserable<HttpResult<VersionResponse>> getVersionDetail();

    // 没有添加Call回调处理,直接返回Okhttp的Call
    @Get(NetUrl.USER_URL)
    public Call<HttpResult<UserResponse>> getUser(@Query("uid") long uid)
}

principle

image

 

Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(Config.BASE_URL) // baseUrl 以/结尾
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) // 添加Call回调
            .addConverterFactory(GsonConverterFactory.create()) // 解析器
            .client(okHttpClient) //配置okHttpClient
            .build();

ApiService service = retrofit.create(ApiService.class);
// 在业务层调用ApiService的方法
service.getVersionDetail();

1. retrofit.create(ApiService.class)Retrofit binds the interface to Okhttp through a dynamic proxy

 

public <T> T create(final Class<T> service) {
...
    return (T) Proxy.newProxyInstance(service.getClassLoader(), new Class<?>[] { service },
        new InvocationHandler() {
            ...
            ServiceMethod<Object, Object> serviceMethod =
                (ServiceMethod<Object, Object>) loadServiceMethod(method);
            OkHttpCall<Object> okHttpCall = new OkHttpCall<>(serviceMethod, args);
            return serviceMethod.callAdapter.adapt(okHttpCall);
          }
        });
}

2. Maintain Okhttp internally, network requests are completed by Okhttp, Retrofit is only responsible for production

3.Call callback, which is actually the Call callback of Okhttp, corresponding to the configuration .addCallAdapterFactory(RxJava2CallAdapterFactory.create()), if there is no such configuration, the Call<Bean>object will be returned

4. The data analysis in the Call callback method corresponds to the configuration .addConverterFactory(GsonConverterFactory.create()). It can also be Jsonfastan analysis conversion factory or a custom analysis factory. You only need to implement the Retrofitgiven data analysis interface. You can refer to GsonConverterFactorythe implementation

Okhttp

principle

The bottom layer of OkHttp is to send HTTP or HTTPS requests and receive responses through Java Sockets, but OkHttp implements the concept of connection pooling, that is, for multiple requests from the same host, you can actually share a Socket connection instead of sending HTTP requests every time. Close the underlying Socket, so that the concept of connection pool is realized. OkHttp encapsulates the OkIo library used for Socket read and write operations.

image

The protagonists of OkHttp

OkHttpClient

Factory for calls, which can be used to send HTTP requests and read their responses.
Plant producer, responsible for the production calls

Request

OkHttp request, by Request.Builder().buildcreating and Request.Builder()configuring request information, such as request method get/post, request parameters RequestBody, request headerheader

Call

The dispatcher, Call is the top-level interface, and RealCall is responsible for the specific implementation. Responsible Requestand Responsebridge will Requestin a execute()synchronous manner performs output Response, or Requestto enqueue(callback)asynchronously added to scheduling.

Dispatcher(ThreadPoolExecutor)

The scheduling thread pool Disptcher achieves high concurrency and low blocking. Using Deque as a cache, the first-in first-out order execution
task calls the finished function in try / finally to control the execution order of the task queue, instead of using locks, reducing coding complexity and improving performance.
Only when Call is requested asynchronously, It only triggers Dispatcher's scheduling work.

Response

Response, including information such as code, message, header, body, etc.

 

 

// 1.创建Client
OkHttpClient client = new OkHttpClient.Builder().build()
// 2.创建Request
Request reuqest = new Request.Builder().get().url(url).builder()
// 3.call execute同步
Response response = client.newCall(request).execute()
// 异步,回调在子线程中执行
client.newCall(request).enqueue(new Callback{
        @Override
        public void onFailure(Call call, IOException e){
        }
        @Override
        public void onResponse(Call call, Response response){
        }
    }) 

Volley

image

RequestQueue

  • StringRequest
  • JsonRequest
  • ImageRequest

Diapatch Thread

  • MainDispatcher
  • CacheDispatcher
  • NetworkDispatcher
  • ImageDispatcher

Get Data Interface

  • HttpStack
    processes the Http request and returns the request result. Currently Volley has HurlStack based on HttpURLConnection and HttpClientStack based on Apache HttpClient

  • ResponseDelivery (Return result distribution interface, currently only based on ExecutorDelivery is distributed in the thread corresponding to the input parameter handler.)

Data

  • Cache (Volley uses DiskBasedCache based on sdcard by default)
  • Network(NetworkResponse)

to sum up

Continuously fetch requests from RequestQueue through two Dispatch Thread, call one of the two types of data acquisition interfaces, Cache or Network, according to whether it has been cached, obtain the requested data from the memory cache or server, and then hand it to ResponseDelivery to do the result distribution and callback deal with.

AysncHttpClient

Apache HttpClient uses asynchronous thread management to manage the request thread. The main analysis will not be done here. . .

Framework Information / Official Document Reference

Retrofit

Okhttp

Volley source code Volley analysis

AsyncHttpClient



Author: ReeseLuo
link: https: //www.jianshu.com/p/7a970db4e7cf
Source: Jane books
are copyrighted by the author. For commercial reproduction, please contact the author for authorization, and for non-commercial reproduction, please indicate the source.

Published 7 original articles · 69 praises · 200,000+ views

Guess you like

Origin blog.csdn.net/u014320421/article/details/105217542