It is necessary to obtain information about the exchange rate, the bank’s website has api in json format, how to get yourself into the application. http://www.nbrb.by/APIHelp/ExRates - can anyone look and help?
1 answer
Run the address http://www.nbrb.by/API/ExRates/Currencies/ {Cur_ID} through Postman or another (possibly online) means to get JSON responses to requests. The result obtained using http://www.jsonschema2pojo.org/ convert to a Java-model.
First, do not forget to add the following dependencies in app / build.gra
implementation 'com.google.code.gson:gson:2.8.0' implementation 'com.squareup.retrofit2:retrofit:2.1.0' implementation 'com.squareup.retrofit2:converter-gson:2.1.0' All models put in the model folder.
Create a network folder, and put the service and factory there.
Factory code:
//Импортируем необходимые классы import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; //Объявляем фабрику - только статичные поля и методы public class ApiFactory { private static final String ROOT_URL = "http://www.nbrb.by/API/ExRates"; static Retrofit buildRetrofit() { return new Retrofit.Builder() .baseUrl(ROOT_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); } public static ApiService getService() { return buildRetrofit().create(ApiService.class); } } Service Code:
//Импортируйте получившиеся у Вас в JSON-POJO модели import com.YOUR_BRAND.YOUR_APP_NAME.model.Currency; import com.YOUR_BRAND.YOUR_APP_NAME.model.Rate; import com.YOUR_BRAND.YOUR_APP_NAME.model.Dynamics; //В данном случае они должны быть в папке model вашего проекта import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Path; import retrofit2.http.Query; import retrofit2.http.Headers; public interface ApiService { @Headers("Content-Type: application/json") @GET("/Currencies/{id}") Call<Currency> getCurrency( @Path("id") String code) @Headers("Content-Type: application/json") @GET("/Rates/{id}") Call<Rate> getRate( @Path("id") String code, @Query("onDate") String onDate, @Query("Periodicity") String periodicity, @Query("ParamMode") String paramMode) @Headers("Content-Type: application/json") @GET("/Rates/Dynamics/{id}") Call<Dynamics> getDynamics( @Path("id") String code, @Query("startDate") String startDate, @Query("endDate") String endDate) } To send a request and get a result where needed (for example, in MainActivity), use the following code (using the example of a currency query, you will write two other requests by analogy):
Call<Currency> call = ApiFactory.getService().getCurrency("1"); //или другой код валюты call.enqueue(new Callback<Currency>() { @Override public void onResponse(Call<Currency> call, Response<Currency> response) { if (response.isSuccessful()) { //Действия, если запрос прошёл //Доступ к ответу на запрос - response.body().getData() //он имеет класс Currency } else { //действия, если запрос не прощёл Log.d("myLogs", ErrorUtils.errorMessage(response)); } } @Override public void onFailure(Call<Currency> call, Throwable t) {} }); In the network folder, also put the classes ApiError and ErrorUtils. Take them here:
How to send a POST request via Retrofit 2.0?
If you have questions, write
- In general, I figured out the receipt and converted it to a code through this online translator, I don’t understand a bit how to make the request in the code itself and send the request directly to the application - Vadim Orlovsky
- @ VadimOrlovskiy see answer update - Pavel Sumarokov 5:02
- Thank you very much, you helped me a lot, I didn’t need it a bit, but thanks to you, I found everything I needed! - Vadim Orlovsky