0

In my application, I connect to a server and have to get a successful response to my further working, after such type of response, in general, I get two tokens ( access+refresh). For my further actions, I have to use my access token because I won't be able to get data. This token, in general, expires in 30 minutes. I can't understand how I can get a new token from the server without fails of my application. I had seen some questions and this Refreshing OAuth token using Retrofit without modifying all calls one was the best I think. But I can't understand the way of using it for me. Right now I am using such an interface:

public interface APIService {
    @Headers("Content-type: application/json")
    @POST("/v1/login")
    Call<Post> auth(@Body Post body);

    @Headers({"Content-type: application/json",
            "Authorization: Bearer access_token"})
    @GET("/v1/message/list")
    Call<Message> getInMess(@Query("type") int type, @Query("offset") int offset);
}

there I have to insert my access token by hands.

And then in my MainActivity Class I initialize my interface:

public void sendPost() 
    {
        final EditText titleEt = findViewById(R.id.login);
        final EditText bodyEt = findViewById(R.id.password);
        final String a = titleEt.getText().toString().trim();
        final String b = bodyEt.getText().toString().trim();
        saveData();
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://server/")
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        APIService mAPIService = retrofit.create(APIService.class);
        //retrofit.create(APIService.class);

        mAPIService.auth(new Post(a, b)).enqueue(new Callback<Post>() {
            @Override
            public void onResponse(@NonNull Call<Post> call, @NonNull Response<Post> response) {
                if (response.isSuccessful()) {
                    Toast.makeText(LoginActivity.this, "Post submitted to API.", Toast.LENGTH_LONG).show();
                    Intent intent = new Intent(LoginActivity.this, SecondScreen.class);
                    findViewById(R.id.btn_submit).getBackground().setColorFilter(Color.parseColor("#1cd000"), PorterDuff.Mode.MULTIPLY);
                    startActivity(intent);
                } else {
                    Toast.makeText(LoginActivity.this, "Unable to submit post to API.Error!!!", Toast.LENGTH_LONG).show();
                    findViewById(R.id.btn_submit).getBackground().setColorFilter(Color.parseColor("#FF0000"), PorterDuff.Mode.MULTIPLY);
                }
            }

            @Override
            public void onFailure(@NonNull Call<Post> call, @NonNull Throwable t) {
                Toast.makeText(LoginActivity.this, "Unable to submit post to API.", Toast.LENGTH_LONG).show();

            }
        });
    }

Please help me to understand the strategy of my further development because I can't solve my problem.

P.S. Sorry for my bad English))

Aseem Sharma
  • 1,673
  • 12
  • 19
Andrew
  • 1,947
  • 2
  • 23
  • 61

1 Answers1

0

You need to intercept the request and add the header in your interceptor. I use this in my applications :

public class AuthenticationInterceptor implements Interceptor {


    public AuthenticationInterceptor(Context context) {

    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        if(!YOUR_TOKEN.isEmpty()) {
            Request authenticatedRequest = request.newBuilder().header("Authorization", "Bearer:" + YOUR_TOKEN).build();
            return chain.proceed(authenticatedRequest);
        }
        return chain.proceed(request);
    }
}
Flyzzx
  • 458
  • 5
  • 13
  • where I have to insert your code in my mainactivity class and where I can get my token without manual inserting, maybe it my app will get it automatically? – Andrew Jul 26 '18 at 13:00
  • You need to provide your token with your storage method. Personnaly, I use SharedPreferencies – Flyzzx Jul 26 '18 at 13:02
  • but previously I have to parse my json answer with the following token? – Andrew Jul 26 '18 at 13:03
  • The first step is the login. Once you are logged, you have your token that you can save with many different solutions (Local Db, shared preferences, etc...). Then you provide your token to the interceptor who will add the header for each request if the token is present – Flyzzx Jul 26 '18 at 13:04
  • ok it seems that I managed to understood your thoughts, but how I can get this token from json responce? I read about parsing so it sounds like a very useful way of getting data from json (but I don't know how I can do it, so maybe I will explore it) – Andrew Jul 26 '18 at 13:07
  • Yes, you need to parse the json response containing your token, then store it into your app. See https://github.com/google/gson to easily parse Json to Object in Java – Flyzzx Jul 26 '18 at 13:09