OKHttp 同时支持同步和异步api.如果我想发出异步请求,我可以:
OKHttp supports both synchronous and asynchronous api. If I want to issue an async request, I can:
这两个选项有什么区别?哪个更好?
What is the difference between these 2 options? And which one is better?
差别很大!
对 HTTP 请求使用 AsyncTask
几乎是您在 Android 上可以做的最糟糕的事情之一.它充满了最好无条件避免的问题和陷阱.例如,您不能在执行期间取消请求.使用 AsyncTask
的模式通常也会泄露对 Activity
的引用,这是 Android 开发的一大罪过.
Using AsyncTask
for HTTP requests is pretty much one of the worst things you can do on Android. It's fraught with problems and gotchas that are best unconditionally avoided. For example, you cannot cancel a request during execution. The patterns of using AsyncTask
also commonly leak a reference to an Activity
, a cardinal sin of Android development.
OkHttp 的 async 非常优越,原因有很多:
OkHttp's async is vastly superior for many reasons:
Callback
的引用将被释放并且永远不会被调用.此外,如果请求尚未开始,它将永远不会被执行.如果您使用的是 HTTP/2 或 SPDY,我们实际上可以取消中间请求以节省带宽和功率.Activity
中发出的每个请求都可以使用 Activity
实例进行标记.然后在 onPause
或 onStop
中,您可以取消所有带有 Activity
实例标记的请求.Call
机制,这比阻塞版本更有效.Callback
is freed and will never be called. Additionally, if the request has not started yet it never will be executed. If you are using HTTP/2 or SPDY we can actually cancel mid-request saving bandwidth and power.Activity
can be tagged with the Activity
instance. Then in onPause
or onStop
you can cancel all requests tagged with the Activity
instance.Call
mechanism this is much more efficient than the blocking version.因此,如果可以,请使用 Call.enqueue
!
So if you can, use Call.enqueue
!
这篇关于使用OKHttp,AsyncTask中的同步请求和OKhttp异步请求有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!