Android REST Clients 实践-网络库

本文对比了Android开发中常用的两款网络库GoogleVolley与Retrofit。分析了各自的优缺点,如Volley的请求调度与缓存机制,以及Retrofit在序列化与文件上传方面的优势。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

记得以前有一篇文章好像叫Android dev tips,第一条说明就是使用成熟的网络通信库,而不要自己编写网络库。为什么呢?

  1. 在实际的APP中都不像一个示例Demo那种请求一段网络文字,一般你会有很多网络请求,所以请求队列,并行请求甚至请求优先级都是必须的
  2. HttpURLConnection的API还是比较底层的,错误处理、常见的HTTP头的处理、Header处理甚至GET请求和POST请求都很难区分
  3. 异步请求需要自行封装HttpURLConnection和AsyncTask

其实以上都是重复任务,大多数APP的需求很类似,所以催生了很多第三方的网络库。我们现在介绍一下当前两个比较火的Google VolleyRetrofit

Google Volley

Google Volley是Google在2013年的IO大会上推出的,他提供了如下功能:

  1. Automatic scheduling of network requests.
  2. Multiple concurrent network connections.
  3. Transparent disk and memory response caching with standard HTTP cache coherence.
  4. Support for request prioritization.
  5. Cancellation request API. You can cancel a single request, or you can set blocks or scopes of requests to cancel.
  6. Ease of customization, for example, for retry and backoff.
  7. Strong ordering that makes it easy to correctly populate your UI with data fetched asynchronously from the network.
  8. Debugging and tracing tools.

其中以上还未提到Volley可以作为小图片加载工具,实际使用可以参见这里,源码解析参见这里

Volley还存在两个缺陷a)不能自动将Json串序列化为实体对象。b)不支持大文件传输及文件上传。不过就像Google所说Volley很容易扩展,Volley Plus就修复了以上两个缺陷

其实Volley的风评不佳

Volley roughly competes with Retrofit + Picasso. On the plus side, it is one library. On the minus side, it is one undocumented, unsupported, “throw the code over the wall and do an I|O presentation on it” library.

–CommonsWare

I’ve used Volley extensively and strongly recommend using Retrofit instead. Volley’s docs are so half assed. Also they expect you to comb through JSONObjects yourself as they don’t provide a way to automatically populate fields in your java models.

–leakingsieve

而且还有一些性能上的问题Volley性能 详情参见这里
所以其实我更喜欢用Retrofit

Retrofit

Retrofit比Volley多了如下特性

  1. URL parameter replacement and query parameter support
  2. Object conversion to request body (e.g., JSON, protocol buffers)
  3. Multipart request body and file upload

2和3正是Volley当前的两个缺陷,Retrofit修复了这两个缺陷。第一条做的也不错,但是我感觉和Spring-android-rest-template相比还是有些差距,spring-android-rest-template可是用参数名直接替换url query parameter。
Retrofit的文档写的不错,示例直接参考代码就可以了。
另外Retrofit是没有Volley那种ImageRequest的,所以Retrofit其实不能作为图片加载器使用。在实际使用中需要配合picasso或glide加载图片。Picasso或Glide此处先略过,以后我们可能会有一个专门的Android中图片处理的文章讲这些。

总结

今天讨论的两个框架其实已经可以直接拿来用了,两个框架进行些许修改都能满足咱们之前谈到的异步发送请求并将结果序列化为实体对象,然后再UI线程进行处理。但是都还有一个问题没有进行处理,就是上一篇”异步请求”章节所说的处理和Activity LifeCycle的关系。下一篇我们会专门讨论这个问题。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值