I try to receive token via POST json {"email":"test@example.com","password":"test"}. In postman it works: Postman request. I try do the same in Android Studio. I create class Token:
public class Token {
@SerializedName("token")
@Expose
public String token;
}
And class APIclient
class APIClient {
private static Retrofit retrofit = null;
static Retrofit getClient() {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
retrofit = new Retrofit.Builder()
.baseUrl("http://mybaseurl.com/")
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
return retrofit;
}
}
and interface APIInterface:
interface APIInterface {
@POST("/authenticate")
Call<Token> getLoginResponse(@Body AuthenticationRequest request);
}
and class AuthenticationRequest:
public class AuthenticationRequest {
String email;
String password;
}
In onCreate in MainActivity:
apiInterface = APIClient.getClient().create(APIInterface.class);
authenticationRequest.email="test@example.com";
authenticationRequest.password="test";
getTokenResponse();
And here is my getTokenResponse method:
private void getTokenResponse() {
Call<Token> call2 = apiInterface.getLoginResponse(authenticationRequest);
call2.enqueue(new Callback<Token>() {
@Override
public void onResponse(Call<Token> call, Response<Token> response) {
Token token = response.body();
}
@Override
public void onFailure(Call<Token> call, Throwable t) {
call.cancel();
}
});
}
And this is what I see in Logcat:
03-15 10:53:56.579 20734-20756/com.retrofi2test D/OkHttp: --> POST http://mybaseurl.com/authenticate http/1.1
03-15 10:53:56.579 20734-20756/com.retrofi2test D/OkHttp: Content-Type: application/json; charset=UTF-8
03-15 10:53:56.579 20734-20756/com.retrofi2test D/OkHttp: Content-Length: 46
03-15 10:53:56.579 20734-20756/com.retrofi2test D/OkHttp: {"email":"test@example.com","password":"test"}
03-15 10:53:56.579 20734-20756/com.retrofi2test D/OkHttp: --> END POST (46-byte body)
Could you tell me what I'm doing wrong? I need to give token every time when I'd like to get information from server via GET method. How can I receive and save token in Android code?