Usage analysis of Android okhttp
Okhttp is a network framework launched by Android 6.0. Since Google cancelled the httpclient related attributes after Android 6.0, the volley framework can not be used normally. That's why we have today's okhttp.
Okhttp usually has two ways to access the network, one is get request, and the other is post request.
1. Get request for okhttp
Usually, we use get to request a website, which depends on the URL address. Okhttp uses the get method to request the website, which usually has the following steps:
A. Create the okhttpclient variable, which is equivalent to a global executor. The main network operation depends on it.
B. Create a builder object.
C. Use the builder object to create a request object.
D. Use the global performer to create a call object.
E. Make a network connection through the call object.
2. Okhttp's post request
The post request is somewhat different from the get request. The main function of get request is to obtain data from the server, while post request is to submit data to the server.
3. The server receives the string from the client
Client code:
Server side code:
If the server wants to receive data from the client, it needs to receive a request; If the server wants to transfer data to the client, it needs to pass it through response.
4. Use post mode to transfer files
Client code
About the code for selecting files -- plagiarize the code on the network and don't write it yourself
During this operation, you must remember to increase the read and write permissions, otherwise the upload will fail.
Server side code
The files file shown above is the FIEs folder under the project name file under Tomcat's webapps (there was no such folder at first, so you need to create it yourself manually).
5. Upload files by post
Client code:
Server side code:
When uploading files, I noticed one small detail: Tomcat server only allows uploading files below 2m. To upload a large file, you must add a sentence to the struct file: < constant name = "struts. Multipart. Maxsize" value = "1024000000" / > the number indicates the user-defined size limit.
6. There is a problem with the display of progress when uploading files
When writing code, we know that we can't directly get the progress of uploading files. Because these data are encapsulated in the requestbody, you can only use the callback interface.
The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.