Type-safe HTTP client for Android and Java by Square, Inc.
Gradle:
compile 'com.squareup.retrofit:retrofit:2.0.0-beta2'And Gson:
compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'| android { | |
| //... | |
| } | |
| dependencies { | |
| //... | |
| compile 'com.squareup.retrofit:retrofit:2.0.0-beta2' | |
| compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2' | |
| } |
| import retrofit.Call; | |
| import retrofit.http.GET; | |
| /** | |
| * Copyright (C) 2016 Mikhael LOPEZ | |
| * Licensed under the Apache License Version 2.0 | |
| * Example Data WebService | |
| * Created by Mikhael LOPEZ on 18/12/2015. | |
| */ | |
| public interface DataWebService { | |
| @GET("data.json") | |
| Call<YourDTO> getData(); | |
| } |
| import retrofit.Call; | |
| import retrofit.Response; | |
| /** | |
| * Copyright (C) 2016 Mikhael LOPEZ | |
| * Licensed under the Apache License Version 2.0 | |
| */ | |
| public class MainActivity extends Activity { | |
| //... | |
| private void downloadData() { | |
| DataWebService service = RetrofitFactory.getRetrofit().create(DataWebService.class); | |
| Call<DataDTO> call = service.getData(); | |
| call.enqueue(new retrofit.Callback<DataDTO>() { | |
| @Override | |
| public void onResponse(Response<DataDTO> response) { | |
| if (response != null && response.isSuccess()) { | |
| DataDTO data = response.body(); | |
| if (data != null) { | |
| // TODO Work Well | |
| } else { | |
| // TODO Fail | |
| } | |
| } else { | |
| // TODO Fail | |
| } | |
| } | |
| @Override | |
| public void onFailure(Throwable t) { | |
| // TODO Fail | |
| } | |
| }); | |
| } | |
| } |
| import android.Manifest; | |
| import android.support.annotation.RequiresPermission; | |
| import retrofit.GsonConverterFactory; | |
| import retrofit.Retrofit; | |
| /** | |
| * Copyright (C) 2016 Mikhael LOPEZ | |
| * Licensed under the Apache License Version 2.0 | |
| * RetrofitFactory to generate a Retrofit instance | |
| */ | |
| public class RetrofitFactory { | |
| // Base URL: always ends with / | |
| private static final String URL_MAIN_WEBSERVICE = "http://url-main-webservice/"; | |
| //region Singleton Retrofit | |
| private static Retrofit retrofit; | |
| /** | |
| * Get {@link Retrofit} instance. | |
| * @return instances of {@link Retrofit} | |
| */ | |
| @RequiresPermission(Manifest.permission.INTERNET) | |
| public static Retrofit getRetrofit() { | |
| if (retrofit == null) { | |
| retrofit = new Retrofit.Builder() | |
| .baseUrl(URL_MAIN_WEBSERVICE) | |
| .addConverterFactory(GsonConverterFactory.create()) | |
| .build(); | |
| } | |
| return retrofit; | |
| } | |
| //endregion | |
| } |