历史由来:
随着Google对HttpClient的摒弃,和Volley的逐渐没落,OkHttp开始异军突起,而Retrofit则对okHttp进行了强制依赖。Retrofit也是Square公司开发的一款针对Android网络请求的框架,其实质就是对okHttp的封装,使用面向接口的方式进行网络请求,利用动态生成的代理类封装了网络接口。retrofit非常适合于RESTful url格式的请求,更多使用注解的方式提供功能。
既然是RESTful架构,那么我们就来看一下什么是REST吧。
REST(REpresentational State Transfer)是一组架构约束条件和原则。RESTful架构都满足以下规则:
(1)每一个URI代表一种资源;
(2)客户端和服务器之间,传递这种资源的某种表现层;
(3)客户端通过四个HTTP动词(GET,POST,PUT,DELETE),对服务器端资源进行操作,实现”表现层状态转化”。
使用Retrofit2.0
依赖注意事项:
1.Retrofit必须使用okhttp请求了,如果项目中没有okhttp的依赖的话,肯定会出错 。
2.okhttp内部依赖okio所以也要添加。
用法介绍
创建API接口
在retrofit中通过一个Java接口作为http请求的api接口。
//定以接口
public interface GitHubService {
@GET("users/{user}/repos")
Call<List<Repo>> listRepos(@Path("user") String user);
}
创建retrofit实例
/**获取实例*/
Retrofit retrofit = new Retrofit.Builder()
//设置OKHttpClient,如果不设置会提供一个默认的
.client(new OkHttpClient())
//设置baseUrl
.baseUrl("https://api.github.com/")
//添加Gson转换器
.addConverterFactory(GsonConverterFactory.create())
.build();
注:
1.retrofit2.0后:BaseUrl要以/结尾;@GET 等请求不要以/开头;@Url: 可以定义完整url,不要以 / 开头。
2.addConverterFactory提供Gson支持,可以添加多种序列化Factory,但是GsonConverterFactory必须放在最后,否则会抛出异常。
调用API接口
GitHubService service = retrofit.create(GitHubService.class);
//同步请求
//https://api.github.com/users/octocat/repos
Call<List<Repo>> call = service.listRepos("octocat");
try {
Response<List<Repo>> repos = call.execute();
} catch (IOException e) {
e.printStackTrace();
}
//不管同步还是异步,call只能执行一次。否则会抛 IllegalStateException
Call<List<Repo>> clone = call.clone();
//异步请求
clone.enqueue(new Callback<List<Repo>>() {
@Override
public void onResponse(Response<List<Repo>> response, Retrofit retrofit) {
// Get result bean from response.body()
List<Repo> repos = response.body();
// Get header item from response
String links = response.headers().get("Link");
/**
* 不同于retrofit1 可以同时操作序列化数据javabean和header
*/
}
@Override
public void onFailure(Throwable throwable) {
showlog(throwable.getCause().toString());
}
});
取消请求
我们可以终止一个请求。终止操作是对底层的httpclient执行cancel操作。即使是正在执行的请求,也能够立即终止。
call.cancel();
retrofit注解
(1)方法注解,包含@GET、@POST、@PUT、@DELETE、@PATH、@HEAD、@OPTIONS、@HTTP。
(2)标记注解,包含@FormUrlEncoded、@Multipart、@Streaming。
(3)参数注解,包含@Query、@QueryMap、@Body、@Field,@FieldMap、@Part,@PartMap。
(4)其他注解,包含@Path、@Header、@Headers、@Url。
使用例子:
一般的get请求
public interface IWeatherGet {
@GET("GetMoreWeather?cityCode=101020100&weatherType=0")
Call<Weather> getWeather();
}
可以看到有一个getWeather()方法,通过@GET注解标识为get请求,@GET中所填写的value和baseUrl组成完整的路径,baseUrl在构造retrofit对象时给出。
Retrofit retrofit = new Retrofit.Builder()
/**http://weather.51wnl.com/weatherinfo/GetMoreWeather?cityCode=101020100&weatherType=0*/
//注意baseurl要以/结尾
.baseUrl("http://weather.51wnl.com/weatherinfo/")
.addConverterFactory(GsonConverterFactory.create())
.build();
IWeatherGet weather = retrofit.create(IWeatherGet.class);
Call<Weather> call = weather.getWeather();
call.enqueue(new Callback<Weather>() {
@Override
public void onResponse(Response<Weather> response, Retrofit retrofit) {
Weather weather = response.body();
WeatherInfo weatherinfo = weather.weatherinfo;
showlog("weather="+weatherinfo.toString());
}
@Override
public void onFailure(Throwable throwable) {
showlog(throwable.getCause().toString());
}
});