Retrofit
Transcript of 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
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'
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();
SAMPLE API METHODS [SYNC]
public interface WeatherService { @GET(“/weather”) WeatherResponse getWeatherWithAsync( @Query("q") String cityName); }
SAMPLE API METHODS [ASYNC]
public interface WeatherService { @GET(“/weather”)
void getWeatherWithCallback( @Query("q") String cityName, Callback<WeatherResponse> callback);
}
BETTER APPROACH* [ASYNC]
* for the ambitious
SAMPLE API METHODS [ASYNC]
public interface WeatherService { @GET(“/weather”)
Observable<WeatherResponse> getWeatherWithObservable( @Query("q") String cityName);
}
BIND API SERVICE TO ADAPTERmRestAdapterApi = restAdapter.create(WeatherService.class);
REQUEST METHODS
@GET, @POST, @PUT, @DELETE, @HEAD
REQUEST METHODS
@GET, @POST, @PUT, @DELETE, @HEAD
@GET(“/weather")
REQUEST METHODS
@GET, @POST, @PUT, @DELETE, @HEAD
@POST(“/users/new”) void createUser(@Body User user);
REQUEST METHODS
@GET, @POST, @PUT, @DELETE, @HEAD
@PUT(“/user/photo”) void uploadPhoto(…);
@DELETE(“/user/{id}”) void deleteUser(…);
URL MANIPULATION@GET(“/group/{id}/users") List<User> groupList(@Path(“id") int groupId);
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
HEADER MANIPULATION@Headers(“Content-type: application/json”) @GET(“/group/{id}/users”)
List<User> groupList(@Path(“id”) int groupId);
A LITTLE BIT OF GSON
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 } … }
JSON{ "weather":[ { … "icon":"01d" } ], "main":{ "temp":301.7, "pressure":1015, "humidity":41, "temp_min":298.15, "temp_max":306.48 } … }
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;}
JSONWeather.class
@SerializedName("icon") private String icon;public String getIcon() { return this.icon;}public void setIcon(String icon) { this.icon = icon;}
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]
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()); } });
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);
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
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");
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
THE END