使用OKHttp,AsyncTask中的同步请求和OKhttp异步请求有什么区别?

Using OKHttp, what is the difference between synchronous request in AsyncTask and OKhttp Asynchronous request?(使用OKHttp,AsyncTask中的同步请求和OKhttp异步请求有什么区别?)

本文介绍了使用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?

推荐答案

差别很大!

对 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 实例进行标记.然后在 onPauseonStop 中,您可以取消所有带有 Activity 实例标记的请求.
  • 如果您使用 HTTP/2 或 SPDY 请求和响应通过单个连接多路复用到远程服务器,并且通过使用异步 Call 机制,这比阻塞版本更有效.
  • 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异步请求有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:使用OKHttp,AsyncTask中的同步请求和OKhttp异步请求有什么区别?

基础教程推荐