由浅入深了解Retrofit(一)

时间:2023-03-09 10:01:28
由浅入深了解Retrofit(一)

Retrofit

Retrofit与okhttp共同出自于Square公司,Retrofit是一个高质量和高效率的http库,Retrofit是对okhttp的网络框架做了一层封装,Retrofit内部的网络请求还是中转给了okhttp来实现,通过Retrofit我们可以非常简单的进行网络请求,提高效率和正确率;

地址

Retrofit 官网:http://square.github.io/retrofit/

github地址:https://github.com/square/retrofit

使用

在Android项目使用Retrofit框架,首先要先添加依赖引用:

compile 'com.squareup.retrofit2:retrofit:2.3.0'

compile 'com.squareup.retrofit2:converter-gson:2.0.2'

Retrofit框架将业务需求进行接口封装,并在接口方法中添加Retrofit注解;

public interface ISearchService {
String HOST = "http://localhost/Store.SOA.Host/api/json/";
@POST("GetCityCountryInfo")
Call<CountryInfo> SearchCountryInfo(@Body SearchCountryInfoRequest request);
}

在ISearchService 接口中定义了查询国家信息的接口,Post注解和Body是Retrofit框架定义的注解;Post标识的是HTTP的POST请求;POST注解中的Value值与HOST组成了这次请求的URL;Body注解代表的POST的请求包体;

使用Retrofit框架,首先是实例化这个Retrofit对象的实例,在Retrofit框架中实例的创建时通过构建模式来创建;

 Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ISearchService.HOST)
.addConverterFactory(GsonConverterFactory.create())
.build();
ISearchService SearchClient= (ISearchService)retrofit.create(ISearchService.class);
SearchCountryInfoRequest request=new SearchCountryInfoRequest();
request.setCityID(58);
Call<CountryInfo> call=SearchClient.SearchCountryInfo(request);

获取到Retrofit对象的实例后,通过create方法来获取ISearchService 接口的动态代理对象,拿到这个动态代理对象后就可以调用接口的方法;

通过动态代理对象调用接口方法获取到的是实现了Call<T>接口的实例,在Call<T>接口中定义网络请求执行的方法(execute,enqueue),execute方法是同步调用,enqueue是异步调用的返回,这2个方法在底层都是调用的okhttp的网络请求方法;

   Response<CountryInfo> result=call.execute();
CountryInfo countryInfo =result.body();