Implement okhttp in Android to download files with a progress bar

Okhttp is a popular network framework. It supports synchronous and asynchronous requests, supports caching, can be intercepted, and is more convenient for downloading and uploading large files. Now we use okhttp to download files with a progress bar!

Relevant data:

Official website address: http://square.github.io/okhttp/

GitHub source address: https://github.com/square/okhttp

1、 Simple server-side construction

You can refer to this article on setting up a local Tomcat server and related configurations.

Create a new project okhttpserver, create a new downloadfile directory under the webcontent directory, and put the JPG file to be downloaded under the project. As shown below:

Start the server. The file download address is http://localhost:8080/OkHttpServer/download/2.jpg 。 So we can set up the server.

2、 Android terminal

Now let's get to the point.

1. The dependencies configuration of build.gradle is as follows:

2.activity_ main.xml

3. Prepare okhttputil as follows:

4. The progressresponsebody in the above code is a self written class, and the progresslistener is a listening interface:

Progresslistener interface

Progressresponsebody inherits ResponseBody and returns the listening progress

5. Code of mainactivity:

6. Finally, don't forget to add permissions:

Source download

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.

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
分享
二维码
< <上一篇
下一篇>>