retrofit一瞥

retrofit,这周采用的一个rest client库,在系统集成的时候用来从其他系统获取rest数据,使用起来非常简单方便。

retrofit可根据定义的api接口,发送http请求获取数据,数据会被指定的converter自动反序列化为对应的DTO(data template object)。由于大多数rest请求返回的数据都采用json格式,因此常用的converter为gson或jackson,这两个库提供了灵活的注解处理相应字段。下面以gson示例retrofit的使用。

class Book { // a DTO
  @SerializedName("name") //name based value put to title
  String title;
  String author;
  String year;
  String type; 
 //ignored getter and setters here...
}
class BookApiService{ //rest api
  @GET("v1/book/{id}")  //get method, request uri is v1/book/id
  public Call getBook(@Path("id")int id); //Call is like a future

  @GET("vi/books") //get method, request uri is vi/books?author=author&year=year
  public  Call> getBooks(@Query("author")String author, @Query("year")int year);

  @Headers("Content-Type: application/json")  //request headers
  @POST("v1/book/add") //post method, request uri is v1/book/add
  public Call addBook(@Body Book book, @Header("auth")String auth); //post request header with auth field, post data is a json format book
}

class BookService{  // retrofit service
  private Retrofit retrofit = new Retrofit.Builder().baseUrl("http://ip/").addConverterFactory(GsonConverterFactory().create()).build(); //base url is the start part of the rest uri , should be end with '/'
  private BookApiService service = retrofit.create(BookApiService.class);

  public Book getBook(int id){ //backend call this method to get book
    Call call = service.getBook(id);
    Response execute = call.execute();
    if(execute.isSuccessful()) { //if request success, make sure to judge success first
      return execute.body();
    } else{  //if request failed, bad request or internal server error...
      ResponseBody body = execute.errorBody(); //deal with error body
     ...
     return null; // or throw exception here
    }
  }
  // ignored other specified api method 
}

你可能感兴趣的:(retrofit一瞥)