[置顶] 浅谈我为什么选择用Retrofit作为我的网络请求框架

来源:互联网 发布:贵人出门多逢雨 知乎 编辑:程序博客网 时间:2024/06/05 10:46

目录(?)[+]

  1. 比较AsyncTaskVolleyRetrofit三者的请求时间
    1. Retrofit20 完胜
  2. 使用
    1. 添加依赖
    2. 请求范例
      1. 声明接口
      2. 调用接口
    3. 进阶使用1ConverterFactory转换工厂
      1. Retrofit支持以下转换
      2. 添加依赖
      3. 定义java bean
      4. 接口方法声明
      5. 调用接口
    4. 进阶使用2 常用接口范例声明

比较AsyncTask、Volley、Retrofit三者的请求时间

使用单次请求7个请求25个请求AsyncTask941ms4539ms13957msVolley560ms2202ms4275msRetrofit2.0312ms889ms1059ms

Retrofit2.0 完胜

使用

添加依赖

build.gradle

compile ‘com.squareup.retrofit2:retrofit:2.0.0-beta4’

请求范例

以淘宝的ip库请求为例

  • 地址:http://ip.taobao.com/service/getIpInfo.php
  • 请求参数:ip
  • 请求方法: get

声明接口

[html] view plain copy
print?在CODE上查看代码片派生到我的代码片
  1. public interface ApiControl {  
  2.   
  3.     //@Query注解的作用理解为查询条件,这里表示需要查询的字段为ip  
  4.     //ResponseBody是Retrofit自带的返回类,  
  5.     @GET("http://ip.taobao.com/service/getIpInfo.php")  
  6.     Call<ResponseBody> getIpInfo(@Query("ip") String ip);  
  7. }  



调用接口

[html] view plain copy
print?在CODE上查看代码片派生到我的代码片
  1. //创建Retrofit实例  
  2. Retrofit retrofit = new Retrofit.Builder()  
  3.         //当我们的@GET()里有url时,这个baseUrl无效。但是这个必须要填,不然会报错,神奇。  
  4.         .baseUrl("http://www.taobao.com.cn/")  
  5.         .build();  
  6.   
  7. ApiControl apiStores = retrofit.create(ApiControl.class);  
  8. Call<ResponseBody> call = apiStores.getIpInfo("220.160.193.209");  
  9. //在主线程里,异步调用。  
  10. call.enqueue(new Callback<ResponseBody>() {  
  11.     @Override  
  12.     public void onResponse(Response<ResponseBody> response) {  
  13.         try {  
  14.             Log.i("onResponse", "response=" + response.body().string());  
  15.         } catch (IOException e) {  
  16.             e.printStackTrace();  
  17.         }  
  18.     }  
  19.   
  20.     @Override  
  21.     public void onFailure(Throwable t) {  
  22.         Log.i("onFailure", "onFailure=" + t.getMessage());  
  23.     }  
  24. });  


同步调用

[html] view plain copy
print?在CODE上查看代码片派生到我的代码片
  1. try {  
  2.     Response<ResponseBody> response = call.execute();  
  3. } catch (IOException e) {  
  4.     e.printStackTrace();  
  5. }  





进阶使用1:ConverterFactory转换工厂

可以帮我们将获取到的数据转换为JavaBEAN

Retrofit支持以下转换

Gson: com.squareup.retrofit2:converter-gson 
Jackson: com.squareup.retrofit2:converter-jackson 
Moshi: com.squareup.retrofit2:converter-moshi 
Protobuf: com.squareup.retrofit2:converter-protobuf 
Wire: com.squareup.retrofit2:converter-wire 
Simple XML: com.squareup.retrofit2:converter-simplexml 
Scalars (primitives, boxed, and String): com.squareup.retrofit2:converter-scalars

Retrofit这里以GsonConverterFactory的为例

添加依赖

compile ‘com.squareup.retrofit2:converter-gson:2.0.0-beta4’

定义java bean

