使用Retrofit2調用HTTP API

前言

Retrofit會將你的HTTP接口調用轉換爲java的interface,你沒必要去實現這個接口,交給Retrofit來建立動態代理.
首先,貼上官網Javadoc.java

官網上的例子

加依賴,下jar包什麼的就跳過了,來一個官網例子就知道怎麼用了.git

//interface
public interface GitHubService {
  @GET("users/{user}/repos")
  Call<List<Repo>> listRepos(@Path("user") String user);
}
//建立工廠
Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.github.com/")
    .build();
    
//建立代理對象
GitHubService service = retrofit.create(GitHubService.class);
//調用方法得到Call對象
Call<List<Repo>> repos = service.listRepos("octocat");

此時尚未發送請求去調用HTTP API.Call對象提供了同步和異步兩種方式來發送請求:github

//同步,出錯時拋出IO或者Runtime異常
Response response = call.execute();
//異步
call.enqueue(new Callback() {
    @Override
    public void onResponse(Call call, Response response)
    {
        //TODO 成功時的回調
    }

    @Override
    public void onFailure(Call call, Throwable t) {
        //TODO 失敗時的回調
    }
});

關於Reponse和Call的細節,能夠去看Javadoc.json

註解介紹

Retrofit的類仍是挺少的,這裏就介紹些我用過的註解吧.api

請求方式的註解

@GET,@POST,@DELETE,@HEAD,@PUT,@PATCH@HTTP.除了@HTTP以外都沒什麼好說的.
@HTTP有三個參數:method,hasBody和path:app

@HTTP(method = "DELETE", path = "admin/delete_user", hasBody = true)
Call<Message> deleteUser(@Body UserVO vo, @Header("Apitoken") ApiToken apiToken
        , @Header("X-Forwarded-For") String forwardedFor);

一些蛋疼的DELETE,POST或者PUT API的response會有body,可是@DELETE,@POST,@PUT都不能有body,這時候就要用@HTTP了.異步

參數位置的註解

@Header,@Body,@Path,@Query,@QueryMap,'@Headers'
對應的參數若是不是基本類型包裝類的話會自動轉換爲json,沒有記錯的話,@Query,@QueryMap不能和'@POST','@PUT'搭配使用,直接來點例子吧.ide

@GET("strategy")
Call<List<Strategy>> getStrategyList(@Query("tid") Long tid,
                                     @Header("Apitoken")ApiToken apiToken,
                                     @Header("X-Forwarded-For") String forwardedFor);
@GET("graph/endpoint_counter")
Call<List<String>> getCounterOfEndpoint(@QueryMap Map<String, String> map,
                                        @Header("Apitoken") ApiToken apiToken,
                                        @Header("X-Forwarded-For") String forwardedFor);
//不要在乎這個奇怪的API
@Headers({"Content-type: application/x-www-form-urlencoded"})
@GET("alarm/eventcases")
Call<List<EventCase>> getEventCasesById(@Query("eventid") String eventId, @Header("Apitoken") ApiToken apiToken,
                                        @Header("X-Forwarded-For") String forwardedFor);

請求數據格式的註解

須要注意的是格式和參數的註解是對應的.ui

@FormUrlEncoded
@POST("user/edit")
Call<User> updateUser(@Field("first_name") String first, @Field("last_name") String last);
@Multipart
@PUT("user/photo")
Call<User> updateUser(@Part("photo") RequestBody photo, @Part("description") RequestBody description);

轉換器

經過添加不一樣的依賴來使用不一樣的轉換器:url

  • 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
相關文章
相關標籤/搜索