Retrofit

27
RETROFIT A type-safe REST client for Android and Java http://square.github.io/retrofit/ Michał Brewczak [https://github.com/Bresiu/android_bootcamp] droidsonroids android bootcamp 2015

Transcript of Retrofit

Page 1: Retrofit

RETROFITA type-safe REST client for Android and Java

http://square.github.io/retrofit/

Michał Brewczak [https://github.com/Bresiu/android_bootcamp]droidsonroids android bootcamp 2015

Page 2: Retrofit

GRADLE

compile ‘com.squareup.retrofit:retrofit:1.9.0' compile ‘com.squareup.okio:okio:1.4.0' compile 'com.squareup.okhttp:okhttp-urlconnection:2.4.0' compile ‘com.squareup.okhttp:okhttp:2.4.0’

compile 'com.google.code.gson:gson:2.3.1'

Page 3: Retrofit

INITIALIZE REST ADAPTERString ENDPOINT = "http://api.openweathermap.org/data/2.5";

RestAdapter mRestAdapter = new RestAdapter.Builder() .setLogLevel(RestAdapter.LogLevel.FULL) .setLog(new AndroidLog(TAG)) .setEndpoint(Const.ENDPOINT) .build();

Page 4: Retrofit

SAMPLE API METHODS [SYNC]

public interface WeatherService { @GET(“/weather”) WeatherResponse getWeatherWithAsync( @Query("q") String cityName); }

Page 5: Retrofit

SAMPLE API METHODS [ASYNC]

public interface WeatherService { @GET(“/weather”)

void getWeatherWithCallback( @Query("q") String cityName, Callback<WeatherResponse> callback);

}

Page 6: Retrofit

BETTER APPROACH* [ASYNC]

* for the ambitious

Page 7: Retrofit

SAMPLE API METHODS [ASYNC]

public interface WeatherService { @GET(“/weather”)

Observable<WeatherResponse> getWeatherWithObservable( @Query("q") String cityName);

}

Page 8: Retrofit

BIND API SERVICE TO ADAPTERmRestAdapterApi = restAdapter.create(WeatherService.class);

Page 9: Retrofit

REQUEST METHODS

@GET, @POST, @PUT, @DELETE, @HEAD

Page 10: Retrofit

REQUEST METHODS

@GET, @POST, @PUT, @DELETE, @HEAD

@GET(“/weather")

Page 11: Retrofit

REQUEST METHODS

@GET, @POST, @PUT, @DELETE, @HEAD

@POST(“/users/new”) void createUser(@Body User user);

Page 12: Retrofit

REQUEST METHODS

@GET, @POST, @PUT, @DELETE, @HEAD

@PUT(“/user/photo”) void uploadPhoto(…);

@DELETE(“/user/{id}”) void deleteUser(…);

Page 13: Retrofit

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

Page 14: Retrofit

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

http://www.api.com/group/42/users?sort=desc

Page 15: Retrofit

HEADER MANIPULATION@Headers(“Content-type: application/json”) @GET(“/group/{id}/users”)

List<User> groupList(@Path(“id”) int groupId);

Page 16: Retrofit

A LITTLE BIT OF GSON

Page 17: Retrofit

JSON{    "coord":{       "lon":17.03,       "lat":51.1    },    "weather":[       {          "id":800,          "main":"Clear",          "description":"Sky is Clear",          "icon":"01d"       }    ],    "base":"stations",    "main":{       "temp":301.7,       "pressure":1015,       "humidity":41,       "temp_min":298.15,       "temp_max":306.48    } … }

Page 18: Retrofit

JSON{    "weather":[       {          …          "icon":"01d"       }    ],    "main":{       "temp":301.7,       "pressure":1015,       "humidity":41,       "temp_min":298.15,       "temp_max":306.48    } … }

Page 19: Retrofit

JSONWeatherResponse.class

@SerializedName("weather") private ArrayList<Weather> weathers;@SerializedName("main") private Main main;public ArrayList<Weather> getWeathers() { return this.weathers;}public void setWeathers(ArrayList<Weather> weathers) { this.weathers = weathers;}public Main getMain() { return this.main;}public void setMain(Main main) { this.main = main;}

Page 20: Retrofit

JSONWeather.class

@SerializedName("icon") private String icon;public String getIcon() { return this.icon;}public void setIcon(String icon) { this.icon = icon;}

Page 21: Retrofit

JSONMain.class

@SerializedName("temp") private Double temp;@SerializedName("pressure") private Double pressure; @SerializedName("temp_min") private Double tempMin;@SerializedName("temp_max") private Double tempMax;

{getters & setters + @Override toString()}

underscore_case [json] vs camelCase [java]

Page 22: Retrofit

RUN QUERY [ASYNC / OBSERVABLE]ApiManager apiManager = new ApiManager();apiManager.getWeatherWithObservable("Wrocław") .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Action1<WeatherResponse>() { @Override public void call(WeatherResponse weatherResponse) { Log.d(TAG, weatherResponse.toString()); } });

Page 23: Retrofit

RUN QUERY [ASYNC / CALLBACK]ApiManager apiManager = new ApiManager(); Callback<WeatherResponse> callback = new Callback<WeatherResponse>() { @Override public void success(WeatherResponse weatherResponse, Response response) { Log.d(TAG, weatherResponse.toString()); } @Override public void failure(RetrofitError error) { Log.d(TAG, error.toString()); }}; apiManager.getWeatherWithCallback("Wrocław", callback);

Page 24: Retrofit

RUN QUERY [SYNC / MAIN THREAD]ApiManager apiManager = new ApiManager(); WeatherResponse weatherResponse = apiManager.getWeatherWithSync(“Wrocław"); Log.d(TAG, weatherResponse.toString());

E/AndroidRuntime﹕ FATAL EXCEPTION: mainCaused by: android.os.NetworkOnMainThreadException

Page 25: Retrofit

RUN QUERY [ASYNC / ASYNC TASK]ApiManager apiManager = new ApiManager(); new AsyncTask<String, Void, WeatherResponse>() { @Override protected WeatherResponse doInBackground(String... params) { return apiManager.getWeatherWithSync(params[0]); } @Override protected void onPostExecute(WeatherResponse weatherResponse) { Log.d(TAG, weatherResponse.toString()); }}.execute("Wrocław");

Page 26: Retrofit

OUTPUT<--- HTTP 200 http://api.openweathermap.org/data/2.5/weather?q=Wroc%C5%82aw&units=metric (196ms) Server: nginx Date: Sun, 12 Jul 2015 12:03:31 GMT Content-Type: application/json; charset=utf-8 Transfer-Encoding: chunked Connection: keep-alive X-Source: redis Access-Control-Allow-Origin: * Access-Control-Allow-Credentials: true Access-Control-Allow-Methods: GET, POST OkHttp-Selected-Protocol: http/1.1 OkHttp-Sent-Millis: 1436702610277 OkHttp-Received-Millis: 1436702610352 {"coord":{"lon":17.03,"lat":51.1},"weather":[{"id":800,"main":"Clear","description":"Sky is Clear","icon":"01d"}],"base":"stations","main":{"temp":28.24,"pressure":1015,"humidity":41,"temp_min":25,"temp_max":31.11},"visibility":10000,"wind":{"speed":1.5},"clouds":{"all":0},"dt":1436701846,"sys":{"type":1,"id":5375,"message":0.0126,"country":"PL","sunrise":1436669458,"sunset":1436727807},"id":3081368,"name":"Wroclaw","cod":200} <--- END HTTP (431-byte body) 07

Page 27: Retrofit

THE END