——當(dāng)你沒有錢漆魔,拿什么去發(fā)展事業(yè)硝全,拿什么去享受生活
前言
許久沒寫總結(jié)了,之前學(xué)過的東西也都忘的差不多抄腔。今天抽空復(fù)習(xí)下之前的筆記瓢湃。
一、簡介
github地址:GitHub
(1)是什么
——是一個okhttp網(wǎng)絡(luò)請求框架的封裝赫蛇。
(2)有什么用
——對okhttp進行拓展:
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ò)請求接口實例???????
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();
}
三、原理
這一塊就不獻丑 悟耘,推薦一篇更詳細的解說 http://www.reibang.com/p/0c055ad46b6c
四落蝙、內(nèi)容推薦
若您發(fā)現(xiàn)文章中存在錯誤或不足的地方,希望您能指出!