Nice programing

Android 네트워킹 라이브러리 비교 : OkHTTP, Retrofit 및 Volley

nicepro 2020. 10. 3. 11:52
반응형

Android 네트워킹 라이브러리 비교 : OkHTTP, Retrofit 및 Volley [닫힘]


Android를 배우는 iOS 개발자가 JSON에서 이미지, 오디오 및 비디오의 스트리밍 다운로드에 이르기까지 다양한 요청을 수행하는 Android 프로젝트를 진행중인 두 부분으로 구성된 질문 :

  1. iOS에서는 AFNetworking 프로젝트를 광범위하게 사용 했습니다. Android에 상응하는 라이브러리가 있습니까?

  2. OkHTTPRetrofit by Square, Volley를 읽었 지만 아직 개발 경험이 없습니다. 누군가가 각각에 대한 최상의 사용 사례에 대한 구체적인 예를 제공 할 수 있기를 바랍니다. 내가 읽은 바에 따르면 OkHTTP는 세 가지 중 가장 강력한 것으로 보이며이 프로젝트의 요구 사항을 처리 할 수 ​​있습니다 (위에서 언급).


누군가가 각각에 대한 최상의 사용 사례에 대한 구체적인 예를 제공 할 수 있기를 바랍니다.

웹 서비스와 통신하는 경우 Retrofit을 사용하십시오. 이미지를 다운로드하는 경우 피어 라이브러리 Picasso를 사용하십시오. Retrofit / Picasso 외부에있는 HTTP 작업을 수행해야하는 경우 OkHTTP를 사용합니다.

Volley는 Retrofit + Picasso와 대략 경쟁합니다. 장점은 하나의 라이브러리입니다. 마이너스 측면에서는 문서화 되지 않고 지원되지 않는 "코드를 벽에 던져 I | O 프리젠 테이션"라이브러리입니다.

수정-Volley는 이제 Google에서 공식적으로 지원합니다. Google 개발자 가이드를 참조하십시오.

내가 읽은 바에 따르면 OkHTTP가 3 개 중 가장 강력한 것 같습니다.

Retrofit은 가능한 경우 OkHTTP를 자동으로 사용합니다. Volley를 OkHTTP에 연결하는 Jake WhartonGist 가 있습니다 .

이 프로젝트의 요구 사항을 처리 할 수 ​​있습니다 (위에 언급)

아마도 "스트리밍"의 일반적인 정의에 따라 "오디오 및 비디오 스트리밍 다운로드"에 이들 중 어느 것도 사용하지 않을 것입니다. 대신 Android의 미디어 프레임 워크가 이러한 HTTP 요청을 처리합니다.

즉, HTTP 기반 스트리밍을 시도하려는 경우 OkHTTP가 해당 시나리오를 처리해야합니다. 나는 Volley가 그 시나리오를 얼마나 잘 처리했는지 기억하지 못한다. Retrofit이나 Picasso는이를 위해 설계되지 않았습니다.


Volley 관점을 살펴보면 요구 사항에 대한 몇 가지 이점이 있습니다.

한편으로 Volley는 개별적이고 작은 HTTP 요청을 처리하는 데 전적으로 집중합니다. 따라서 HTTP 요청 처리에 몇 가지 단점이있는 경우 Volley가 도움이 될 것입니다. 반면에 이미지 처리에 특이한 점이 있다면 유일한 실제 후크는 ImageCache 입니다. "아무것도 아니지만 많지 않습니다!,". 그러나 요청을 정의하면 병렬 AsyncTasks와 달리 조각 또는 활동 내에서 사용하는 것과 같은 다른 이점이 있습니다.

Volley의 장단점 :

그래서 Volley의 좋은 점은 무엇입니까?

  • 네트워킹 부분은 이미지만을위한 것이 아닙니다. Volley는 백엔드의 필수적인 부분입니다. 간단한 REST 서비스를 기반으로 한 새로운 프로젝트의 경우 이것은 큰 승리가 될 수 있습니다.

  • NetworkImageView는 Picasso보다 요청 정리에 대해 더 공격적이며 GC 사용 패턴에서 더 보수적입니다. NetworkImageView는 강력한 메모리 참조에만 의존하며 ImageView에 대한 새 요청이 작성되거나 ImageView가 화면 밖으로 이동하는 즉시 모든 요청 데이터를 정리합니다.

  • 공연. 이 게시물은이 주장을 평가하지 않지만 메모리 사용 패턴을 신중하게 고려했습니다. Volley는 또한 컨텍스트 전환을 줄이기 위해 주 스레드에 대한 콜백을 일괄 처리하기 위해 노력합니다.

  • 발리 역시 미래를 가지고 있습니다. 관심이 있으시면 RequestFuture를 확인하십시오.

  • 고해상도 압축 이미지를 다루는 경우 Volley가 여기에서 잘 작동하는 유일한 솔루션입니다.

  • Volley는 Okhttp와 함께 사용할 수 있습니다 (새로운 버전의 Okhttp는 더 나은 성능을 위해 NIO를 지원합니다)

  • Volley는 활동 라이프 사이클과 잘 어울립니다.

