亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Android?Retrofit使用詳細教程

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

一、 Retrofit是什么

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

二、 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中添加網絡權限

<uses-permission android:name="android.permission.INTERNET"/>

Google在Android p為了安全起見,已經明確規(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文件,文件內容如下:

<?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ù)據解析器
                .build();

2.4 創(chuàng)建RetrofitApi

//定義 網絡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ù)據

        //異步
        call.enqueue(new Callback<List<User>>() {
            @Override
            public void onResponse(Call<List<User>> call, Response<List<User>> response) {
                //處理請求數(shù)據
            }
            @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 網絡請求方法

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ù)據只有一條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ù)據只有一條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ù)據
  • @FieldMap必須與 @FormUrlEncoded 一起配合使用

3.2.2 @Multipart

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

3.2.3 @Steaming

  • 表示數(shù)據以流的形式返回
  • 大文件官方建議用 @Streaming 來進行注解,不然會出現(xiàn)IO異常,小文件可以忽略不注入
    /**
     * 大文件官方建議用 @Streaming 來進行注解,不然會出現(xiàn)IO異常,小文件可以忽略不注入
     *
     * @param fileUrl 地址
     * @return ResponseBody
     */
    @Streaming
    @GET
    Call<ResponseBody> downloadFile(@Url String fileUrl);

3.3 網絡請求類

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ù)據類型 給服務器,@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ù)據流,所以適用于 有文件上傳 的場景,與 @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設置

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

下一篇文章總結一下Retrofit+Rxjava封裝成網絡請求庫

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

相關文章

最新評論