由浅入深了解Retrofit(一)

本文介绍Retrofit框架的使用方法,包括配置依赖、定义接口、发起请求等步骤,并通过一个查询国家信息的例子详细展示了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();

 

转载于:https://www.cnblogs.com/h20064528/p/6866554.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值