使用OKHttp,什么是AsyncTask的和OKhttp异步请求同步请求之间的区别? [英] Using OKHttp, what is the difference between synchronous request in AsyncTask and OKhttp Asynchronous request?

查看:2475
本文介绍了使用OKHttp,什么是AsyncTask的和OKhttp异步请求同步请求之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

OKHttp支持同步和异步API 。 如果我想发出一个异步请求,我可以:

OKHttp supports both synchronous and asynchronous api. If I want to issue an async request, I can:

  1. 使用一个AsyncTask的,并发出OKhttp同步API。
  2. 发出OKhttp异步API。

这两个选项之间的区别是什么?哪一个更好?

What is the difference between these 2 options? And which one is better?

推荐答案

相当多的不同!

使用的AsyncTask HTTP请求是pretty的多的最糟糕的事情,你可以在Android上做一。这是充满了问题和最好无条件地避免陷阱。例如,您无法取消执行过程中的要求。采用的模式的AsyncTask 也经常漏引用一个活动,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的异步大大优于原因是多方面的:

OkHttp's async is vastly superior for many reasons:

  • 在它支持原生抵消。如果一个请求是在飞行中,引用了回调被释放,永远不会被调用。此外,如果请求尚未开始它永远不会被执行。如果您正在使用HTTP / 2或SPDY我们实际上可以取消中间请求节省带宽和功耗。
  • 支持标记多个请求,并解除他们都用一个方法调用。这意味着每一个要求你做的,比方说,一个活动可以被标记与活动实例。然后,在的onPause 的onStop 则可以取消标记与活动的所有请求实例。
  • 如果您使用的是HTTP / 2或SPDY请求​​和响应复到远程服务器的单个连接,并使用异步呼叫机制,这是更有效比堵版。
  • It supports native canceling. If a request is in-flight, the reference to the 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.
  • It supports tagging multiple requests and canceling them all with a single method call. This means every request you make in, say, an Activity can be tagged with the Activity instance. Then in onPause or onStop you can cancel all requests tagged with the Activity instance.
  • If you are using HTTP/2 or SPDY requests and responses are multiplexed over a single connection to the remote server and by using the asynchronous Call mechanism this is much more efficient than the blocking version.

所以,如果可以的话,使用 Call.enqueue

So if you can, use Call.enqueue!

这篇关于使用OKHttp,什么是AsyncTask的和OKhttp异步请求同步请求之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