Volley 관련 문제 :
Volley는 새로운 기능이므로 아직 지원되지 않는 항목이 거의 없지만 수정되었습니다.

  1. 멀티 파트 요청 (솔루션 : https://github.com/vinaysshenoy/enhanced-volley )

  2. 상태 코드 201은 오류로 간주되며, 상태 코드 200에서 207은 이제 성공적인 응답입니다. (고정 : https://github.com/Vinayrraj/CustomVolley )

    업데이트 : Google 발리의 최신 릴리스에서 2XX 상태 코드 버그가 수정 되었습니다! Ficus Kirkpatrick에게 감사드립니다!

  3. 덜 문서화되어 있지만 많은 사람들이 github에서 발리를 지원하고 있으며 Java와 같은 문서는 여기 에서 찾을 수 있습니다 . 안드로이드 개발자 웹 사이트에서 Volley를 사용하여 네트워크 데이터전송 하기위한 가이드를 찾을 수 있습니다 . 발리 소스 코드는 Google Git 에서 찾을 수 있습니다.

  4. Volley Framework 의 리디렉션 정책 을 해결 / 변경하려면 OkHTTP (위에서 언급 한 CommonsWare) 와 함께 Volley를 사용하십시오.

또한이 Comparing Volley 's image loading with Picasso를 읽을 수 있습니다.

개조 :

Square 에서 출시했으며 REST API를 사용하기 매우 쉽습니다 (업데이트 : Voila! with NIO 지원).

개조의 장점 :

  • Compared to Volley, Retrofit's REST API code is brief and provides excellent API documentation and has good support in communities! 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

  • 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. (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!!).

Cons of Retrofit for version 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.

  • 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)

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

Update:

Android Async vs Volley vs Retrofit performance benchmarks (milliseconds, lower value is better):

Android Async vs Volley vs Retrofit performance benchmarks

(FYI above Retrofit Benchmarks info will improve with java NIO support because the new version of OKhttp is dependent on NIO Okio library)

In all three tests with varying repeats (1 – 25 times), Volley was anywhere from 50% to 75% faster. Retrofit clocked in at an impressive 50% to 90% faster than the AsyncTasks, hitting the same endpoint the same number of times. On the Dashboard test suite, this translated into loading/parsing the data several seconds faster. 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.

RetroFit Wins in benchmark test!

In the end, we decided to go with Retrofit for our application. 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. 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. 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.

When to use 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! also Volley has better memory related error handling than Retrofit!

OkHttp can be used with Volley, Retrofit uses OkHttp by default! It has SPDY support, connection pooling, disk caching, transparent compression! Recently, it has got some support of java NIO with Okio library.

Source, credit: volley-vs-retrofit by Mr. Josh Ruesch

Note: About streaming it depends on what type of streaming you want like RTSP/RTCP.


RoboSpice Vs. Volley

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

  • RoboSpice(RS) is service based and more respectful of Android philosophy than Volley. Volley is thread based and this is not the way background processing should take place on 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).
  • RoboSpice and volley both offer nice features like prioritization, retry policies, request cancellation. 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.
  • RoboSpice does more outside of UI Thread : volley will deserialize your POJOs on the main thread, which is horrible to my mind. With RS your app will be more responsive.
  • In terms of speed, we definitely need metrics. RS has gotten super fast now, but still we don't have figure to put here. Volley should theoretically be a bit faster, but RS is now massively parallel... who knows ?
  • RoboSpice offers a large compatibility range with extensions. You can use it with okhttp, retrofit, ormlite (beta), jackson, jackson2, gson, xml serializer, google http client, spring android... Quite a lot. Volley can be used with ok http and uses gson. that's it.
  • Volley offers more UI sugar that RS. Volley provides NetworkImageView, RS does provide a spicelist adapter. In terms of feature it's not so far, but I believe Volley is more advanced on this topic.
  • More than 200 bugs have been solved in RoboSpice since its initial release. It's pretty robust and used heavily in production. Volley is less mature but its user base should be growing fast (Google effect).
  • RoboSpice is available on maven central. Volley is hard to find ;)

