概念
特點
性能好、處理快,使用簡單;默認使用okhttp處理網絡請求;默認使用Gson解析。
常用註解接口
Retrifit採用註解方式標註方法,常用接口如下:
實現簡單網絡請求
步驟
Demo
1、創建接口
public interface GitHubApi {
//使用GET註解,參數爲baseUrl後邊的路徑
@GET("repos/{owner}/{repo}/contributors")
//返回類型爲帶有泛型的Call,使用Path註解標註參數
Call<ResponseBody> contributorsBySimpleGetCall(@Path("owner")
String owner, @Path("repo") String repo);
}
2、創建Retroift實例//其中指定了baseUrl
Retrofit retrofit = new Retrofit.Builder().baseUrl("https://api.github.com/")
.build();
3、通過Retrofit實例創建接口服務對象
GitHubApi repo = retrofit.create(GitHubApi.class);
4、調用接口中自定義方法獲取Call對象
Call<ResponseBody> call = repo.contributorsBySimpleGetCall(mUserName, mRepo);
5、調用Call對象enqueue()方法執行網絡請求
//注意,callback在主線程中執行
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
Gson gson = new Gson();
ArrayList<Contributor> contributorsList = gson.fromJson(response.body().string(),
new TypeToken<List<Contributor>>(){}.getType());
for (Contributor contributor : contributorsList){
Log.d("login",contributor.getLogin());
Log.d("contributions",contributor.getContributions()+"");
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
添加轉換器
1、創建Javabean
public class Contributor {
private String login;
private Integer contributions;
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public Integer getContributions() {
return contributions;
}
public void setContributions(Integer contributions) {
this.contributions = contributions;
}
}
2、修改接口,返回的不再是Response,而是List<Contributor>@GET("repos/{owner}/{repo}/contributors")
Call<List<Contributor>> contributorsByAddConverterGetCall(@Path("owner") String owner, @Path("repo") String repo);
3、創建retrofit時添加轉換器
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
4、修改調用
GitHubApi repo = retrofit.create(GitHubApi.class);
Call<List<Contributor>> call = repo.contributorsByAddConverterGetCall(mUserName, mRepo);
call.enqueue(new Callback<List<Contributor>>() {
@Override
public void onResponse(Call<List<Contributor>> call, Response<List<Contributor>> response) {
List<Contributor> contributorList = response.body();
for (Contributor contributor : contributorList){
Log.d("login", contributor.getLogin());
Log.d("contributions", contributor.getContributions() + "");
}
}
@Override
public void onFailure(Call<List<Contributor>> call, Throwable t) {
}
});
簡單的Retrofit調用過程就是如此