17 Temmuz 2023 Pazartesi

Retrofit

Giriş
Altta OKHttp kullanır

Örnek
Elimizde şöyle bir arayüz olsun
interface JsonPlaceholderApi {
    @GET("todos/{id}")
    Call<Todo> getTodo(@Path("id") int id);
}

class Todo {
    int userId;
    int id;
    String title;
    boolean completed;

    // getters and setters
}
Şöyle yaparız
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;


Retrofit retrofit = new Retrofit.Builder()
  .baseUrl("https://jsonplaceholder.typicode.com/")
  .addConverterFactory(GsonConverterFactory.create())
  .build();

JsonPlaceholderApi jsonPlaceholderApi = retrofit.create(JsonPlaceholderApi.class);

Call<Todo> call = jsonPlaceholderApi.getTodo(1);
call.enqueue(new Callback<Todo>() {
  @Override
  public void onResponse(Call<Todo> call, Response<Todo> response) {
    if (!response.isSuccessful()) {
      System.out.println("Unexpected code " + response);
      return;
    }
Todo todo = response.body();
    System.out.println(todo);
  }
@Override
  public void onFailure(Call<Todo> call, Throwable t) {
    t.printStackTrace();
  }
});

Hiç yorum yok:

Yorum Gönder