Android Retrofit2的詳細(xì)使用

Retrofit2

1.Retrofit2概述

1,Retrofit框架是Square公司出品的目前非常流行的網(wǎng)絡(luò)框架.
效率高,實(shí)現(xiàn)簡(jiǎn)單,運(yùn)用注解和動(dòng)態(tài)代理.
極大簡(jiǎn)化了網(wǎng)絡(luò)請(qǐng)求的繁瑣步驟,非常適合REST ful網(wǎng)絡(luò)請(qǐng)求.
目前Retofit版本是2

2,Retrofit其實(shí)我們可以理解為OkHttp的加強(qiáng)版。
它也是一個(gè)網(wǎng)絡(luò)加載框架。底層是使用OKHttp封裝的。
準(zhǔn)確來(lái)說(shuō),網(wǎng)絡(luò)請(qǐng)求的工作本質(zhì)上是OkHttp完成,而 Retrofit 僅負(fù)責(zé)網(wǎng)絡(luò)請(qǐng)求接口的封裝。
它的一個(gè)特點(diǎn)是包含了特別多注解,方便簡(jiǎn)化你的代碼量。
并且還支持很多的開源庫(kù)(著名例子:Retrofit + RxJava)

2.Retrofit2的好處

1,超級(jí)解耦
    解耦?解什么耦?
    我們?cè)谡?qǐng)求接口數(shù)據(jù)的時(shí)候,API接口定義和API接口使用總是相互影
響,什么傳參、回調(diào)等,耦合在一塊。有時(shí)候我們會(huì)考慮一下怎么封裝我們的代
碼讓這兩個(gè)東西不那么耦合,這個(gè)就是Retrofit的解耦目標(biāo),也是它的最大的特點(diǎn)。
2,可以配置不同HttpClient來(lái)實(shí)現(xiàn)網(wǎng)絡(luò)請(qǐng)求,如OkHttp、HttpClient...
3,支持同步、異步和RxJava
4,可以配置不同的反序列化工具來(lái)解析數(shù)據(jù),如json、xml...
5,請(qǐng)求速度快,使用非常方便靈活

3.Retrofit2配置

1,官網(wǎng):http://square.github.io/retrofit/
2,依賴:
    implementation 'com.squareup.retrofit2:retrofit:2.5.0'
3,OkHttp庫(kù)依賴
    由于Retrofit是基于OkHttp,所以還需要添加OkHttp庫(kù)依賴
    implementation 'com.squareup.okhttp3:okhttp:3.12.0'
4,添加網(wǎng)絡(luò)權(quán)限
    <uses-permission android:name="android.permission.INTERNET" />

4,Retrofit2的使用步驟

1,定義接口(封裝URL地址和數(shù)據(jù)請(qǐng)求)
2,實(shí)例化Retrofit
3,通過(guò)Retrofit實(shí)例創(chuàng)建接口服務(wù)對(duì)象
4,接口服務(wù)對(duì)象調(diào)用接口中的方法,獲取Call對(duì)象
5,Call對(duì)象執(zhí)行請(qǐng)求(異步、同步請(qǐng)求)

Retrofit2發(fā)送GET、POST請(qǐng)求(異步、同步)

1.Retrofit2發(fā)送GET

//主機(jī)地址
String URL = "http://api.shujuzhihui.cn/api/news/";//必須以反斜杠結(jié)尾

//接口服務(wù)
public interface MyServer {
    
    //GET
    @GET("categories?appKey=908ca46881994ffaa6ca20b31755b675")
    Call<ResponseBody> getData1();

    @GET("categories?")
    Call<ResponseBody> getData2(@Query("appKey") String appkey);

    @GET("categories?")
    Call<ResponseBody> getData3(@QueryMap Map<String,Object> map);
}

