A little knowledge of Android's network communication

network communication mechanism

The network is divided into: physical layer, data link layer, network layer, transport layer, session layer, presentation layer and application layer from bottom to top. The IP protocol corresponds to the network layer, the TCP protocol corresponds to the transport layer, and the HTTP protocol corresponds to the application layer. The three are essentially incomparable. The socket is the encapsulation and application of the TCP/IP protocol. It can also be said that the TCP/IP protocol is a transport layer protocol, which mainly solves how data is transmitted in the network, while HTTP is an application layer protocol, which mainly solves how to package data.

TCP/IP protocol

The purpose of network programming is to communicate with other computers directly or indirectly through network protocols.

There are two main problems in network programming, one is how to accurately locate one or more hosts on the network; the other is how to transmit data reliably and efficiently after finding the host. The most widely used Internet protocol is the TCP/IP protocol. In the TCP/IP protocol, the IP layer is mainly responsible for the location of network hosts and the routing of data transmission. An IP address can uniquely determine a host on the Internet. The TCP layer provides an application-oriented reliable or unreliable data transmission mechanism, which is the main object of network programming, and generally does not need to care about how the IP layer handles data.

Socket

We know that if two processes need to communicate, the most basic premise is that they can uniquely identify a process. In local process communication, we can use PID to uniquely identify a process, but the PID is only unique locally. Two processes in the network The probability of PID conflict is very high. At this time, we need to find another way. We know that the ip address of the IP layer can uniquely identify the host, and the protocol and port number of the TCP layer can uniquely identify a process of the host, so we can use the ip address + Protocol + port number uniquely identifies a process in the network. After the processes in the network can be uniquely identified, they can communicate using sockets. What is a socket? We often translate socket into socket. Socket is an abstraction layer between the application layer and the transport layer. It abstracts the complex operations of the TCP/IP layer into several simple interfaces for the application layer to call the implemented process in the network. Communication in. Socket has no necessary connection with the TCP/IP protocol. When the Socket programming interface was designed, it was hoped that it could also adapt to other network protocols. Therefore, the appearance of Socket just makes it easier for programmers to use the TCP/IP protocol stack, which is an abstraction of the TCP/IP protocol.

HTTP protocol

The HTTP protocol is the Hypertext Transfer Protocol (Hypertext Transfer Protocol), which is the basis of Web networking and one of the commonly used protocols for mobile phone networking. The HTTP protocol is an application built on top of the TCP protocol. The most notable feature of HTTP connections is that each request sent by the client requires the server to send back a response, and the connection will be actively released after the request ends. The process from establishing a connection to closing it is called a "one-time connection". HTTP provides a concrete form for encapsulating or displaying data. Socket provides the ability for network communication.

HTTPS protocol

HTTPS (full name: Hypertext Transfer Protocol over Secure Socket Layer) is a secure HTTP channel, in short, a secure version of HTTP. That is to say, the SSL layer is added under HTTP, and the security foundation of HTTPS is SSL, so the detailed content of encryption requires SSL. It is a URI scheme (abstract identifier scheme) with a syntax similar to the http: scheme. For secure HTTP data transfer. The https: URL indicates that it uses HTTP, but HTTPS has a different default port than HTTP and an encryption/authentication layer (between HTTP and TCP). Widely used for security-sensitive communications on the World Wide Web, such as transaction payments.

Android network permissions

<uses-permission android:name="android.permission.INTERNET" /><-- 允许应用程序打开网络套接字 -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /><-- 允许应用程序访问网络连接信息 -->

Choose an HTTP Client

