2

I am having an issue with sending token in header and getting some information from website after authorization.

Here is my MainActivity.java:

    public class MainActivity extends AppCompatActivity {

    public static final String BASE_URL = "https://api.some.some/v1/";

    SomeAPI userClient;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    userClient  = retrofit.create(SomeAPI.class);

    login();

    }

    private void login() {
        Auth login = new Auth("123456", "12345678");
        Call<User> call = userClient.login(login);

        call.enqueue(new Callback<User>() {
            @Override
            public void onResponse(Call<User> call, Response<User> response) {
if (response.code() == 201) {
                    Toast.makeText(MainActivity.this, response.body().getToken(), Toast.LENGTH_SHORT).show();
                    token = response.body().getToken();
                }
                else {
                    Toast.makeText(MainActivity.this, "Token is not truth :(", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<User> call, Throwable t) {
                Toast.makeText(MainActivity.this, "error!", Toast.LENGTH_SHORT).show();
            }
        });
    }

    }

Here is my Some API interface:

public interface SomeAPI {

    @POST("token")
    Call<User> login(@Body Auth login);

}
Here is my Auth.java:

public class Auth {
    private String login;
    private String password;

    public Auth(String login, String password) {
        this.login = login;
        this.password = password;
    }
}

Here is my User.java:

    public class User {
        private int id;
        private String email;
        private String token;

        public int getId(){
            return id;
        }

        public void setId(){
            this.id = id;
        }
        public String getEmail(){
            return  email;
        }

        public void setEmail(String email){
            this.email = email;
        }
        public String getToken(){return token;}
        public void setToken(String token){this.token = token;}
public String getfirst_name()
    {
        return first_name;
    }
    public void setfirst_name(String first_name) {
        this.first_name = first_name;
    }

    }

So after this all I have a token and now I want to get some information in my other activity.

Userprofile.java:

    ProstoTVAPI userClient;

        String first_name = "";

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile);
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();

            userClient  = retrofit.create(ProstoTVAPI.class);

            getUserInfo();
    }
        private void getUserInfo() {
            User user = new User();
            Call<User> call = userClient.getInfo();

            call.enqueue(new Callback<User>() {
                @Override
                public void onResponse(Call<User> call, Response<User> response) {
                    if (response.code() == 200){
                            first_name = response.body().getfirst_name();
                            tvName.setText(first_name);


                    }
                    else {
                        Toast.makeText(UserProfile.this, "First name was not loaded", Toast.LENGTH_SHORT).show();

                    }
                }

                @Override
                public void onFailure(Call<User> call, Throwable t) {
                    Toast.makeText(UserProfile.this, "error!", Toast.LENGTH_SHORT).show();
                }
            });
        }

I must send token which I have got after authorization to get new information, for example first_name = response.body().getfirst_name();

How I can do It from this activity? What I need to change/add in my code?

UPD:

I have created PreferencesManager where I am saving my prefs:

public class PreferencesManager {

    private static final String PREFERENCES = "MyPrefs";
    private static PreferencesManager instance = null;
    private static SharedPreferences sharedPreferences;

    public static PreferencesManager getInstance() {
        if (instance == null) {
            instance = new PreferencesManager();
        }
        return instance;
    }

    private static SharedPreferences getSharedPreferences(Context context) {
        if (sharedPreferences == null) {
            sharedPreferences = context.getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE);
        }
        return sharedPreferences;
    }


    public static void putString(Context context, String key, String value) {
        SharedPreferences sharedPreferences = getSharedPreferences(context);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(key, value).apply();
    }

    public static String getString(Context context, String key, String defValue) {
        SharedPreferences sharedPreferences = getSharedPreferences(context);
        return sharedPreferences.getString(key, defValue);
    }


}

So In Activity where I have got token I did: editor.putString("token", token);, where editor - SharedPreferences.Editor editor;

And In Activity where I sending token as a header I did:

    private void getUserInfo() {
            User user = new User();

            Call<User> call = userClient.getInfo("Bearer " + token);
...
}

and in onCreate():

editor = getSharedPreferences("MyPrefs", MODE_PRIVATE).edit();
token = PreferencesManager.getString(this,"token", null);

also I have added into ApiInterface:

Call<User> getInfo(@Header("Authorization") String token);
danyapd
  • 2,516
  • 1
  • 14
  • 23

2 Answers2

1

i am sending token in header this way:-

this is ApiInterface class:-

Call<ReactionResponse> submitReactionPart(@Header("Authorization") String token);

and this is activity:-

Call<ReactionResponse> responseCall = apiInterface.submitReactionPart("Bearer " +token);

this is my preference claas have a look:-

    public class AppPrefrences {

        private static SharedPreferences mPrefs;
        private static SharedPreferences.Editor mPrefsEditor;

        public static boolean isUserLoggedOut(Context ctx) {
            mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
            return mPrefs.getBoolean("id_logged_in", true);
        }

        public static void setUserLoggedOut(Context ctx, Boolean value) {
            mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
            mPrefsEditor = mPrefs.edit();
            mPrefsEditor.putBoolean("id_logged_in", value);
            mPrefsEditor.commit();
        }

    public static String getUserImage(Context ctx) {
        mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
        return mPrefs.getString("userImage", "");
    }

    public static void setUserImage(Context ctx, String value) {
        mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
        mPrefsEditor = mPrefs.edit();
        mPrefsEditor.putString("userImage", value);
        mPrefsEditor.commit();
    }

}

in activity where you want to use the preference value, it will return string value:-

String userImageUrl = AppPreference.getUserImage(MyActivity.class);

in activity where you want to store your value in preference :-

AppPreference.setUserImage(MyActivity.class, "put your value here");
Sandeep Malik
  • 1,972
  • 1
  • 8
  • 17
  • if you have any query leave a comment – Sandeep Malik Apr 12 '19 at 06:54
  • How can I get token from another activity? `Activity.token` when token defined like `public static String token` didn't work for me – danyapd Apr 12 '19 at 08:02
  • 1
    save your token in preferences and get where you want this token. – Sandeep Malik Apr 12 '19 at 08:03
  • so simple and genius, how I didn't remember about pref before. I have added `token = PreferencesManager.getString(this,"token", null);` into UserProfile.java `onCreate()` and then everyrhing like you said, but I have got empty token after getting from `SharedPreferences`. I will add my PreferencesManager.class to the question now. – danyapd Apr 12 '19 at 10:01
  • 1
    i am posting my preference class and i think it can help you – Sandeep Malik Apr 12 '19 at 10:07
  • but in your class you have boolean and I must to put and get string - token. my preference class is wrong? – danyapd Apr 12 '19 at 10:13
  • 1
    it is just for reference you can store any type of value you want. ok i am inserting an string type getter and setter – Sandeep Malik Apr 12 '19 at 10:14
  • it is not like mine. how did you use your getters and setters in Activity? – danyapd Apr 12 '19 at 10:57
  • 1
    i added the use of gatter ans setter in my answer. this is very easy to use. – Sandeep Malik Apr 12 '19 at 11:00
1

You can create OkHttpClient interceptor to add token header to all calls:

private static Response intercept(Interceptor.Chain chain) throws IOException
    {
            Request.Builder builder = chain.request().newBuilder()
                    .addHeader("authorization", String.format("%s %s", UserSession.tokenType, UserSession.accessToken));

            return chain.proceed(builder.build());
    }

Then create OkHttpClient instance and add interceptor:

client = new OkHttpClient.Builder()
                    .cache(cache)
                    .addInterceptor(YourClass::intercept)
                    .build();

And finally, build your Retrofit instance:

final Retrofit retrofit =
                new Retrofit.Builder()
                        .baseUrl(baseUrl)
                        .client(client)
                        .addConverterFactory(GsonConverterFactory.create(gson))
                        .build();

As long as your UserSession class holds tokenType and accessToken, authorization header will be added automatically to all calls. You can save your UserSession to shared prefs or keep it in memory.

user1209216
  • 7,404
  • 12
  • 60
  • 123