//Get異步
private void initGetEnqueue() {

    //1.創(chuàng)建Retrofit對(duì)象
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(MyServer.URL)
            .build();
    
    //2.獲取MyServer接口服務(wù)對(duì)象
    MyServer myServer = retrofit.create(MyServer.class);
    
    //3.獲取Call對(duì)象
    //方式一
    Call<ResponseBody> call1 = myServer.getData1();

    //方式二
    Call<ResponseBody> call2 = myServer.getData2("908ca46881994ffaa6ca20b31755b675");

    //方式三
    Map<String,Object> map = new HashMap<>();
    map.put("appKey","908ca46881994ffaa6ca20b31755b675");
    Call<ResponseBody> call = myServer.getData3(map);

    //4.Call對(duì)象執(zhí)行請(qǐng)求
    call.enqueue(new Callback<ResponseBody>() {

        @Override
        public void onResponse(Call<ResponseBody> call,Response<ResponseBody> response) {

            try {
                String result = response.body().string();

                Log.e("retrofit", "onResponse: "+result);
                tv.setText(result);//默認(rèn)直接回調(diào)主線程
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {

            Log.e("retrofit", "onFailure: "+t.getMessage());
        }
    });
}


//GET同步
private void initGetExecute() {

    //1.創(chuàng)建Retrofit對(duì)象
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(MyServer.URL)
            .build();

    //2.獲取MyServer接口服務(wù)對(duì)象
    MyServer myServer = retrofit.create(MyServer.class);

    //3.獲取Call對(duì)象
    final Call<ResponseBody> call = myServer.getData1();

    new Thread(){//子線程執(zhí)行
        @Override
        public void run() {
            super.run();

            try {
                //4.Call對(duì)象執(zhí)行請(qǐng)求
                Response<ResponseBody> response = call.execute();

                final String result = response.body().string();

                Log.e("retrofit", "onResponse: "+result);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tv.setText(result);//默認(rèn)直接回調(diào)主線程
                    }
                });
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }.start();

}

2.Retrofit2發(fā)送POST

String URL = "http://api.shujuzhihui.cn/api/news/";//必須以反斜杠結(jié)尾

public interface MyServer {
    
    //POST("categories?")    POST("categories")相同
    @POST("categories?")
    @FormUrlEncoded
    Call<ResponseBody> postData1(@Field("appKey") String appKey);

    @POST("categories")  
    @FormUrlEncoded
    Call<ResponseBody> postData2(@FieldMap Map<String,Object> map);
}

//POST異步
private void initPostEnqueue() {

    //1.創(chuàng)建Retrofit對(duì)象
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(MyServer.URL)
            .build();

    //2.獲取MyServer接口服務(wù)對(duì)象
    MyServer myServer = retrofit.create(MyServer.class);

    //3.獲取Call對(duì)象
    //方式一
    Call<ResponseBody> call1 = myServer.postData1("908ca46881994ffaa6ca20b31755b675");

    //方式二
    Map<String,Object> map = new HashMap<>();
    map.put("appKey","908ca46881994ffaa6ca20b31755b675");
    Call<ResponseBody> call = myServer.postData2(map);

    //4.Call對(duì)象執(zhí)行請(qǐng)求
    call.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call,Response<ResponseBody> response) {

            try {
                String result = response.body().string();

                Log.e("retrofit", "onResponse: "+result);
                tv.setText(result);//默認(rèn)直接回調(diào)主線程
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {

            Log.e("retrofit", "onFailure: "+t.getMessage());
        }
    });
}

Retrofit注解

注解代碼       請(qǐng)求格式

請(qǐng)求方式:
    @GET           GET請(qǐng)求
    @POST          POST請(qǐng)求
    @DELETE        DELETE請(qǐng)求
    @HEAD          HEAD請(qǐng)求
    @OPTIONS       OPTIONS請(qǐng)求
    @PATCH         PATCH請(qǐng)求

請(qǐng)求頭:
    @Headers("K:V") 添加請(qǐng)求頭,作用于方法
    @Header("K")    添加請(qǐng)求頭,參數(shù)添加頭
    @FormUrlEncoded 用表單數(shù)據(jù)提交,搭配參數(shù)使用
    @Multipart      用文件上傳提交   multipart/form-data

請(qǐng)求參數(shù):
    @Query          替代參數(shù)值,通常是結(jié)合get請(qǐng)求的
    @QueryMap       替代參數(shù)值,通常是結(jié)合get請(qǐng)求的
    @Field          替換參數(shù)值,是結(jié)合post請(qǐng)求的
    @FieldMap       替換參數(shù)值,是結(jié)合post請(qǐng)求的