Most web-connected Android apps use HTTP to send and receive data. Android provides three HTTP clients: HttpURLConnection, Apache HttpClient and okhttp. Both support HTTPS, streaming uploads and downloads, configurable timeouts, IPv6 and connection pooling.

  • HttpURLConnection class in Java .NET package

  • HttpUrlConnection is the networking API provided in the JDK. We know that the Android SDK is based on Java, so of course, the most primitive and basic API, HttpUrlConnection, is given priority. In fact, most open source networking frameworks are basically encapsulated based on JDK's HttpUrlConnection.

  • HttpClient

    HttpClient is a Java request network framework provided by the open source organization Apache. It was first born to facilitate the development of Java servers. It encapsulates and simplifies the APIs of HttpUrlConnection in JDK, improves performance and reduces the tediousness of calling APIs. Therefore, this networking framework is also introduced, and we can use it directly without importing any jar or class library. It is worth noting that the Android official has announced that the use of HttpClient is not recommended. It was deprecated in Api22, and should be gone now.

  • okhttp

    HTTP is the network request method used by mainstream applications to exchange data and content. Effective use of HTTP can make your APP faster and reduce traffic usage.

    OkHttp is a great HTTP client:

    • Support SPDY, can combine multiple requests to the same host

    • Use connection pooling techniques to reduce request latency (if SPDY is available)

    • Reduce the amount of data transferred using GZIP compression

    • Cache responses to avoid repeated network requests

    When your network is congested, that is when OKHttp comes into play. It can avoid common network problems. If your service is deployed on a different IP, if the first connection fails, OkHTtp will try other connections. This is also necessary to deploy service redundancy in different data centers, which is now common in IPv4+IPv6. OkHttp will use the current TLS feature (SNI ALPN) to initiate new connections, and will switch to TLS 1.0 if the handshake fails. Using OkHttp is easy and supports both asynchronous blocking requests and callbacks. If you use OkHttp, you don't have to rewrite your code, the okhttp-urlconnection module implements the API in java.net .HttpURLConnection, and the okhttp-apache module implements the API in HttpClient, but it's better to use OkhttpUtils (which is encapsulated by okhttp) ), the network request is simpler and more convenient.

There are also many third-party network request frameworks

1.volley

Volley's Chinese translation is "salvo, concurrent". It is an Android platform network communication library released at the Google Conference in 2013. It has functions such as network request processing, asynchronous loading and caching of small pictures, and can help Android APP. Perform network operations more easily and more quickly and efficiently.

Advantages: 
(1) Automatically schedule network requests; 
(2) High concurrent network connections; 
(3) Cache disk and memory transparent responses through standard HTTP cache coherence (cache coherence); 
(4) Support specifying request priorities (Priority ordering of the request queue); 
(5) Provide various cancellation mechanisms: the network request cancel mechanism, we can cancel a single request, or specify an area in the cancellation request queue; 
(6) The framework is easy to be customized, for example, customized Retry or rollback function; 
(7) Contains debugging and tracking tools; 
(8) The default Android 2.3 and above is based on HttpURLConnection, and below 2.3 is based on HttpClient 
(9) Provides a simple image loading tool (in fact, the loading of images is Our most valued feature)

Disadvantages: 
(1) Can't download files: this is also its most deadly place

Official website or related address: 
  Volley's github address: https://github.com/mcxiaoke/android-volley
 Google I/O 2013 – Volley: Easy, Fast Networking for Android:                                                     https://www.youtube.com/watch ?v=yhv8l9F44qo&feature=player_embedded 
 Simple to use: http://www.dengzhr.com/others/mobile/android/762

2.Android-async-http

Android-async-http is a powerful network request library. This network request library is an asynchronous network request processing library based on the Apache HttpClient library. The network processing is based on Android's non-UI thread, and the request result is processed through the callback method. 
android-async-http is a powerful third-party open source network request library. Unfortunately, the Android 6.0 (api 23) SDK no longer provides org.apache.http.* (only a few classes remain).

Advantages: 
(1) Process request result in anonymous callback 
(2) HTTP request outside UI thread 
(3) File breakpoint upload 
(4)  Smart retry 
(5) Default gzip compression 
(6) Support parsing into Json format 
( 7) Cookies can be persisted to SharedPreference

Official website or related address: 
github address of Android-async-http: https://github.com/loopj/android-async-http 
Official website tutorial: http://loopj.com/android-async-http/

Next, let's take a look at the two frameworks Afinal framework and xUtils encapsulated by our Chinese. These two frameworks are very rich in functions, and even provide database encapsulation, which is in line with the apps developed by our Chinese, which are a lot of All the functions of the network are integrated, is such a powerful network framework really that powerful? Usually we think like this: the more feature-rich an open source framework is, the more functional it is, such as the network framework, is it better than other network-specific frameworks?

