zoukankan      html  css  js  c++  java
  • Retrofit2,A type-safe HTTP client for Android and Java

    Retrofit2

    A type-safe HTTP client for Android and Java . Retrofit2

    Introduction

    • Retrofit turns your HTTP API into a Java interface.
    public interface GitHubService {
      @GET("users/{user}/repos")
      Call<List<Repo>> listRepos(@Path("user") String user);
    }
    
    // The Retrofit class generates an implementation of the GitHubService interface.
    
    Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("https://api.github.com/")
        .build();
    
    GitHubService service = retrofit.create(GitHubService.class);
    
    
    • Each Call from the created GitHubService can make a synchronous or asynchronous HTTP request to the remote webserver.

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

    • Use annotations to describe the HTTP request:
      • URL parameter replacement and query parameter support
      • Object conversion to request body (e.g., JSON, protocol buffers)
      • Multipart request body and file upload

    API Declaration

    Annotations on the interface methods and its parameters indicate how a request will be handled.

    REQUEST METHOD

    Every method must have an HTTP annotation that provides the request method and relative URL. There are five built-in annotations: GET, POST, PUT, DELETE, and HEAD. The relative URL of the resource is specified in the annotation. @GET("users/list") You can also specify query parameters in the URL. @GET("users/list?sort=desc").

    URL MANIPULATION

    A request URL can be updated dynamically using replacement blocks and parameters on the method. A replacement block is an alphanumeric string surrounded by { and }. A corresponding parameter must be annotated with @Path using the same string.

    可以使用方法上的替换块和参数动态更新请求URL。 替换块是由{和}包围的字母数字串。 必须使用相同的字符串使用“@ Path”注释相应的参数。

    @GET("group/{id}/users")
    Call<List<User>> groupList(@Path("id") int groupId);
    
    • Query parameters can also be added.
    @GET("group/{id}/users")
    Call<List<User>> groupList(@Path("id") int groupId, @Query("sort") String sort);
    
    • For complex query parameter combinations a Map can be used.
    @GET("group/{id}/users")
    Call<List<User>> groupList(@Path("id") int groupId, @QueryMap Map<String, String> options);
    
    • REQUEST BODY

    An object can be specified for use as an HTTP request body with the @Body annotation.

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

    The object will also be converted using a converter specified on the Retrofit instance. If no converter is added, only RequestBody can be used.

    该对象也将使用在Retrofit实例上指定的转换器进行转换。 如果没有加入转换器,则只能使用RequestBody.(意思是说,它允许你自定义序列化组件,比如gsonjacksonProtobuf等等)

    • FORM ENCODED AND MULTIPART

    Methods can also be declared to send form-encoded and multipart data.

    Form-encoded data is sent when @FormUrlEncoded is present on the method. Each key-value pair is annotated with @Field containing the name and the object providing the value.

    当方法中存在@FormUrlEncoded时,会发送表单编码数据。 每个键值对都用@Field进行注释,其中包含名称和提供该值的对象。

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

    Multipart requests are used when @Multipart is present on the method. Parts are declared using the @Part annotation.

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

    Multipart parts use one of Retrofit's converters or they can implement RequestBody to handle their own serialization.

    HEADER MANIPULATION

    You can set static headers for a method using the @Headers annotation.

    @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);
    

    Note that headers do not overwrite each other. All headers with the same name will be included in the request.

    请注意,标题不会相互覆盖。 所有名称相同的标题都将包含在请求中。(意思是,同一个头属性别重复指定就好了,否则会重复显示)

    A request Header can be updated dynamically using the @Header annotation. A corresponding parameter must be provided to the @Header. If the value is null, the header will be omitted. Otherwise, toString will be called on the value, and the result used.

    可以使用@Header注释动态更新请求头。 必须向@Header提供相应的参数。 如果值为null,则头将被省略。 否则,将调用toString的值,并使用结果。

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

    Headers that need to be added to every request can be specified using an OkHttp interceptor.

    SYNCHRONOUS VS. ASYNCHRONOUS

    Call instances can be executed either synchronously or asynchronously. Each instance can only be used once, but calling clone() will create a new instance that can be used.

    调用实例可以同步或异步执行。 每个实例只能使用一次,但调用“clone()”将会创建一个可以使用的新实例。

    On Android, callbacks will be executed on the main thread. On the JVM, callbacks will happen on the same thread that executed the HTTP request.

    在Android上,回调将在主线程上执行。 在JVM上,回调将发生在执行HTTP请求的同一个线程上。

    Retrofit Configuration

    Retrofit is the class through which your API interfaces are turned into callable objects. By default, Retrofit will give you sane defaults for your platform but it allows for customization.

    Retrofit是将API接口转换为可调用对象的类。 默认情况下,Retrofit将为您的平台提供明智的默认值,但允许自定义。

    CONVERTERS

    By default, Retrofit can only deserialize HTTP bodies into OkHttp's ResponseBody type and it can only accept its RequestBody type for @Body.
    Converters can be added to support other types. Six sibling modules adapt popular serialization libraries for your convenience.

    • 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

    Here's an example of using the GsonConverterFactory class to generate an implementation of the GitHubService interface which uses Gson for its deserialization.

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

    CUSTOM CONVERTERS

    If you need to communicate with an API that uses a content-format that Retrofit does not support out of the box (e.g. YAML, txt, custom format) or you wish to use a different library to implement an existing format, you can easily create your own converter. Create a class that extends the Converter.Factory class and pass in an instance when building your adapter.

    Download

    ↓ v2.3.0 JAR

    The source code to the Retrofit, its samples, and this website is available on GitHub.

    MAVEN

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

    GRADLE

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

    Retrofit requires at minimum Java 7 or Android 2.3.

    PROGUARD

    If you are using ProGuard in your project add the following lines to your configuration:

    # 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 uses Okio under the hood, so you may want to look at its ProGuard rules as well.

  • 相关阅读:
    <modules>
    如何禁用Visual Studio 2013的Browser Link功能
    Visual Studio 2013 Web开发、新增功能:“Browser Link”
    MVC中的AppendTrailingSlash以及LowercaseUrls
    js如何关闭当前页,而不弹出提示框
    border-radius实例1
    border-radius讲解2
    border-radius讲解1
    Android服务Service具体解释(作用,生命周期,AIDL)系列文章-为什么须要服务呢?
    最小生成树-Prim算法和Kruskal算法
  • 原文地址:https://www.cnblogs.com/hager/p/7495989.html
Copyright © 2011-2022 走看看