什么是Retrofit
官方网站中将Retrofit
描述为
A type-safe REST client for Android and Java.
我们可以使用注释来描述HTTP
请求,URL
参数替换和查询参数(@Query
)是默认支持的。另外,还提供了自定义的头部(Headers
),multipart
,文件的上传和下载,mocking responses
等等。在后面的教程中,将看到这些详细教程。
Retrofit2
依赖配置引入
// retrofit利用OkHttp作为默认的网络层,在Okhttp的基础上建立的
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
//用于打印返回回来的数据
compile 'com.squareup.okhttp3:logging-interceptor:3.8.1'
添加网路请求权限
<uses-permission android:name="android.permission.INTERNET" />
如何描述一个API
创建一个接口然后定义请求方法。
ZhiHu Client
public interface ZhiHuClient {
// https://news-at.zhihu.com/api/4/news/before/20170707
@GET("/api/4/news/before/{date}")
Call<ZhiHuPaseNews> getZhiHuPastNews(@Path("date") String date);
}
上面的代码定义了一个ZhiHu Client
接口和一个getZhiHuPastNews
方法,这个方法返回知乎过往消息。@GET
注释声明该方法使用HTTP GET
方法。上面代码还演示了如何修改路径参数。方法的{ }
路径,会被getZhiHuPastNews
传递进来的参数替换。
ZhiHuPaseNews
该类包含映射响应数据所需的类属性。
public class ZhiHuPaseNews {
private String date;
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
注:实际开发中会用GsonFormat
生成相关实体类。
请求数据
//请求的Base url
String API_BASE_URL = "https://news-at.zhihu.com/";
//通过给okhttpClient设置拦截器,能很方便的看到网络返回的数据
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
httpClient.addInterceptor(httpLoggingInterceptor);
//简单配置ZhiHuClient
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create());
Retrofit retrofit = builder.client(httpClient.build()).build();
ZhiHuClient client = retrofit.create(ZhiHuClient.class);
//传入参数,动态替换url上的参数
Call<ZhiHuPaseNews> call = client.getZhiHuPastNews("20170707");
//异步请求
call.enqueue(new Callback<ZhiHuPaseNews>() {
@Override
public void onResponse(Call<ZhiHuPaseNews> call, Response<ZhiHuPaseNews> response) {
//成功返回的回调
//TODO:把返回结果展示
}
@Override
public void onFailure(Call<ZhiHuPaseNews> call, Throwable t) {
//失败返回的回调
//TODO:处理返回失败
}
});
这时通过控制台能看到类似这样的Log
总结
上面的例子中,还有很多能改进的地方(例如缓存的管理,每次访问网络不必去生成一个新的对象),但是作为学习的开始这已经足够了。