[html] view plain copy
print?在CODE上查看代码片派生到我的代码片
  1. public class IpInfo {  
  2.   
  3.   
  4.     private int code;  
  5.   
  6.   
  7.     private DataBean data;  
  8.   
  9.     public int getCode() {  
  10.         return code;  
  11.     }  
  12.   
  13.     public void setCode(int code) {  
  14.         this.code = code;  
  15.     }  
  16.   
  17.     public DataBean getData() {  
  18.         return data;  
  19.     }  
  20.   
  21.     public void setData(DataBean data) {  
  22.         this.data = data;  
  23.     }  
  24.   
  25.     public static class DataBean {  
  26.         private String country;  
  27.         private String country_id;  
  28.         private String area;  
  29.         private String area_id;  
  30.         private String region;  
  31.         private String region_id;  
  32.         private String city;  
  33.         private String city_id;  
  34.         private String county;  
  35.         private String county_id;  
  36.         private String isp;  
  37.         private String isp_id;  
  38.         private String ip;  
  39.   
  40.         public String getCountry() {  
  41.             return country;  
  42.         }  
  43.   
  44.         public void setCountry(String country) {  
  45.             this.country = country;  
  46.         }  
  47.   
  48.         public String getCountry_id() {  
  49.             return country_id;  
  50.         }  
  51.   
  52.         public void setCountry_id(String country_id) {  
  53.             this.country_id = country_id;  
  54.         }  
  55.   
  56.         public String getArea() {  
  57.             return area;  
  58.         }  
  59.   
  60.         public void setArea(String area) {  
  61.             this.area = area;  
  62.         }  
  63.   
  64.         public String getArea_id() {  
  65.             return area_id;  
  66.         }  
  67.   
  68.         public void setArea_id(String area_id) {  
  69.             this.area_id = area_id;  
  70.         }  
  71.   
  72.         public String getRegion() {  
  73.             return region;  
  74.         }  
  75.   
  76.         public void setRegion(String region) {  
  77.             this.region = region;  
  78.         }  
  79.   
  80.         public String getRegion_id() {  
  81.             return region_id;  
  82.         }  
  83.   
  84.         public void setRegion_id(String region_id) {  
  85.             this.region_id = region_id;  
  86.         }  
  87.   
  88.         public String getCity() {  
  89.             return city;  
  90.         }  
  91.   
  92.         public void setCity(String city) {  
  93.             this.city = city;  
  94.         }  
  95.   
  96.         public String getCity_id() {  
  97.             return city_id;  
  98.         }  
  99.   
  100.         public void setCity_id(String city_id) {  
  101.             this.city_id = city_id;  
  102.         }  
  103.   
  104.         public String getCounty() {  
  105.             return county;  
  106.         }  
  107.   
  108.         public void setCounty(String county) {  
  109.             this.county = county;  
  110.         }  
  111.   
  112.         public String getCounty_id() {  
  113.             return county_id;  
  114.         }  
  115.   
  116.         public void setCounty_id(String county_id) {  
  117.             this.county_id = county_id;  
  118.         }  
  119.   
  120.         public String getIsp() {  
  121.             return isp;  
  122.         }  
  123.   
  124.         public void setIsp(String isp) {  
  125.             this.isp = isp;  
  126.         }  
  127.   
  128.         public String getIsp_id() {  
  129.             return isp_id;  
  130.         }  
  131.   
  132.         public void setIsp_id(String isp_id) {  
  133.             this.isp_id = isp_id;  
  134.         }  
  135.   
  136.         public String getIp() {  
  137.             return ip;  
  138.         }  
  139.   
  140.         public void setIp(String ip) {  
  141.             this.ip = ip;  
  142.         }  
  143.     }  
  144. }  


接口方法声明

[html] view plain copy
print?在CODE上查看代码片派生到我的代码片
  1. //GSON转换数据  
  2. @GET("http://ip.taobao.com/service/getIpInfo.php")  
  3. Call<IpInfo> getIpInfo2(@Query("ip") String ip);  


调用接口

[html] view plain copy
print?在CODE上查看代码片派生到我的代码片
  1. Call<IpInfo> ipInfoCall = apiStores.getIpInfo2("220.160.193.207");  
  2. ipInfoCall.enqueue(new Callback<IpInfo>() {  
  3.     @Override  
  4.     public void onResponse(Response<IpInfo> response) {  
  5.         Log.d("onResponse",response.body().getData().getCity());  
  6.     }  
  7.   
  8.     @Override  
  9.     public void onFailure(Throwable t) {  
  10.         Log.i("onFailure", "onFailure=" + t.getMessage());            }  
  11. });  


进阶使用2: 常用接口范例声明

[html] view plain copy
print?在CODE上查看代码片派生到我的代码片
  1. //这里url为请求地址  
  2.   
  3. //多参数,用map,注解用@QueryMap  
  4. @GET("url")  
  5. Call<ResponseBody> getInfo(@QueryMap Map<String,String> params);  
  6.   
  7. //post的请求参数是放在请求体中的,就是body内(详见http请求),这是以json格式传递参数的  
  8. @POST("url")  
  9. @FormUrlEncoded  
  10. Call<ResponseBody> doLogin(@Body User user);  
  11.   
  12. //post表单传递,map,就是我们一般用到的  
  13. @POST("url")  
  14. @FormUrlEncoded  
  15. Call<ResponseBody> doLogin(@FieldMap Map<String,String> params);  
  16.   
  17. //也是post表单传递,是以单个进行传递  
  18. @FormUrlEncoded  
  19. @POST("url")  
  20. Call<ResponseBody> doLogin(@Field("username") String name, @Field("password") String password);  
  21.   
  22. //请求头更改  
  23. @FormUrlEncoded  
  24. @Headers({"Accept: application/vnd.github.v3.full+json",  
  25.         "User-Agent: Retrofit-Sample-App"})  
  26. Call<ResponseBody> getUserInfo();  
  27.   
  28. //动态改变请求头  
  29. @GET("/user")  
  30. Call<User> getUser(@Header("Authorization")   
[html] view plain copy
print?在CODE上查看代码片派生到我的代码片
  1. String authorization);  
0 0
原创粉丝点击