概念
特点
性能好、处理快,使用简单;默认使用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调用过程就是如此