Junior — Middle
Vai esat izmantojis Retrofit bibliotēku darbam ar API jūsu projektos?
sobes.tech AI
Atbilde no AI
Jā, es izmantoju Retrofit bibliotēku, lai sadarboties ar REST API Android projektos. Retrofit vienkāršo HTTP pieprasījumu veidošanu un automātiski pārvērš JSON atbildes Java objektos, izmantojot konvertētājus (piemēram, Gson).
Retrofit lietošanas piemērs:
public interface ApiService {
@GET("users/{id}")
Call<User> getUser(@Path("id") int userId);
}
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.example.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiService api = retrofit.create(ApiService.class);
Call<User> call = api.getUser(1);
call.enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
if (response.isSuccessful()) {
User user = response.body();
// datu apstrāde
}
}
@Override
public void onFailure(Call<User> call, Throwable t) {
// kļūdu apstrāde
}
});
Retrofit palīdz rakstīt tīru un uzturamu kodu tīkla izsaukumiem.