How do I send a POST request via Retrofit 2.0?
Perhaps now a stupid question will be asked, because I am new to Java programming and to Android development in general, so I want to apologize in advance. I need to get data from the API using Retrofit 2.0. I watched all sorts of tutorials on the Internet, moreover, I even managed to get a list of Github repositories. But I do not understand how to get not a list,but something specific. For example, at the moment I need to send the / login method the parameters E-Mail and Password to get the authorization token. But, as mentioned above, I can't figure out how :( If someone could help me in any way, I would be very grateful. I'm not asking you to write code for me, I'm asking you to help me figure it all out.
1 answers
Copy and paste the results of a successful request from Postman to http://www.jsonschema2pojo.org/, if necessary, correct the received files and insert them into the Android Studio project in the (package) directory named model - the name is optional, it's just traditionally established. After that, you write two modules: the factory and the service, and put them in the project in the network directory.
Factory code:
//Импортируем необходимые классы
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
//Объявляем фабрику - только статичные поля и методы
public class ApiFactory {
private static final String ROOT_URL = "https://your_api_address";
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 (taking into account the POST request and the login and input parameters password):
//Импортируйте получившиеся у Вас в JSON-POJO модели
//В данном случае Вы должны назвать свою модель AccessToken
import com.YOUR_BRAND.YOUR_APP_NAME.model.AccessToken;
import retrofit2.Call;
import retrofit2.http.POST;
import retrofit2.http.Query;
import retrofit2.http.Headers;
public interface ApiService {
@Headers("Content-Type: application/json")
@POST("auth/login") //путь вашего сервиса к авторизации
Call<AccessToken> getToken(
@Query("login") String login,
@Query("password") String password);
}
In the main part of your application, to get a token in response to a username and password, you write something like this (taking into account how you have named variables, classes, etc.):
private void getToken() {
Call<AccessToken> call = ApiFactory.getService().getToken(EMAIL, PASSWORD);
call.enqueue(new Callback<AccessToken>() {
@Override
public void onResponse(Call<AccessToken> call, Response<AccessToken> response) {
if (response.isSuccessful()) {
//Тут Вы просто сохраняете токен для дальнейшего использования
MainActivity.token = response.body().getData().getToken();
MainActivity.tokenAcquired = true;
Log.d("myLogs", token);
getTasks();
} else {
MainActivity.token = "";
MainActivity.tokenAcquired = false;
Log.d("myLogs", ErrorUtils.errorMessage(response));
}
}
@Override
public void onFailure(Call<AccessToken> call, Throwable t) {}
});
}
ErrorUtils class (optional, only for parsing the error):
package com.YOUR_BRAND.YOUR_APP_NAME.network;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.Locale;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Response;
public class ErrorUtils {
private static final String ERROR_MESSAGE = "Код HTTP: %d\nОшибка: %s\nКод ошибки: %d";
private static APIError parseError(Response<?> response) {
Converter<ResponseBody, APIError> converter =
ApiFactory.buildRetrofit()
.responseBodyConverter(APIError.class, new Annotation[0]);
APIError error;
try {
error = converter.convert(response.errorBody());
} catch (IOException e) {
return new APIError();
}
return error;
}
public static String errorMessage(Response<?> response) {
try {
APIError error = parseError(response);
return String.format(Locale.getDefault(), ERROR_MESSAGE, response.code(), error.message(), error.status());
} catch (com.google.gson.JsonSyntaxException e) {
return String.format(Locale.getDefault(), ERROR_MESSAGE, response.code(), "NULL", 0);
}
}
}
ApiError class
package com.YOUR_BRAND.YOUR_APP_NAME.network;
import com.google.gson.annotations.SerializedName;
public class APIError {
@SerializedName("httpStatus")
private int statusCode;
@SerializedName("errorMessage")
private String message;
public APIError() {
}
public int status() {
return statusCode;
}
public String message() {
return message;
}
}
Well, here's some information to start thinking about. com. YOUR_BRAND.YOUR_APP_NAME is the name of your project, specified in the headers of java modules. Bye sort it out and have a good night. If you have any questions, ask them, but I'll answer them tomorrow. I'm sorry in advance if there are any typos in the code. Good work!