OkHttp framework,
Introduction: an open-source project that processes network requests is the hottest Lightweight Framework on Android. It is contributed by mobile payment Square to replace HttpUrlConnection and Apache HttpClient. OkHttp supports Android 2.3 and later versions and requires JDK 1.7 and later versions. OkHttp has a slight difference in the use of some methods between 2.x and OkHttp3.x versions.
Advantages:
1. Allow all requests connected to the same host address to improve the request Efficiency
2. Share the Socket to reduce the number of requests to the server
3. The connection pool reduces the request latency.
4. cache response data to reduce repeated network requests
5. reduced data traffic consumption
6. Automatic GZip Compression
Before using OkHttp, you must introduce the OkHttp package in the project. OkHttp also depends on another okio package. You can also fill in the build. gradle configuration file in the corresponding model, and synchronize the project. The environment will automatically download the required package:
Compile 'com. squareup. okhttp3: okhttp: 3.2.0 'compile 'com. squareup. okio: 1.7.0' // you can modify the version number.
The basic classes required for OkHttp's first learning include OkHttpClient, RequestBody, Request, Call, and Response ......
1. OkHttpClient:
There are two ways to create Object Instantiation for this class: Standard default type and custom form
// Standard Format: OkHttpClient mOkHttpClient = new OkHttpClient (); // custom format: OkHttpClient mOkHttpClient = new OkHttpClient. builder (). connectTimeout (10, TimeUtil. SECONDS) // set the default connection timeout length for the new connection. The first parameter is large or small, and the second parameter is the unit. readTimeout (10, TimeUtil. SECONDS) // set the default read timeout duration for the new connection. writeTimeout (10, TimeUtil. SECONDS) // set the default write timeout duration for the new connection. cache (setCache) // set the response cache for reading and writing cache responses [1]. build ();
[1]: The parameter is the Cache object File filePath = new File (getExternalCacheDir (), "netCache"); int cacheSize = 10*1024*1024; Cache setCache = new Cache (filePath, cacheSize); note: In OkHttp2. +, set the above timeout methods and 3. + different versions: mOkHttpClient. setConnectTimeout (10, TimeUtil. SECONDS); mOkHttpCLient. setConnectTimeout (10, TimeUtil. SECONDS); mOkHttpClient. setConnectTimeout (10, TimeUtil. SECONDS); mOkHttpClient. setCache (setCache );
2. RequestBody:
This class is used for the post method of OkHttp and is a request body class for data uploading.
Core Methods: contentType, contentLength, create, writeTo method ......
Public abstract MediaType contentType () public long MediaType contentLength () public abstract void writeTo (BufferedSink sink) public static RequestBody create (MediaType contentType, String content) [2] // [2]: the second parameter can be of multiple types. The class has multiple create overload methods. The api points to this // Class Object Instantiation method:
MediaType mMediaType = MediaType. parse ("application/octet-stream"); // putFile https://tool.oschina.net/commonsFile = new File (Environment. getExternaStorageDirectory (), "file name. extension "); // The parent path and sub-path are concatenated into the absolute file address RequestBody mRequestBody = RequestBody. create (mMediaType, putFile); [3] // [3]: the first and second parameter types are various. The create method is generally used to upload file or string data, another method (FormBody) RequestBody mRequestBody = FormBody will be used to upload key-Value Pair type data. builder (). add ("key", "value1 "). add ("key", "value2 "). build ();
3. Request:
This class is used to generate network connection request objects, including multi-medium information: Request Parameters, request headers, request methods...
Common methods include url, post, method, headers, etc.
Request mRequest = new Request. builder (). url ("https://www.baidu.com "). post (mRequestBody) [4]. build ();/* [4]: If the post method is not displayed, this network request uses the get method to request the network. The parameters are examples of the Request body object, using post to upload data is safer than using get, and the data size is not limited. More parameters can be passed (for long form data, it is useful to upload files )*/
4. Call:
This class is the last object that requires an instance for network request execution. This class provides synchronous and asynchronous Connection Methods for network requests. All connections are not in the UI thread. If after a network request, handler needs to be called to update the UI layout. The method is runOnUiThread ().
Call mCall = mOkHttpClient. newCall (mRequest); // use an asynchronous network to connect to mCall. enqueue (new CallBack () {@ override public void onFailure (Call call, IOException e) {// Network Connection Failed} @ override public void onResponse (Call call, Response response) {if (response. isSuccessful () {// The request data is successful. The Returned code is 200 ~ 300 [5]} else {// data request failed}); [5]: response. isSuccessful () source code: public boolean isSuccessful () {return code >=200 & code <= 300 ;}// you must enable a new sub-thread to use synchronization, time-consuming operations cannot run new Thread (new Runnable () {Call mCall = mOkHttpClient in the main UI Thread. newCall (mRequest); Response mResponse = mCall.exe cute (); // next, Let's explain if (mResponse. isSuccessful () {// The network synchronization request is successful. to update the UI layout, use the runOnUiThread method} else {}}). start (); // start the thread using the start method after creating a subthread. Note: runOnUiThread (new Runnable () {@ override public void run () {// update the UI logic code}); // the synchronous method will block the execution of the current thread, and the asynchronous method will not block the execution of the current thread
5. Response:
This class is the Response information object after the network request. The data returned by the server is stored in this example object, and only one valid call can be made to the Response instance in one request, if a program is called twice, a program error occurs. Therefore, the data in the Response instance must be saved before you need to use the data multiple times. The Response class provides multiple methods: body, code, protocol, request, isSuccessful, headers (response header object), toString...
Response mResponse = mCall.exe cute (); if (mResponse. isSuccessful () {String str = mResponse. body (). string (); [6] int code = mResponse. code (); Protocol protocol = mResponse. protocol (); Request request = mResponse. request (); String head = mResponse. toString (); Log. I ("Response information set:", "" + str + code + protocol + request + head);}/* [6]: The body indicates that the retrieved data has no content, the data can be converted into string, byte stream, byte stream, byte array, and other forms of data. With this attribute, the OkHttp file download function is enabled. Of course, files can be uploaded, this is related to. The RequsetBody instance method in the second point can "place" the local file to the Request body. This is, when receiving parameters, the server can obtain the file data uploaded by the user */After learning these five points, you can write basic get, post synchronous or asynchronous network connections. For the client class that OkHttpClient represents an HTTP request, we recommend that you create only one instance for this object in most cases.
Here is a complete example of the asynchronous method for post requests:
Public class PostAsyn () {private TextView tvShowNetInfo; public static OkHttpClient okHttpClient; static (okHttpClient = new OkHttpClient. builder (). connectTimeout (15, TimeUnit. SECONDS ). readTimeout (15, TimeUnit. SECONDS ). writeTimeout (15, TimeUnit. SECOND ). build (); @ Overvide public void onCreate (Bundle saveInstanceState) {super. onCreate (saveInstanceState); setContentView (R. layout. activity_main); tvShowNetInfo = (TextView) findViewId (R. id. TV _show_net_info); postAsynDate ();} public void postAsynData () {RequestBody requestBody = new FormBody. builder (). add ("key1", "value1 "). add ("key2", "value2 "). build (); Request requset = new Request. builder (). url (" https://www.baidu.com "). Post (requestBody ). build (); Call call = okHttpClient. newCall (request); call. enqueue (new Callback () {@ Overvide public void onFailure (Call call, IOException e) {goUiThread ("network connection failed");} @ Overvide public void onResponse (Call call Call, response response) {if (response. isSuccessful () {goUiThread ("request data successful, response code:" + response. code ();} else {goUiThread ("network connection succeeded, but no response data, response code:" + response. code () ;}}) ;}private void goUiThread (final String str) {runOnUiThread (new Runnable () {@ Overvide public void run () {tvShowNetInfo. setText (str) ;}}}/// the corresponding layout file is omitted // This is only a basic OkHttp operation, it also provides more advanced use, such as using cache, send complex request bodies