使用 Retrofit 的步骤共有6个:
步骤1:添加Retrofit库的依赖
dependencies {
compile 'com.squareup.retrofit2:retrofit:2.0.2'
// Retrofit库
compile 'com.squareup.okhttp3:okhttp:3.1.2'
// Okhttp库
}
步骤2:创建 接收服务器返回数据 的类
public static class Contributor {
public final String login;
public final int contributions;
public Contributor(String login, int contributions) {
this.login = login;
this.contributions = contributions;
}
@Override
public String toString() {
return "Contributor{" +
"login='" + login + '\'' +
", contributions=" + contributions +
'}';
}
}
步骤3:创建 用于描述网络请求 的接口
Retrofit将 Http请求 抽象成 Java接口:采用 注解 描述网络请求参数 和配置网络请求参数 。
- 用 动态代理 动态 将该接口的注解“翻译”成一个 Http 请求,最后再执行 Http 请求
- 注:接口中的每个方法的参数都需要使用注解标注,否则会报错
public interface GitHub {
@GET("/repos/{owner}/{repo}/contributors")
Call<List<Contributor>> contributors(
@Path("owner") String owner,
@Path("repo") String repo);
}
步骤4:创建 Retrofit 实例
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com")
.addConverterFactory(GsonConverterFactory.create())
.client(new OkHttpClient())
.build();
步骤5:创建 网络请求接口实例 并 配置网络请求参数
GitHub gitHubService = retrofit.create(GitHub.class);
Call<List<Contributor>> call = gitHubService.contributors("square", "retrofit");
步骤6:发送网络请求(异步 / 同步)并 处理服务器返回的数据
try{
Response<List<Contributor>> response = call.execute(); // 同步
Log.d(TAG, "response:" + response.body().toString());
} catch (IOException e) {
e.printStackTrace();
}
//发送网络请求(异步)
call.enqueue(new Callback<Translation>() {
//请求成功时回调
@Override
public void onResponse(Call<Translation> call, Response<Translation> response) {
//请求处理,输出结果
response.body().show();
}
//请求失败时候的回调
@Override
public void onFailure(Call<Translation> call, Throwable throwable) {
System.out.println("连接失败");
}
});