I have a JWT Authentication in Spring Boot application. In the backend, POST method /login return JSON as like
{"token":"xxxxxxxxxxxxxxxxxxxxxxxxx"}
I have this problem with Android client. I use Retrofit 2.
In interface I have:
@POST("/login")
Call<TokenInfo> login(@Body UserCredentials userCredentials);
My retrofit Client:
package com.findme.my_app_android;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
public class RetrofitClient {
private static Retrofit ourInstance;
public static Retrofit getInstance(){
if(ourInstance==null)
ourInstance = new Retrofit.Builder()
.baseUrl("http://172.20.10.2:8080")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
return ourInstance;
}
}
And in MainActivity
i use:
private void login(UserCredentials userCredentials, final View v){
Call<TokenInfo> call = restAPI.login(userCredentials);
call.enqueue(new Callback<TokenInfo>() {
@Override
public void onResponse(Call<TokenInfo> call, Response<TokenInfo> response) {
//retrofit authentication token save
if(response.isSuccessful()){
Log.d("token", response.body().token);
}
openDeviceChoiceActivity();
}
@Override
public void onFailure(Call<TokenInfo> call, Throwable t) {
openAlert(v);
}
});
}
In Call<...> i use TokenInfo
and TokenHolder
as below:
public class TokenInfo {
@SerializedName("token")
@Expose
public String token;
}
or
public class TokenHolder {
private static TokenHolder instance = new TokenHolder();
private String token = null;
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public static TokenHolder getInstance() {
return instance;
}
}
Unfortunately, always my response.body()
is null
. What is the problem?