AFNetworking for Android:

Fast Android Networking is here

Fast Android Networking Library supports all types of HTTP/HTTPS request like GET, POST, DELETE, HEAD, PUT, PATCH

Fast Android Networking Library supports downloading any type of file

Fast Android Networking Library supports uploading any type of file (supports multipart upload)

Fast Android Networking Library supports cancelling a request

Fast Android Networking Library supports setting priority to any request (LOW, MEDIUM, HIGH, IMMEDIATE)

Fast Android Networking Library supports RxJava

As it uses OkHttp as a networking layer, it supports:

Fast Android Networking Library supports HTTP/2 support allows all requests to the same host to share a socket

Fast Android Networking Library uses connection pooling which reduces request latency (if HTTP/2 isn’t available)

Transparent GZIP shrinks download sizes

Fast Android Networking Library supports response caching which avoids the network completely for repeat requests

Thanks: The library is created by me


Async HTTP client loopj vs. Volley

The specifics of my project are small HTTP REST requests, every 1-5 minutes.

I using an async HTTP client (1.4.1) for a long time. The performance is better than using the vanilla Apache httpClient or an HTTP URL connection. 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.

After using it for some time, even without tests, I see clearly that the response time is down to 1.5x, 2x Volley.

Maybe Retrofit is better than an async HTTP client? I need to try it. But I'm sure that Volley is not for me.


Just to add a bit to the discussion from my experience working with Volley:

  1. Volley does not handle streaming uploads or downloads in any sense. 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. So, Volley is a poor choice for uploading or downloading large files. 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.

  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. You just clone a repo, build a jar, and you're on your own. 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. 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. 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!). 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. It certainly does. Easily customizable retry policies, transparent caching, a cancellation API, and support for request scheduling and concurrent connections are great features. 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).


I've recently found a lib called ion that brings a little extra to the table.

ion has built-in support for image download integrated with ImageView, JSON (with the help of GSON), files and a very handy UI threading support.

I'm using it on a new project and so far the results have been good. Its use is much simpler than Volley or Retrofit.


Adding to the accepted answer and what LOG_TAG said....for Volley to parse your data in a background thread you must subclass Request<YourClassName> as the onResponse method is called on the main thread and parsing on the main thread may cause the UI to lag if your response is big. Read here on how to do that.


Retrofit 1.9.0 vs. RoboSpice

I am using both in my app.

Robospice works faster than Retrofit whenever I parse the nested JSON class. Because Spice Manger will do everything for you. In Retrofit you need to create GsonConverter and deserialize it.

I created two fragments in the same activity and called the same time with two same kind of URLs.

09-23 20:12:32.830  16002-16002/com.urbanpro.seeker E/RETROFIT﹕   RestAdapter Init
09-23 20:12:32.833  16002-16002/com.urbanpro.seeker E/RETROFIT﹕ calling the method
09-23 20:12:32.837  16002-16002/com.urbanpro.seeker E/ROBOSPICE﹕ initialzig spice manager
09-23 20:12:32.860  16002-16002/com.urbanpro.seeker E/ROBOSPICE﹕ Executing the method
09-23 20:12:33.537  16002-16002/com.urbanpro.seeker E/ROBOSPICE﹕ on SUcceess
09-23 20:12:33.553  16002-16002/com.urbanpro.seeker E/ROBOSPICE﹕ gettting the all contents
09-23 20:12:33.601  16002-21819/com.urbanpro.seeker E/RETROFIT﹕ deseriazation starts
09-23 20:12:33.603  16002-21819/com.urbanpro.seeker E/RETROFIT﹕ deseriazation ends

And yet another option: https://github.com/apptik/jus

  • It is modular like Volley, but more extended and documentation is improving, supporting different HTTP stacks and converters out of the box
  • It has a module to generate server API interface mappings like Retrofit
  • It also has JavaRx support

And many other handy features like markers, transformers, etc.

참고URL : https://stackoverflow.com/questions/16902716/comparison-of-android-networking-libraries-okhttp-retrofit-and-volley

반응형