一、Retrofit框架
Retrofit是一種基於OkHttp的RESTful API請求框架,提供了一個輕量、易於學習和使用的API。Retrofit可以讓我們通過註解為每一個請求配置請求方法、url、參數、請求頭等信息,它通過動態代理技術,把java介面轉化成HTTP請求,在結構上比較清晰。下面詳細介紹四大註解用法。
1、@Get
註解用於指定請求類型。
@GET("https://www.myapi.com/data")
Call<ResponseBody> getData();
2、@Path
註解用於指定 URL 中變數的取值。
@GET("https://www.myapi.com/data/{id}")
Call<ResponseBody> getDataById(@Path("id") int id);
3、@Query
註解用於指定查詢參數。它可以添加多個 Query 參數,只需要再寫一個 @Query 即可。
@GET("https://www.myapi.com/data")
Call<ResponseBody> getDataByQuery(@Query("page") int page, @Query("count") int count);
4、@Body
註解使用一個對象作為其請求體。POST和PUT請求使用它傳遞實體。
@POST("https://www.myapi.com/data")
Call<ResponseBody> createData(@Body Data data); // Data對象即為請求體
二、Retrofit協程
在調用請求時,Retrofit默認是運行在主線程上的,如果在請求一些耗時的數據,可能會導致主線程卡死,出現ANR等問題。因此在這種情況下,可以選擇使用協程處理請求。Retrofit的協程版本需要引入一個擴展庫,下面給出具體的代碼實現。
//1、在gradle中引入擴展庫
implementation "com.squareup.retrofit2:retrofit:2.x.y"
implementation "com.squareup.retrofit2:converter-gson:2.x.y"
implementation 'com.jakewharton.retrofit:retrofit2-kotlin-coroutines-adapter:0.9.2'
//2、定義一個協程請求介面
interface ApiService {
@GET("https://www.myapi.com/data")
suspend fun getData(): ResponseBody
}
//3、使用協程調用請求
val apiService = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(CoroutineCallAdapterFactory())
.build().create(ApiService::class.java)
GlobalScope.launch(Dispatchers.Main) {
try {
val response = withContext(Dispatchers.IO) { apiService.getData() }
//處理請求結果
} catch (e: Exception) {
//處理異常
}
}
三、Retrofit下載文件
Retrofit同樣支持下載文件,我們可以通過設置下載文件的地址以及回調函數來實現文件的下載,下面給出一個具體的例子。
//1、定義一個文件下載的介面
interface DownloadService {
@Streaming
@GET
fun downloadFile(@Url fileUrl: String): Call
}
//2、創建下載文件時需要的OkHttp Client,並設置連接和讀取超時時間
val httpClient = OkHttpClient.Builder()
.connectTimeout(60, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.build()
//3、創建Retrofit對象
val retrofit = Retrofit.Builder()
.baseUrl(baseUrl)
.client(httpClient)
.build()
//4、創建下載服務對象
val downloadService = retrofit.create(DownloadService::class.java)
//5、開始進行文件的下載
val downloadCall = downloadService.downloadFile(fileUrl)
downloadCall.enqueue(object : Callback {
override fun onResponse(call: Call, response: Response) {
//下載完成,開始處理
}
override fun onFailure(call: Call, t: Throwable) {
//下載失敗,進行異常處理
}
})
四、Retrofit的所有形式
Retrofit不僅支持GET和POST請求,還支持PUT、DELETE等多種請求方式,並提供了RxJava、Java8 Lambda、協程等多種形式供我們選擇。下面給出不同形式的代碼實現。
1、RxJava形式
//1、定義一個介面
interface ApiService {
@GET("https://www.myapi.com/data")
fun getData(): Observable<ResponseBody>
}
//2、創建RxJava請求介面對象並進行請求
val apiService = Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build()
.create(ApiService::class.java)
apiService.getData().subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
//處理請求結果
}, {
//處理異常
})
2、Java8 Lambda形式
//1、定義一個介面
interface ApiService {
@GET("https://www.myapi.com/data")
Call<ResponseBody> getData();
}
//2、創建Java8 Lambda請求介面對象並進行請求
ApiService apiService = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(ApiService.class);
Call call = apiService.getData();
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
//處理請求結果
}
@Override
public void onFailure(Call call, Throwable throwable) {
//處理異常
}
});
3、協程形式
//1、定義一個介面
interface ApiService {
@GET("https://www.myapi.com/data")
suspend fun getData(): ResponseBody
}
//2、使用協程請求介面
val apiService = Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(ApiService::class.java)
GlobalScope.launch(Dispatchers.Main) {
try {
val response = withContext(Dispatchers.IO) { apiService.getData() }
//處理請求結果
} catch (e: Exception) {
//處理異常
}
}
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/186053.html