Android?Retrofit使用詳細教程
一、 Retrofit是什么
Retrofit是Android用來接口請求的網(wǎng)絡(luò)框架,內(nèi)部是基于OkHttp實現(xiàn)的,retrofit負責(zé)接口請求的封裝,retrofit可以直接將接口數(shù)據(jù)解析為Bean類、List集合等,直接簡化了中間繁瑣的數(shù)據(jù)解析過程
二、 Retrofit的簡單使用
Retrofit在github的地址 :https://github.com/square/retrofit
Retrofit官方使用介紹 :https://square.github.io/retrofit/
2.1 在項目中引入retrofit
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'//解析json字符所用2.2 清單文件AndroidManifest.xml中添加網(wǎng)絡(luò)權(quán)限
<uses-permission android:name="android.permission.INTERNET"/>
Google在Android p為了安全起見,已經(jīng)明確規(guī)定禁止http協(xié)議額,接口都是https請忽略,如果接口有http請在清單文件AndroidManifest.xml中application先添加networkSecurityConfig配置
<application android:name=".App" android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:networkSecurityConfig="@xml/network_security_config" android:requestLegacyExternalStorage="true" android:supportsRtl="true" android:theme="@style/AppTheme" tools:ignore="UnusedAttribute">
res文件夾下新建xml文件夾,xml文件夾中新建network_security_config文件,文件內(nèi)容如下:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true" />
</network-security-config>2.3 創(chuàng)建Retrofit
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com/")
.addConverterFactory(GsonConverterFactory.create())//設(shè)置數(shù)據(jù)解析器
.build();2.4 創(chuàng)建RetrofitApi
//定義 網(wǎng)絡(luò)API 地址
public interface RetrofitApi{
@GET("users/{user}/repos")
Call<List<User>> getData(@Path("user") String user);
}2.5 請求接口
//獲取API
GitHubService service = retrofit.create(RetrofitApi.class);
Call<List<User>> call= service.getData("user");2.6 發(fā)送請求數(shù)據(jù)
//異步
call.enqueue(new Callback<List<User>>() {
@Override
public void onResponse(Call<List<User>> call, Response<List<User>> response) {
//處理請求數(shù)據(jù)
}
@Override
public void onFailure(Call<List<User>> call, Throwable throwable) {
}
});
//同步
try {
Response<List<User>> execute = call.execute();
execute.body().toString();
} catch (IOException e) {
e.printStackTrace();
}三、Retrofit注解參數(shù)類型

