Android网络库的比较:OkHTTP,Retrofit和Volley [关闭]

本文翻译自:Comparison of Android networking libraries: OkHTTP, Retrofit, and Volley [closed]

Two-part question from an iOS developer learning Android, working on an Android project that will make a variety of requests from JSON to image to streaming download of audio and video: 来自学习Android的iOS开发人员的一个分为两个部分的问题,该问题涉及一个Android项目,该项目将提出从JSON到图像到音频和视频流下载的各种请求:

  1. On iOS I have used the AFNetworking project extensively. 在iOS上,我广泛使用了AFNetworking项目。 Is there an equivalent library for Android? 是否有适用于Android的等效库?

  2. I've read up on OkHTTP and Retrofit by Square, as well as Volley but don't yet have experience developing with them. 我已经阅读了Square的OkHTTPRetrofit ,以及Volley,但还没有与它们一起开发的经验。 I'm hoping someone could provide some concrete examples of best use cases for each. 我希望有人可以为每个案例提供一些最佳用例的具体示例。 From what I've read, seems like OkHTTP is the most robust of the three, and could handle the requirements of this project (mentioned above). 根据我的阅读,似乎OkHTTP是这三个中最强大的,并且可以满足该项目的要求(如上所述)。


#1楼

参考:https://stackoom.com/question/18vAS/Android网络库的比较-OkHTTP-Retrofit和Volley-关闭


#2楼

I'm hoping someone can provide some concrete examples of best use cases for each. 我希望有人可以为每个案例提供一些最佳用例的具体示例。

Use Retrofit if you are communicating with a Web service. 如果要与Web服务通信,请使用Retrofit。 Use the peer library Picasso if you are downloading images. 如果要下载图像,请使用对等库Picasso。 Use OkHTTP if you need to do HTTP operations that lie outside of Retrofit/Picasso. 如果需要执行Retrofit / Picasso之外的HTTP操作,请使用OkHTTP。

Volley roughly competes with Retrofit + Picasso. 排球大致与Retrofit + Picasso竞争。 On the plus side, it is one library. 从好的方面来说,它是一个库。 On the minus side, it is one undocumented, an unsupported, "throw the code over the wall and do an I|O presentation on it" library. 在不利的一面,它是 一个没有证件的, 不受支持的“将代码扔在墙上,并在上面进行I | O演示”库。

EDIT - Volley is now officially supported by Google. 编辑-Volley现在由Google正式支持。 Kindly refer Google Developer Guide 请参考Google开发者指南

From what I've read, seems like OkHTTP is the most robust of the 3 根据我的阅读,似乎OkHTTP是3种中最强大的

Retrofit uses OkHTTP automatically if available. 如果可用,Retrofit自动使用OkHTTP。 There is a Gist from Jake Wharton that connects Volley to OkHTTP. 杰克·沃顿(Jake Wharton)有一个要点 ,它将Volley连接到OkHTTP。

and could handle the requirements of this project (mentioned above). 并可以满足该项目的要求(如上所述)。

Probably you will use none of them for "streaming download of audio and video", by the conventional definition of "streaming". 按照“流”的常规定义,您可能都不会将它们用于“流式下载音频和视频”。 Instead, Android's media framework will handle those HTTP requests for you. 相反,Android的媒体框架将为您处理这些HTTP请求。

That being said, if you are going to attempt to do your own HTTP-based streaming, OkHTTP should handle that scenario; 话虽如此,如果您打算尝试进行自己的基于HTTP的流传输,则OkHTTP应该可以处理这种情况。 I don't recall how well Volley would handle that scenario. 我不记得Volley将如何处理这种情况。 Neither Retrofit nor Picasso are designed for that. Retrofit和Picasso都不是为此目的而设计的。


#3楼

Looking at the Volley perspective here are some advantages for your requirement: 从Volley的角度看,这里有一些您需要的优点:

