Android Retrofit簡介

——當(dāng)你沒有錢,拿什么去發(fā)展事業(yè),拿什么去享受生活

前言

許久沒寫總結(jié)了,之前學(xué)過的東西也都忘的差不多。今天抽空復(fù)習(xí)下之前的筆記。

一、簡介

github地址:GitHub

(1)是什么

——是一個(gè)okhttp網(wǎng)絡(luò)請求框架的封裝。

(2)有什么用

——對okhttp進(jìn)行拓展:

1.解耦 通過注解獲取網(wǎng)絡(luò)請求參數(shù)

2.支持Rxjava.Gson

3......

二、怎么用

步驟:

(1)添加依賴

 implementation "com.squareup.retrofit2:retrofit:2.9.0"

(2)創(chuàng)建Retrofit

Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://api.github.com/")
                .build();

(3)創(chuàng)建用于描述網(wǎng)絡(luò)請求的接口???????

//獲取API 
GitHubService service = retrofit.create(GitHubService.class);
//定義 網(wǎng)絡(luò)API 地址
public interface GitHubService {
    @GET("users/{user}/repos")
    Call<List<User>> getData(@Path("user") String user);
}

(4)創(chuàng)建Call對象/網(wǎng)絡(luò)請求接口實(shí)例???????

Call<List<User>> call= service.getData("user");

(5)發(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();
        }

(6)總結(jié)

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://api.github.com/")
                .build();

        GitHubService service = retrofit.create(GitHubService.class);

        Call<List<User>> call = service.getData("octocat");

        call.enqueue(new Callback<List<User>>() {
            @Override
            public void onResponse(Call<List<User>> call, Response<List<User>> response) {}
            @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();
        }

三、原理

這一塊就不獻(xiàn)丑 ,推薦一篇更詳細(xì)的解說 http://www.itdecent.cn/p/0c055ad46b6c

四、內(nèi)容推薦

若您發(fā)現(xiàn)文章中存在錯誤或不足的地方,希望您能指出!

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

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