3.1 網(wǎng)絡(luò)請求方法
3.1.1 GET請求
//簡單的get請求(沒有參數(shù))
@GET("user")
Call<UserInfo> getItem();//簡單的get請求(URL中帶有參數(shù))
@GET("News/{userId}")
Call<TradesBean> getItem(@Path("userId") String userId);//參數(shù)在url問號之后
@GET("trades")
Call<TradesBean> getItem(@Query("userId") String userId);//get請求,多個請求參數(shù)
@GET("trades")
Call<TradesBean> getItem(@QueryMap Map<String, String> map);
@GET("trades")
Call<TradesBean> getItem(
@Query("userId") String userId,
@QueryMap Map<String, String> map);//get請求,不使用baseUrl,直接請求url地址
@GET
Call<TradesBean> getItem(@Url String url,
@QueryMap Map<String, Object> params);3.1.2 POST請求
http://192.168.43.173/api/trades/{userId}
//需要補全URL,post的數(shù)據(jù)只有一條reason
@FormUrlEncoded
@POST("trades/{userId}")
Call<TradesBean> postResult(
@Path("userId") String userId,
@Field("reason") String reason;http://192.168.43.173/api/trades/{userId}?token={token}
//需要補全URL,問號后需要加token,post的數(shù)據(jù)只有一條reason
@FormUrlEncoded
@POST("trades/{userId}")
Call<TradesBean> postResult(
@Path("userId") String userId,
@Query("token") String token,
@Field("reason") String reason;
//post一個對象
@POST("trades/{userId}")
Call<TradesBean> postResult(
@Path("userId") String userId,
@Query("token") String token,
@Body TradesBean bean;//post請求,不使用baseUrl,直接請求url地址
@FormUrlEncoded
@POST
Call<TradesBean> postResultl(@Url String url,
@FieldMap Map<String, Object> params);3.2 標記類

3.2.1 @FormUrlEncoded
- 作用:表示發(fā)送form-encoded的數(shù)據(jù)
- @FieldMap必須與 @FormUrlEncoded 一起配合使用
3.2.2 @Multipart
- 作用:表示發(fā)送form-encoded的數(shù)據(jù)(適用于 有文件 上傳的場景)
- 每個鍵值對需要用@Part來注解鍵名,隨后的對象需要提供值。
@Multipart
@POST
Call<ResponseBody> uploadFiles(@Url String uploadUrl,
@Part MultipartBody.Part file);3.2.3 @Steaming
- 表示數(shù)據(jù)以流的形式返回
- 大文件官方建議用 @Streaming 來進行注解,不然會出現(xiàn)IO異常,小文件可以忽略不注入
/**
* 大文件官方建議用 @Streaming 來進行注解,不然會出現(xiàn)IO異常,小文件可以忽略不注入
*
* @param fileUrl 地址
* @return ResponseBody
*/
@Streaming
@GET
Call<ResponseBody> downloadFile(@Url String fileUrl);3.3 網(wǎng)絡(luò)請求類

3.3.1 @Header & @Headers
添加請求頭 &添加不固定的請求頭
// @Header
@GET("user")
Call<User> getUser(@Header("Authorization") String authorization)
// @Headers
@Headers("Authorization: authorization")
@GET("user")
Call<User> getUser()
// 以上的效果是一致的。
// 區(qū)別在于使用場景和使用方式
// 1. 使用場景:@Header用于添加不固定的請求頭,@Headers用于添加固定的請求頭
// 2. 使用方式:@Header作用于方法的參數(shù);@Headers作用于方法3.3.2 @Body
- 以 Post方式 傳遞 自定義數(shù)據(jù)類型 給服務(wù)器,@Body會將請求參數(shù)放到請求體中,所以適用于POST請求
- Body相當于多個@Field,以對象的方式提交,@Body 提交的提交的Content-Type 為application/json; charset=UTF-8
- @Body標簽不能和@FormUrlEncoded或@Multipart標簽同時使用,會報錯
3.3.3 @Field & @FieldMap
- 發(fā)送 Post請求 時提交請求的表單字段
- @FieldMap必須與 @FormUrlEncoded 一起配合使用
- 提交的Content-Type 為application/x-www-form-urlencoded
3.3.4 @Part & @PartMap
發(fā)送 Post請求 時提交請求的表單字段
與@Field的區(qū)別:功能相同,但攜帶的參數(shù)類型更加豐富,包括數(shù)據(jù)流,所以適用于 有文件上傳 的場景,與 @Multipart 注解配合使用
3.3.5 @Query和@QueryMap
用于 @GET 方法的查詢參數(shù)(Query = Url 中 ‘?’ 后面的 key-value)
//參數(shù)在url問號之后
@GET("trades")
Call<TradesBean> getItem(@Query("userId") String userId);3.3.6 @Path
URL地址的缺省值
@GET("users/{user}/repos")
Call<ResponseBody> getBlog(@Path("user") String user );
// 訪問的API是:https://api.github.com/users/{user}/repos
// 在發(fā)起請求時, {user} 會被替換為方法的第一個參數(shù) user(被@Path注解作用)3.3.7 @Url
直接傳入一個請求的 URL變量 用于URL設(shè)置
@GET
Call<ResponseBody> testUrlAndQuery(@Url String url, @Query("showAll") boolean showAll);
// 當有URL注解時,@GET傳入的URL就可以省略
// 當GET、POST...HTTP等方法中沒有設(shè)置Url時,則必須使用 {@link Url}提供下一篇文章總結(jié)一下Retrofit+Rxjava封裝成網(wǎng)絡(luò)請求庫
到此這篇關(guān)于Android Retrofit使用詳情的文章就介紹到這了,更多相關(guān)Android Retrofit使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Kotlin高效實現(xiàn) Android ViewPager2 頂部導(dǎo)航之動態(tài)配置與性能優(yōu)化指
文章介紹了使用AndroidViewPager2和TabLayout實現(xiàn)高效頂部導(dǎo)航的方法,并提供了優(yōu)化指南,包括避免不必要的Fragment實例化、動態(tài)配置頁面、使用Kotlin特性減少冗余代碼等,通過這些優(yōu)化,代碼變得更加高效、簡潔和易于維護,感興趣的朋友跟隨小編一起看看吧2025-03-03
Flutter實現(xiàn)倒計時秒數(shù)轉(zhuǎn)時分秒然后倒計時功能
有一個需求,需要在頁面進行顯示倒計時,倒計時結(jié)束后,做相應(yīng)的邏輯處理,這篇文章主要介紹了Flutter實現(xiàn)倒計時功能,秒數(shù)轉(zhuǎn)時分秒,然后倒計時,需要的朋友可以參考下2023-08-08
Android中實現(xiàn)多線程的幾種方式小結(jié)
在 Android 中,實現(xiàn)多線程編程主要有7種方式,每種方式都有其適用場景和優(yōu)缺點,本文將詳細介紹一下具體實現(xiàn)方式,大家可以根據(jù)需要自行選擇2025-03-03
Android編程實現(xiàn)啟動另外的APP及傳遞參數(shù)的方法
這篇文章主要介紹了Android編程實現(xiàn)啟動另外的APP及傳遞參數(shù)的方法,涉及Activity啟動及Intent設(shè)置相關(guān)操作技巧,需要的朋友可以參考下2017-05-05