Volley, on one hand, is totally focused on handling individual, small HTTP requests. 一方面,Volley完全专注于处理单个的小型HTTP请求。 So if your HTTP request handling has some quirks, Volley probably has a hook for you. 因此,如果您的HTTP请求处理有一些怪癖,Volley可能为您提供了一个钩子。 If, on the other hand, you have a quirk in your image handling, the only real hook you have is ImageCache . 另一方面,如果您在图像处理方面有一个怪癖,那么唯一真正的钩子就是ImageCache "It's not nothing, but it's not a lot!, either". “也不是没有,但也不是很多!”。 but it has more other advantages like Once you define your requests, using them from within a fragment or activity is painless unlike parallel AsyncTasks 但是它还有更多其他优点,例如,一旦定义了请求,就可以在片段或活动中使用请求,这与并行AsyncTasks一样轻松

Pros and cons of Volley: 凌空抽烟的利弊:

So what's nice about Volley? 那么Volley有什么好处呢?

  • The networking part isn't just for images. 网络部分不仅用于图像。 Volley is intended to be an integral part of your back end. Volley旨在成为您后端不可或缺的一部分。 For a fresh project based off of a simple REST service, this could be a big win. 对于基于简单REST服务的全新项目,这可能是一个巨大的胜利。

  • NetworkImageView is more aggressive about request cleanup than Picasso, and more conservative in its GC usage patterns. 与Picasso相比,NetworkImageView在请求清除方面更具攻击性,并且在GC使用模式方面更为保守。 NetworkImageView relies exclusively on strong memory references, and cleans up all request data as soon as a new request is made for an ImageView, or as soon as that ImageView moves offscreen. NetworkImageView完全依赖于强大的内存引用,并在对ImageView发出新请求时或在ImageView移出屏幕后立即清除所有请求数据。

  • Performance. 性能。 This post won't evaluate this claim, but they've clearly taken some care to be judicious in their memory usage patterns. 这篇文章不会评估这种说法,但是他们显然已经谨慎考虑了它们的内存使用模式。 Volley also makes an effort to batch callbacks to the main thread to reduce context switching. Volley还努力将回调批处理到主线程,以减少上下文切换。

  • Volley apparently has futures, too. 凌空显然也有期货。 Check out RequestFuture if you're interested. 如果有兴趣,请查看RequestFuture。

  • If you're dealing with high-resolution compressed images, Volley is the only solution here that works well. 如果您要处理高分辨率的压缩图像,Volley是这里唯一运作良好的解决方案。

  • Volley can be used with Okhttp (New version of Okhttp supports NIO for better performance ) Volley可以与Okhttp一起使用(新版本的Okhttp支持NIO以获得更好的性能)

  • Volley plays nice with the Activity life cycle. 排球在“活动”生命周期中表现良好。

