Okhttp, retrofit progress acquisition method (one line of code)

cause

For the majority of Android developers, the most recently used network library is okhttp (retrofit relies on okhttp).

Unlike the built-in httpurlconnection in the SDK, okhttp can explicitly obtain the data reading and writing process. We need to perform some operations.

introduce

Retrofit depends on okhttp and okhttp depends on okio. So what the hell is okio? Okio is a library that complexes java.io and java.nio to make it much easier to access, store, and process your data

Okio is a class library that implements java.io and java.nio. It makes it easier to connect, store and process your data ~ (okio is both a reading and writing related class library, and the progress should be obtained from okio).

Well, for the majority of developers, the heart is like this: TM has to look at your documents and use cases, follow your rules, relax!

In fact, after reading the API and looking at example, the design of others is still great.

Don't talk more nonsense. Let's see the effect first.

effect

Actual code:

You only need one line of code! Why can I? Because this is the encapsulated class library I wrote ~ (the last address)

thinking

Okhttp relies on okio to read and write data. We need to find okio for processing. So, how to add?

Okhttp can add an interceptor. We can obtain the corresponding ResponseBody and requestbody objects through the interface method of the interceptor for operation. Then we get the implementation methods related to reading and writing. The specific implementation is through source and sink objects.

Source official explanation: supplies a stream of bytes. Use this interface to read data from wherever it's located.

Sink official explanation: receives a stream of bytes. Use this interface to write data wherever it's needed.

In one sentence: the source object is the packaging of the input stream (downloading and reading data), and the sink is the packaging of the output stream (writing and uploading data).

realization

Add, download and upload interceptors as needed

Concrete implementation of interceptor

summary

The above is the specific process. The steps are actually very simple. It's good for you to understand. I have also encapsulated the specific class library and demo, which you can rely on directly (see readme.md, easy to use).

Address: https://github.com/HoldMyOwn/TNetProgress

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