Junior — Middle
Da li ste koristili biblioteku Retrofit za rad sa API-jem u svojim projektima?
sobes.tech АИ
Одговор од АИ
Да, koristio sam biblioteku Retrofit za interakciju sa REST API-jem u Android projektima. Retrofit pojednostavljuje kreiranje HTTP zahteva i automatski pretvara JSON odgovore u Java objekte pomoću konvertera (npr. Gson).
Primer korišćenja Retrofit-a:
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();
// обрада података
}
}
@Override
public void onFailure(Call<User> call, Throwable t) {
// обрада грешке
}
});
Retrofit помаже да се пише чист и одржив код за мрежне позиве.