Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Retrofit, a simple REST client for Android

Retrofit, a simple REST client for Android

Wilfredo Nieves

November 26, 2016
Tweet

More Decks by Wilfredo Nieves

Other Decks in Technology

Transcript

  1. What is Retrofiit? • Type-safe REST client for Android •

    Model your remote API’s as interfaces. • Developed by Square • Made open source in 2010 (Retrofit 1) • Leverages Java annotations describe HTTP requests.
  2. What does it do? • Consumes remote API’s • HTTP

    requests (POST, GET, PUT, DELETE, etc.) • File uploads • Authentication • Serializes JSON or XML responses to POJO’s (Plain Old Java Objects)
  3. Why use Retrofit • Easy to use • Wraps up

    Thread communication • Exception management. • Plenty of code examples on the web • Strong community
  4. What do we need? • POJO (Plain Old Java Object)

    • API service declarations (Java interfaces) • RestAdapter • android.permission.INTERNET Permission
  5. Plain Old Java Objects • Java Model class • Fields

    define a response from the API • Use the @SerializedName annotation to map response field name.
  6. Service Endpoints • Create a Java interface to describe your

    API endpoints • Use annotations to specify request type and headers • Callback parameter for asynchronous calls
  7. Rest Adapter • Retrofit class adapts a Java interface to

    HTTP calls by using annotations • Build using the base URL of the API and a Converter object • Use the create method to generate an implementation
  8. Asynchronous Request • The Call class sends a request to

    a webserver and returns a response • Use the enqueue() method to make an asynchronous requests, execute() for synchronous. • To cancel a request just: call.cancel() • Clone instances with: call.clone()
  9. Response • Parameterized Response object • Response info. • Code

    • Success • Message • Headers • Raw body • Error body
  10. New in retrofit 2.0 • OkHttp is the default connection

    interface (is automatically added) • Pluggable JSON and XML converters, even create them yourself • Gson: com.squareup.retrofit:converter-gson Jackson: com.squareup.retrofit:converter-jackson Moshi: com.squareup.retrofit:converter-moshi Protobuf: com.squareup.retrofit:converter-protobuf Wire: com.squareup.retrofit:converter-wire Simple XML: com.squareup.retrofit:converter-simplexml