zoukankan      html  css  js  c++  java
  • 由浅入深了解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();
  • 相关阅读:
    Codeforces Round #368 (Div. 2)D. Persistent Bookcase DFS
    POJ Sudoku 数独填数 DFS
    Memory
    UESTC 771 最大容积(前缀后缀和)
    【题解】P2916 [USACO08NOV]安慰奶牛Cheering up the Cow-C++
    Prim算法与Kruskal(没有代码)
    【题解】P1396 营救-C++
    【题解】Unit Fraction Partition-C++
    【题解】P2078 朋友-C++
    【题解】P1892 [BOI2003]团伙-C++
  • 原文地址:https://www.cnblogs.com/h20064528/p/6866554.html
Copyright © 2011-2022 走看看