Skip to content

Instantly share code, notes, and snippets.

@lopspower
Last active April 30, 2019 10:26
Show Gist options
  • Save lopspower/004f9295966ab5cb6ef6 to your computer and use it in GitHub Desktop.
Save lopspower/004f9295966ab5cb6ef6 to your computer and use it in GitHub Desktop.
Retrofit Introduction

Retrofit Introduction

Twitter API

Type-safe HTTP client for Android and Java by Square, Inc.

Download

Gradle:

compile 'com.squareup.retrofit:retrofit:2.0.0-beta2'

And Gson:

compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'

📚 Best Android Gists

You can see other best Android Gists or offer your just here https://github.com/lopspower/BestAndroidGists 👍.

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, Retrofit retrofit) {
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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment