1

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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Bartosz20188
  • 47
  • 1
  • 2
  • 10

2 Answers2

0

check this log:

    public void onResponse(Call<TokenInfo> call, Response<TokenInfo> response) {
        Log.d("error", response.errorBody().string())

    }
Saba
  • 1,208
  • 14
  • 19
0

you should see the

response.code()

if code is greater than 300 then it is client request error like: 404-> not found 401-> authentication error etc please let me know the error code