欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Android?Retrofit使用詳細(xì)教程

 更新時(shí)間:2024年03月20日 10:33:02   作者:Billy_Zuo  
Retrofit是Android用來接口請求的網(wǎng)絡(luò)框架,內(nèi)部是基于OkHttp實(shí)現(xiàn)的,retrofit負(fù)責(zé)接口請求的封裝,retrofit可以直接將接口數(shù)據(jù)解析為Bean類、List集合等,直接簡化了中間繁瑣的數(shù)據(jù)解析過程,這篇文章主要介紹了Android?Retrofit使用詳情,需要的朋友可以參考下

一、 Retrofit是什么

Retrofit是Android用來接口請求的網(wǎng)絡(luò)框架,內(nèi)部是基于OkHttp實(shí)現(xiàn)的,retrofit負(fù)責(zé)接口請求的封裝,retrofit可以直接將接口數(shù)據(jù)解析為Bean類、List集合等,直接簡化了中間繁瑣的數(shù)據(jù)解析過程

二、 Retrofit的簡單使用

Retrofit在github的地址https://github.com/square/retrofit

Retrofit官方使用介紹 https://square.github.io/retrofit/

2.1 在項(xiàng)目中引入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請?jiān)谇鍐挝募嗀ndroidManifest.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問號(hào)之后
 @GET("trades")
 Call<TradesBean> getItem(@Query("userId") String userId);
//get請求,多個(gè)請求參數(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}

//需要補(bǔ)全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}

//需要補(bǔ)全URL,問號(hào)后需要加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一個(gè)對象
 @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 標(biāo)記類

3.2.1 @FormUrlEncoded

  • 作用:表示發(fā)送form-encoded的數(shù)據(jù)
  • @FieldMap必須與 @FormUrlEncoded 一起配合使用

3.2.2 @Multipart

  • 作用:表示發(fā)送form-encoded的數(shù)據(jù)(適用于 有文件 上傳的場景)
  • 每個(gè)鍵值對需要用@Part來注解鍵名,隨后的對象需要提供值。
    @Multipart
    @POST
    Call<ResponseBody> uploadFiles(@Url String uploadUrl,
                                         @Part MultipartBody.Part file);

3.2.3 @Steaming

  • 表示數(shù)據(jù)以流的形式返回
  • 大文件官方建議用 @Streaming 來進(jìn)行注解,不然會(huì)出現(xiàn)IO異常,小文件可以忽略不注入
    /**
     * 大文件官方建議用 @Streaming 來進(jìn)行注解,不然會(huì)出現(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會(huì)將請求參數(shù)放到請求體中,所以適用于POST請求
  • Body相當(dāng)于多個(gè)@Field,以對象的方式提交,@Body 提交的提交的Content-Type 為application/json; charset=UTF-8
  • @Body標(biāo)簽不能和@FormUrlEncoded或@Multipart標(biāo)簽同時(shí)使用,會(huì)報(bào)錯(cuò)

3.3.3 @Field & @FieldMap

  • 發(fā)送 Post請求 時(shí)提交請求的表單字段
  • @FieldMap必須與 @FormUrlEncoded 一起配合使用
  • 提交的Content-Type 為application/x-www-form-urlencoded

3.3.4 @Part & @PartMap

發(fā)送 Post請求 時(shí)提交請求的表單字段

與@Field的區(qū)別:功能相同,但攜帶的參數(shù)類型更加豐富,包括數(shù)據(jù)流,所以適用于 有文件上傳 的場景,與 @Multipart 注解配合使用

3.3.5 @Query和@QueryMap

用于 @GET 方法的查詢參數(shù)(Query = Url 中 ‘?’ 后面的 key-value)

//參數(shù)在url問號(hào)之后
 @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ā)起請求時(shí), {user} 會(huì)被替換為方法的第一個(gè)參數(shù) user(被@Path注解作用)

3.3.7 @Url

直接傳入一個(gè)請求的 URL變量 用于URL設(shè)置

  @GET
        Call<ResponseBody> testUrlAndQuery(@Url String url, @Query("showAll") boolean showAll);
       // 當(dāng)有URL注解時(shí),@GET傳入的URL就可以省略
       // 當(dāng)GET、POST...HTTP等方法中沒有設(shè)置Url時(shí),則必須使用 {@link Url}提供

下一篇文章總結(jié)一下Retrofit+Rxjava封裝成網(wǎng)絡(luò)請求庫

到此這篇關(guān)于Android Retrofit使用詳情的文章就介紹到這了,更多相關(guān)Android Retrofit使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論