Note: The author of this framework has stopped updating, so it is now deprecated

3.Afinal framework

Afinal is a sqlite orm and ioc framework for android. At the same time, it encapsulates the http framework in android, making it easier to use; using finalBitmap, there is no need to consider the problem of oom when bitmap is loaded in android and the problem of image loading position dislocation when sliding quickly.

Afinal's mission is to be concise and fast. The convention is greater than the way of configuration. Try to do everything in one line of code.

Afinal is mainly divided into four modules: 
(1) Database module: Orm framework in android, using thread pool to operate sqlite. 
(2) Annotation module: The ioc framework in android can perform UI binding and event binding in a fully annotated way. No need to findViewById and setClickListener etc. In fact, it is initialized using reflection. 
(3) Network module: Encapsulate http data requests through httpclient, support ajax loading, and support the functions of downloading and uploading files. 
(4) Picture cache module: When loading bitmap through FinalBitmap, imageview does not need to consider the phenomenon of oom and picture dislocation when the android container slides quickly during the bitmap loading process.

Official website or related address: 
github address of Afinal framework: https://github.com/yangfuhai/afinal

Note: The author of this framework has stopped updating, so it is now deprecated

4.xUtils

xUtils is the same type of framework as Afinal, and now the author has not updated it two or three years ago.

Introduction to the official website: 
xUtils3 api has changed a lot, and has been transferred to  https://github.com/wyouflf/xUtils3 
xUtils 2.x is not very compatible with Android 6.0, please upgrade to xUtils3 as soon as possible. 
xUtils contains many useful android tools . 
xUtils supports large file upload, more comprehensive http request protocol support (10 kinds of predicates), more flexible ORM, more event annotation support and is not affected by confusion... 
xUitls is at least compatible with android 2.2 (api level 8)

Official website or related address: 
github address of Afinal framework: https://github.com/wyouflf/xUtils

Note: The author of this framework has stopped updating, so it is now deprecated

The above network framework is actually only personal, so it is not recommended to use it, or it is too rich in functions. If it is used in mainstream apps, it will cost a lot for later maintenance. For example, if you find that a certain function in your framework is not suitable for use, and you need to replace this part of the framework, you will find that the shadow of this framework does not appear in your entire project, and the cost of post-maintenance is too great!

The following network frameworks (okhttp, retrofit) are the best network frameworks at present, and the company also found that many projects use these network frameworks. These two network open source frameworks are provided by square company. In the open source world, there are two network frameworks provided by two companies that are very rich, one is square and Facebook, and I sincerely thank these two companies.

5.OKHttp

OkHttp is a relatively mature solution. It is said that HttpURLConnection has been replaced by OkHttp in the source code of Android 4.4. In Android 6.0, the underlying source code has used OKHttp, which is certain.

OkHttp handles a lot of network complications: it automatically recovers from many common connection problems. If your server is configured with multiple IP addresses, when the first IP connection fails, OkHttp will automatically try the next IP. OkHttp also handles proxy server issues and SSL handshake failures.

Using OkHttp eliminates the need to rewrite the networking code in your program. OkHttp implements almost the same API as Java .NET .HttpURLConnection . If you use Apache HttpClient, OkHttp also provides a corresponding okhttp-apache module.

Official website or related address: 
github address of OKHttp: https://github.com/square/okhttp

6.retrofit

In fact, retrofit is a framework encapsulated by OKHttp, and its underlying network requests use OKHttp. The author of this framework is also very famous, namely Jake Wharton. Simply my idol!

Advantages: 
(1) Support okhttp 
(2) Annotation processing, simplify code 
(3) Support uploading and downloading files 
(4) Support own replacement of parsing methods 
(5) Support multiple http request libraries

Official website or related address: 
github address of OKHttp: https://github.com/square/retrofit

2. Insights on choosing an open source framework

1. The cost of learning: the length of time to learn the framework, and whether the documentation is complete 
2. Popularity: whether the open source framework is popular, the number of starts on github, are the criteria we consider 
3. Whether it is still maintained : If the framework is no longer maintained, with the continuous updating of technology, there will be large and small problems. 
4. Code volume: Of course, the volume should not be too large. 
5. Code design: The design of the overall framework

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325650455&siteId=291194637