Problems With Volley: 排球问题:
Since Volley is new, few things are not supported yet, but it's fixed. 由于Volley是新产品,因此尚不支持某些功能,但已修复。

  1. Multipart Requests (Solution: https://github.com/vinaysshenoy/enhanced-volley ) 多部分请求(解决方案: https : //github.com/vinaysshenoy/enhanced-volley

  2. status code 201 is taken as an error, Status code from 200 to 207 are successful responses now.(Fixed: https://github.com/Vinayrraj/CustomVolley ) 状态码201被视为错误,状态码从200到207现在已经成功响应。(修复: https : //github.com/Vinayrraj/CustomVolley

    Update: in latest release of Google volley, the 2XX Status codes bug is fixed now!Thanks to Ficus Kirkpatrick! 更新:在谷歌抽射最新版本中,2xx状态代码错误是固定的 ,现在由于榕帕特里克!

  3. it's less documented but many of the people are supporting volley in github, java like documentation can be found here . 它的文档较少,但是许多人在github中支持volley,可以在此处找到类似Java的文档。 On android developer website, you may find guide for Transmitting Network Data Using Volley . 在android开发人员网站上,您可以找到使用Volley传输网络数据的指南。 And volley source code can be found at Google Git 凌空源代码可以在Google Git中找到

  4. To solve/change Redirect Policy of Volley Framework use Volley with OkHTTP (CommonsWare mentioned above) 要解决/更改Volley Framework的重定向策略, 请将Volley与OkHTTP配合使用 (上面提到的CommonsWare)

Also you can read this Comparing Volley's image loading with Picasso 您也可以阅读与毕加索比较《凌空凌空》的图像

Retrofit: 改造:

It's released by Square , This offers very easy to use REST API's (Update: Voila! with NIO support) 它由Square发布,它提供了非常易于使用的REST API(更新:Voila!具有NIO支持)

Pros of Retrofit: 改造的优点:

  • Compared to Volley, Retrofit's REST API code is brief and provides excellent API documentation and has good support in communities! 与Volley相比,Retrofit的REST API代码简短,并提供了出色的API文档,并在社区中提供了良好的支持! It is very easy to add into the projects. 添加到项目中非常容易。

  • We can use it with any serialization library, with error handling. 我们可以将其与任何带有错误处理的序列化库一起使用。

Update: - There are plenty of very good changes in Retrofit 2.0.0-beta2 更新: -Retrofit 2.0.0-beta2中有很多非常好的更改

  • version 1.6 of Retrofit with OkHttp 2.0 is now dependent on Okio to support java.io and java.nio which makes it much easier to access, store and process your data using ByteString and Buffer to do some clever things to save CPU and memory. 改造的1.6版本OkHttp 2.0现在依赖于奥基奥以支持java.iojava.nio的 ,这使得它更容易访问,存储和使用的字节字符串缓冲区做一些聪明的事情,以节省CPU和内存处理您的数据。 (FYI: This reminds me of the Koush's OIN library with NIO support!) We can use Retrofit together with RxJava to combine and chain REST calls using rxObservables to avoid ugly callback chains (to avoid callback hell!!) . (供参考:这让我想起的Koush的OIN与NIO支持库!)我们可以利用起来改造与RxJava结合起来,并用rxObservables避免难看的回调链链REST调用(避免回调地狱!)。

Cons of Retrofit for version 1.6: 1.6版改造的缺点:

  • Memory related error handling functionality is not good (in older versions of Retrofit/OkHttp) not sure if it's improved with the Okio with Java NIO support. 与内存相关的错误处理功能不好(在Retrofit / OkHttp的旧版本中),不确定带有Java NIO支持的Okio是否会改进它。

  • Minimum threading assistance can result call back hell if we use this in an improper way. 如果我们以不正确的方式使用它,则最少的线程帮助可能导致回调。

(All above Cons have been solved in the new version of Retrofit 2.0 beta) (以上所有缺点均已在Retrofit 2.0 beta的新版本中解决)

======================================================================== ================================================== ======================

Update: 更新:

Android Async vs Volley vs Retrofit performance benchmarks (milliseconds, lower value is better): Android Async,Volley和Retrofit性能基准(毫秒,值越低越好):

Android Async,Volley和Retrofit性能基准

(FYI above Retrofit Benchmarks info will improve with java NIO support because the new version of OKhttp is dependent on NIO Okio library) (以上更新基准信息的FYI将通过Java NIO支持得到改善,因为新版本的OKhttp依赖于NIO Okio库)

In all three tests with varying repeats (1 – 25 times), Volley was anywhere from 50% to 75% faster. 在所有三个具有不同重复次数的测试中(1-25次),Volley的速度提高了50%至75%。 Retrofit clocked in at an impressive 50% to 90% faster than the AsyncTasks, hitting the same endpoint the same number of times. 翻新的速度比AsyncTasks快50%至90%,到达相同端点的次数相同。 On the Dashboard test suite, this translated into loading/parsing the data several seconds faster. 在Dashboard测试套件上,这转化为更快地加载/解析数据几秒钟。 That is a massive real-world difference. 那是现实世界的巨大差异。 In order to make the tests fair, the times for AsyncTasks/Volley included the JSON parsing as Retrofit does it for you automatically. 为了使测试公平,AsyncTasks / Volley的时间包括JSON解析,因为Retrofit会自动为您执行。

RetroFit Wins in benchmark test! RetroFit在基准测试中获胜!

In the end, we decided to go with Retrofit for our application. 最后,我们决定将Retrofit用于我们的应用程序。 Not only is it ridiculously fast, but it meshes quite well with our existing architecture. 它不仅快得离谱,而且与我们现有的体系结构非常吻合。 We were able to make a parent Callback Interface that automatically performs error handling, caching, and pagination with little to no effort for our APIs. 我们能够制作一个父级的回调接口,该接口可以自动执行错误处理,缓存和分页,而对我们的API几乎不需要付出任何努力。 In order to merge in Retrofit, we had to rename our variables to make our models GSON compliant, write a few simple interfaces, delete functions from the old API, and modify our fragments to not use AsyncTasks. 为了合并到Retrofit中,我们必须重命名变量以使我们的模型符合GSON的要求,编写一些简单的接口,从旧的API中删除函数,并修改片段以不使用AsyncTasks。 Now that we have a few fragments completely converted, it's pretty painless. 现在,我们已经完成了一些片段的完全转换,这非常轻松。 There were some growing pains and issues that we had to overcome, but overall it went smoothly. 我们不得不克服一些不断增长的痛苦和问题,但总体而言进展顺利。 In the beginning, we ran into a few technical issues/bugs, but Square has a fantastic Google+ community that was able to help us through it. 一开始,我们遇到了一些技术问题/错误,但Square拥有一个出色的Google+社区,可以帮助我们解决这个问题。

When to use Volley?! 什么时候使用Volley ?!

We can use Volley when we need to load images as well as consuming REST APIs!, network call queuing system is needed for many n/w request at the same time! 当我们需要加载图像以及使用REST API时,我们可以使用Volley !,同时许多n / w请求都需要网络呼叫排队系统! also Volley has better memory related error handling than Retrofit! 而且Volley具有比Retrofit更好的内存相关错误处理!

OkHttp can be used with Volley, Retrofit uses OkHttp by default! OkHttp可以与Volley一起使用,Retrofit默认使用OkHttp It has SPDY support, connection pooling, disk caching, transparent compression! 它具有SPDY支持,连接池,磁盘缓存,透明压缩! Recently, it has got some support of java NIO with Okio library. 最近,它通过Okio库获得了对Java NIO的支持。

Source, credit: volley-vs-retrofit by Mr. Josh Ruesch 资料来源:信贷:Josh Ruesch先生提出的volley-vs- retrofit

Note: About streaming it depends on what type of streaming you want like RTSP/RTCP. 注意: 关于流,它取决于您想要哪种流类型,例如RTSP / RTCP。


#4楼

RoboSpice Vs. RoboSpice与 Volley 凌空抽射

From https://groups.google.com/forum/#!topic/robospice/QwVCfY_glOQ 来自https://groups.google.com/forum/#!topic/robospice/QwVCfY_glOQ

  • RoboSpice(RS) is service based and more respectful of Android philosophy than Volley. RoboSpice(RS)是基于服务的,并且比Volley更尊重Android哲学。 Volley is thread based and this is not the way background processing should take place on Android. Volley是基于线程的,这不是在Android上进行后台处理的方式。 Ultimately, you can dig down both libs and find that they are quite similar, but our way to do background processing is more Android oriented, it allow us, for instance, to tell users that RS is actually doing something in background, which would be hard for volley (actually it doesn't at all). 最终,您可以挖掘两个库,发现它们非常相似,但是我们进行后台处理的方式更面向Android,例如,它使我们可以告诉用户RS实际上是在后台做某事。很难抽射(实际上根本不行)。
  • RoboSpice and volley both offer nice features like prioritization, retry policies, request cancellation. RoboSpice和volley都提供了不错的功能,例如优先级划分,重试策略,请求取消。 But RS offers more : a more advanced caching and that's a big one, with cache management, request aggregation, more features like repluging to a pending request, dealing with cache expiry without relying on server headers, etc. 但是RS提供了更多功能:更高级的缓存,这是一个很大的缓存,具有缓存管理,请求聚合,更多功能,例如重新插入挂起的请求,无需依赖服务器标头即可处理缓存过期等。
  • RoboSpice does more outside of UI Thread : volley will deserialize your POJOs on the main thread, which is horrible to my mind. RoboSpice在UI Thread之外执行了更多操作:volley将在主线程上反序列化您的POJO,这在我看来是可怕的。 With RS your app will be more responsive. 使用RS,您的应用程序将响应更快。
  • In terms of speed, we definitely need metrics. 在速度方面,我们绝对需要指标。 RS has gotten super fast now, but still we don't have figure to put here. RS现在发展很快,但是我们仍然没有数字可言。 Volley should theoretically be a bit faster, but RS is now massively parallel... who knows ? 理论上,Volley应该会快一点,但是RS现在是大规模并行的……谁知道呢?
  • RoboSpice offers a large compatibility range with extensions. RoboSpice通过扩展提供了广泛的兼容性范围。 You can use it with okhttp, retrofit, ormlite (beta), jackson, jackson2, gson, xml serializer, google http client, spring android... Quite a lot. 您可以将其与okhttp,retrofit,ormlite(beta),jackson,jackson2,gson,xml序列化器,google http客户端,spring android等结合使用。 Volley can be used with ok http and uses gson. Volley可以与ok http一起使用,并使用gson。 that's it. 而已。
  • Volley offers more UI sugar that RS. 排球提供了比RS更多的UI糖。 Volley provides NetworkImageView, RS does provide a spicelist adapter. Volley提供了NetworkImageView,RS提供了一个spicelist适配器。 In terms of feature it's not so far, but I believe Volley is more advanced on this topic. 就功能而言,还不算很远,但是我相信Volley在这个话题上更先进。
  • More than 200 bugs have been solved in RoboSpice since its initial release. 自RoboSpice最初发布以来,已经解决了200多个错误。 It's pretty robust and used heavily in production. 它非常强大,并且在生产中大量使用。 Volley is less mature but its user base should be growing fast (Google effect). Volley还不成熟,但是其用户群应该快速增长(Google效应)。
  • RoboSpice is available on maven central. RoboSpice在Maven Central上可用。 Volley is hard to find ;) 凌空很难找到;)

#5楼

Async HTTP client loopj vs. Volley 异步HTTP客户端loopj与Volley

The specifics of my project are small HTTP REST requests, every 1-5 minutes. 我的项目的详细信息是每1-5分钟发送一次小的HTTP REST请求。

I using an async HTTP client (1.4.1) for a long time. 我长时间使用异步HTTP客户端(1.4.1)。 The performance is better than using the vanilla Apache httpClient or an HTTP URL connection. 与使用普通的Apache httpClient或HTTP URL连接相比,该性能更好。 Anyway, the new version of the library is not working for me: library inter exception cut chain of callbacks. 无论如何,新版本的库对我不起作用:库间异常剪切回调链。

Reading all answers motivated me to try something new. 阅读所有答案促使我尝试一些新事物。 I have chosen the Volley HTTP library. 我选择了Volley HTTP库。

After using it for some time, even without tests, I see clearly that the response time is down to 1.5x, 2x Volley. 使用一段时间后,即使没有进行测试,我也清楚地看到响应时间降低到1.5倍,2倍凌空。

Maybe Retrofit is better than an async HTTP client? 也许Retrofit比异步HTTP客户端更好? I need to try it. 我需要尝试一下。 But I'm sure that Volley is not for me. 但是我敢肯定,Volley不适合我。


#6楼

Just to add a bit to the discussion from my experience working with Volley: 只是为了增加我在Volley工作中的经验而进行的讨论:

  1. Volley does not handle streaming uploads or downloads in any sense. Volley不会以任何方式处理流媒体上载或下载。 That is, the entire request body has to be in memory and you cannot use an OutputStream to write the request body to the underlying socket, nor can you use an InputStream to read the response body, as basic HttpURLConnection does. 也就是说,整个请求正文必须在内存中,并且不能像基本HttpURLConnection一样使用OutputStream将请求正文写入基础套接字,也不能使用InputStream读取响应正文。 So, Volley is a poor choice for uploading or downloading large files. 因此,Volley是上传或下载大文件的不佳选择。 Your requests and responses should be small. 您的要求和回应应该很小。 This is one of the biggest limitations of Volley that I have personally encountered. 这是我亲自遇到的凌空运动的最大局限之一。 For what it's worth, OkHttp does have interfaces for working with streams. 就其价值而言,OkHttp确实具有用于处理流的接口。

  2. The lack of official documentation is annoying, although I have been able to work around that by reading the source code, which is pretty easy to follow. 缺少官方文档很烦人,尽管我已经能够通过阅读源代码来解决此问题,这很容易理解。 What is more bothersome is that, as far as I can tell, Volley has no official release versions and no Maven or Gradle artifact, and therefore managing it as a dependency becomes more of a headache than, say, any of the libraries Square has released. 更麻烦的是,据我所知,Volley没有正式发行版本,也没有Maven或Gradle构件,因此将其作为依赖项进行管理比任何Square发行的库都更加令人头疼。 You just clone a repo, build a jar, and you're on your own. 您只需克隆一个回购库,构建一个jar,就可以自己完成工作了。 Looking for a bug fix? 寻找错误修正? Fetch and hope it's there. 获取并希望它在那里。 You might get some other stuff, too; 您可能还会得到一些其他东西。 it won't be documented. 它不会被记录下来。 In my opinion, this effectively means that Volley is an unsupported 3rd party library, even though the code base is reasonably active. 我认为,即使代码库相当活跃,这实际上也意味着Volley是不受支持的第三方库。 Caveat emptor. 买者自负。

  3. As a nit, having the Content-Type tied to the class/request type (JsonObjectRequest, ImageRequest, etc.) is kind of awkward and reduces the flexibility of the calling code a bit, as you are tied to Volley's existing Request type hierarchy. 作为一种形式,将Content-Type绑定到类/请求类型(JsonObjectRequest,ImageRequest等)有点尴尬,并且由于将您绑定到Volley现有的Request类型层次结构,因此稍微降低了调用代码的灵活性。 I like the straightforwardness of just setting Content-Type as a header like any other (don't do this with Volley, by the way; you'll end up with two Content-Type headers!). 我喜欢直接将Content-Type设置为标头的简单性(顺便说一句,不要对Volley这样做;您最终将获得两个Content-Type标头!)。 That's just my personal opinion, though, and it can be worked around. 不过,那只是我个人的观点,可以解决。

That is not to say that Volley does not have some useful features. 这并不是说Volley没有某些有用的功能。 It certainly does. 当然可以。 Easily customizable retry policies, transparent caching, a cancellation API, and support for request scheduling and concurrent connections are great features. 轻松自定义的重试策略,透明的缓存,取消API以及对请求调度和并发连接的支持都是很棒的功能。 Just know that it's not intended for all HTTP use cases (see item 1 above), and that there are some headaches involved in putting Volley into production use in your app (item 2). 只是知道它并不适合所有HTTP用例(请参阅上面的项目1),并且在应用程序中将Volley投入生产使用时涉及一些麻烦(项目2)。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值