天天看點

Android REST Clients 實踐-網絡庫

記得以前有一篇文章好像叫Android dev tips,第一條說明就是使用成熟的網絡通信庫,而不要自己編寫網絡庫。為什麼呢?

  1. 在實際的APP中都不像一個示例Demo那種請求一段網絡文字,一般你會有很多網絡請求,是以請求隊列,并行請求甚至請求優先級都是必須的
  2. HttpURLConnection的API還是比較底層的,錯誤處理、常見的HTTP頭的處理、Header處理甚至GET請求和POST請求都很難區分
  3. 異步請求需要自行封裝HttpURLConnection和AsyncTask

其實以上都是重複任務,大多數APP的需求很類似,是以催生了很多第三方的網絡庫。我們現在介紹一下目前兩個比較火的Google Volley及Retrofit

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

而且還有一些性能上的問題

Android REST Clients 實踐-網絡庫

詳情參見這裡

是以其實我更喜歡用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的關系。下一篇我們會專門讨論這個問題。

繼續閱讀