Retrofit使用总结

作者: 牧童遥指2000 | 来源:发表于2017-03-14 21:16 被阅读103次

    Retrofit-一个对Android和Java类型安全的HTTP客户端

    引言

    Retrofit把你的HTTP API变成了Java接口

    public interface GitHubService {
      @GET("users/{user}/repos")
      Call<List<Repo>> listRepos(@Path("user") String user);
    }
    
    
    

    生成类

    retrofit生成GitHubService接口的一个实现

    Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("https://api.github.com/")
        .build();
    
    GitHubService service = retrofit.create(GitHubService.class);
    

    获得Call对象

    每个GitHubService实现类获得的Call对象都能实现一个对远程服务器的同步和一部访问

    
    Call<List<Repo>> repos = service.listRepos("octocat");
    
    

    使用注释来描述HTTP 请求

    1.URL参数的替换和查询(query)

    2.对象转化成JSON请求

    1. Multipart请求和上传

    API 介绍

    方法和参数的注释表明了请求如何被执行

    1.请求方法

    每一个方法都有一个请求注释,代表了请求方式和相关的url。有五种基本的请求方式注释:GET, POST, PUT, DELETE, and HEAD.
    相关的链接在括号里写明了。

    e.g.:

    
    @GET("users/list")
    
    //也可以写明查询参数
    
    @GET("users/list?sort=desc")
    
    

    2.URL

    请求的URL可以被动态的改变

    可以用{id}和@path (“id”)实现动态替换,两个id必须相同

    
    
    @GET("group/{id}/users")
    Call<List<User>> groupList(@Path("id") int groupId);
    
    

    查询参数的动态替换

    链接:group/{id}/users?sort = sort

    e.g.:

    
    @GET("group/{id}/users")
    Call<List<User>> groupList(@Path("id") int groupId, @Query("sort") String sort);
    
    

    复杂的查询参数用map实现

    @GET("group/{id}/users")
    Call<List<User>> groupList(@Path("id") int groupId, @QueryMap Map<String, String> options);
    
    

    3.请求体对象

    当请求体是对象的时候,可以用@body标签

    
    @POST("users/new")
    Call<User> createUser(@Body User user);
    
    

    4.表单和MULTIPART

    @FormUrlEncoded注释用于表单数据的提交,@Field用于标识每个键值对

    
    @FormUrlEncoded
    @POST("user/edit")
    Call<User> updateUser(@Field("first_name") String first, @Field("last_name") String last);
    
    

    Multipart请求是用@ Multipart注释来标识的,每一部分的请求是 @Part标识

    
    @Multipart
    @PUT("user/photo")
    Call<User> updateUser(@Part("photo") RequestBody photo, @Part("description") RequestBody description);
    
    

    5. HEADER部分

    可以使用@Headers注释设置一个静态头

    
    @Headers("Cache-Control: max-age=640000")
    @GET("widget/list")
    Call<List<Widget>> widgetList();
    
    
    @Headers({
        "Accept: application/vnd.github.v3.full+json",
        "User-Agent: Retrofit-Sample-App"
    })
    @GET("users/{username}")
    Call<User> getUser(@Path("username") String username);
    
    

    在参数部分使用@Header进行动态头的设置

    @GET("user")
    Call<User> getUser(@Header("Authorization") String authorization)
    
    

    在Android中,callBACK将被在主线程中执行,在Java中,将被在调用的线程执行。

    Retrofit配置

    CONVERTERS转化器定制

    常见的五种

    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
    
    

    下面是一个GsonConverterFactory使用的例子

    
    Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("https://api.github.com")
        .addConverterFactory(GsonConverterFactory.create())
        .build();
    
    GitHubService service = retrofit.create(GitHubService.class);
    
    

    你也可以自己定制。

    Retrofit配置导入

    MAVEN

    
    
    
    <dependency>
      <groupId>com.squareup.retrofit2</groupId>
      <artifactId>retrofit</artifactId>
      <version>2.2.0</version>
    </dependency>
    
    

    GRADLE

    compile 'com.squareup.retrofit2:retrofit:2.2.0'
    Retrofit requires at minimum Java 7 or Android 2.3.
    
    

    PROGUARD配置

    
    # Platform calls Class.forName on types which do not exist on Android to determine platform.
    -dontnote retrofit2.Platform
    # Platform used when running on Java 8 VMs. Will not be used at runtime.
    -dontwarn retrofit2.Platform$Java8
    # Retain generic type information for use by reflection by converters and adapters.
    -keepattributes Signature
    # Retain declared checked exceptions for use by a Proxy instance.
    -keepattributes Exceptions
    
    
    

    相关文章

      网友评论

      本文标题:Retrofit使用总结

      本文链接:https://www.haomeiwen.com/subject/cehknttx.html