【Android】 Retrofit 2.0
Aug 27, 2017 · 2 min read
因為之前都是使用 Version 1.9, 最近準備改成 Version2.0, 以下針對最常用的GET與POST介紹
Add Dependenciescompile 'com.squareup.retrofit2:retrofit:2.1.0'compile 'com.squareup.retrofit2:converter-gson:2.0.0'
Add Permission<uses-permission android:name="android.permission.INTERNET"/>
建立Service Interface
在Version 1.9中synchronous與asynchronous的宣告方式有兩種,在Version 2.0只有一種皆已Call開頭,且預設回傳的型態為okhttp3.ResponseBody。這邊我習慣都是直接用Gson(建立回傳的class)來處理回傳的資料
public interface APIService {
@GET(“test.json”)
Call<ChannelInfoRs> getChannelInfo();@POST(“test”)
@Headers(“Content-Type: application/json”)
Call<DramaListRs> getDramaList(@Body Params params);
}
下面為ChannelInfoRs, 只要parameter name與Response format parameter name一樣即可自動parser,這也是retorfit2.0方便的地方
Get example
這邊要注意的是因為Version 2.0預設回傳的Type為ResponseBody,若要轉換為GSON需加入addConverterFactory(GsonConverterFactory.create())
而YOUR_BASEURL建議要以’/’為結尾
Post example
通常POST都會帶Request Body,這邊建一個request class,將需要的parameter設置進去
以上就是retrofit GET與POST的基本用法!