請(qǐng)求路徑:
    @Path           替換路徑
    @Url            路徑拼接

請(qǐng)求體:
    @Body(RequestBody)  設(shè)置請(qǐng)求體,是結(jié)合post請(qǐng)求的

文件處理:
    @Part Multipart.Part
    @Part("key") RequestBody requestBody(單參)
    @PartMap Map<String,RequestBody> requestBodyMap(多參)
    @Body RequestBody requestBody(自定義參數(shù))

Retrofit2其他常用注解使用

String URL = "http://api.shujuzhihui.cn/api/news/";//必須以反斜杠結(jié)尾

public interface MyServer {
    
    //Path
    @GET("wages/{wageId}/detail") 
    Call<ResponseBody >getImgData(@Path("wageId") String wageId);

    //Url
    @GET
    Call<ResponseBody >getImgData(@Url String url);

    @GET
    Call<ResponseBody >getImgData(@Url String url,@Query("appKey") String appkey);

    
    //Json
    @POST("categories")
    @Headers("Content-Type:application/json")
    Call<ResponseBody> getFormDataJson(@Body RequestBody requestBody);

    //Form
    @POST("categories")
    @Headers("Content-Type:application/x-www-form-urlencoded")
    Call<ResponseBody> getFormData1(@Body RequestBody requestBody);

    //復(fù)用URL
    @POST()
    @Headers("Content-Type:application/x-www-form-urlencoded")
    Call<ResponseBody> getFormData2(@Url String url,@Body RequestBody requestBody);

    //通用
    @POST()
    Call<ResponseBody> getFormData3(@Url String url, @Body RequestBody requestBody, @Header("Content-Type") String contentType);
}

//RequestBody參數(shù)拼接
private void initPostBody() {

    Retrofit.Builder builder = new Retrofit.Builder();
    Retrofit retrofit = builder.baseUrl(MyServer.URL)
            .build();

    MyServer myServer = retrofit.create(MyServer.class);

    //Json類型
    String json1 = "{\n" + "    \"appKey\": \"908ca46881994ffaa6ca20b31755b675\"\n" +  "}";
    RequestBody requestBody01 = RequestBody.create(MediaType.parse("application/json,charset-UTF-8"),json1);
    Call<ResponseBody> call01 = myServer.getFormDataJson(requestBody01);

    //String類型
    //有參形式
    RequestBody requestBody02 = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded,charset-UTF-8"),"appKey=908ca46881994ffaa6ca20b31755b675");
    Call<ResponseBody> call02 = myServer.getFormData1(requestBody02);

    //無(wú)參形式
    RequestBody requestBody3 = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded,charset-UTF-8"),"");
    Call<ResponseBody> call03 = myServer.getFormData1(requestBody3);

    //RequestBody (Form表單,鍵值對(duì)參數(shù)形式)
    //方式一(requestBody)
    FormBody requestBody = new FormBody.Builder()
            .add("appKey","908ca46881994ffaa6ca20b31755b675")
            .build();
    Call<ResponseBody> call1 = myServer.getFormData1(requestBody);

    //方式二(url+requestBody)
    FormBody requestBody = new FormBody.Builder()
            .add("appKey","908ca46881994ffaa6ca20b31755b675")
            .build();
    Call<ResponseBody> call2 = myServer.getFormData2("categories",requestBody);

    //方式三(url+requestBody+header)
    FormBody requestBody = new FormBody.Builder()
            .add("appKey","908ca46881994ffaa6ca20b31755b675")
            .build();
    Call<ResponseBody> call3 = myServer.getFormData3("categories",requestBody,"application/x-www-form-urlencoded");


    call3.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {

            try {
                String result = response.body().string();

                Log.e("retrofit", "onResponse: "+result);
                tv.setText(result);//默認(rèn)直接回調(diào)主線程
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {

            Log.e("retrofit", "onFailure: "+t.getMessage());
        }
    });
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容