Use the okhttp package of Android to upload and download files based on HTTP protocol

The HTTP connection foundation of okhttp only needs to provide a URL when sending HTTP requests using okhttp. Okhttp needs to comprehensively consider three different elements in its implementation to determine the actual HTTP connection with the HTTP server. The purpose of this is to achieve the best performance. The first element to consider is the URL itself. The URL gives the path to the resource to be accessed. Such as URL http://www.baidu.com The corresponding is the HTTP document on Baidu's home page. The more important part of the URL is the mode used when accessing, that is, HTTP or HTTPS. This will determine whether okhttp establishes a plaintext HTTP connection or an encrypted HTTPS connection. The second element is the address of the HTTP server, such as baidu.com. Each address has a corresponding configuration, including port number, HTTPS connection settings and network transmission protocol. URLs at the same address can share the same underlying TCP socket connection. There can be significant performance improvements through shared connections. Okhttp provides a connection pool to reuse connections. The third element is the route used when connecting to the HTTP server. Routing includes the IP address of the specific connection (found through DNS query) and the proxy server used. For HTTPS connections, it also includes the TLS version used in communication negotiation. For the same address, there may be multiple different routes. Okhttp automatically tries alternative routes when it encounters an access error. When requesting a URL through okhttp, okhttp first obtains the address information from the URL, and then obtains the connection from the connection pool according to the address. If no connection is found in the connection pool, select a route to try to connect. Trying to connect requires DNS query to get the IP address of the server, as well as proxy server and TLS version. After the actual connection is established, okhttp sends an HTTP request and obtains a response. When there is a problem with the connection, okhttp will automatically select another route to try. This allows okhttp to automatically deal with possible network problems. After successfully obtaining the response of the HTTP request, the current connection will be put back into the connection pool and provided to subsequent requests for reuse. The connection pool will periodically close idle connections to free up resources.

File upload and download examples: 1. Upload files without parameters

2. Upload files with parameters

3. Upload files with parameters and progress

4. Create requestbody with progress

5. Download without progress file

6. Download with progress file

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>