jeudi 23 avril 2020

How to add bearer token to retrofit request in Java

Hi Im trying to add a bearer token to a retrofit call in java, but i cant seem to pass it.

Currently Im logging in with one method and this creates a bearer token and im trying to add the token to the Get Call, but its just returning a 401 error, have I added the token to the call correctly?

@GET("diagnosis/configuration")
Call<ResponseBody> getFavourites (@Query("favourite") Boolean fave,@Header("Bearer Token") String authHeader);

@POST("auth/login")
Call<LoginResponse> postLogin (@Body LoginCredentialsBody body);



public class LoginApiStepDefinition extends TestBaseFix {

Retrofit retrofit = super.buildRetrofit(super.buildOkHttpClient());
RetrofitCallsLogin call = retrofit.create(RetrofitCallsLogin.class);
RetrofitCallsGetFavourites favecall = retrofit.create(RetrofitCallsGetFavourites.class);

private Response<LoginResponse> responseBody;
private String favouritesResponseBody;


String usernameValue;
String passwordValue;

private String token;


@And("I login with {string} and {string} to return login token")
public void iLoginWithAndToReturnLoginToken(String username, String password) throws Exception {

    LoginApi(username, password);

}


public String LoginApi(String username, String password) throws Exception {


    usernameValue = username;
    passwordValue = password;

    //gets fixture ids for the dates
    LoginCredentialsBody login = new LoginCredentialsBody();
    login.setPassword(passwordValue);
    login.setUsername(usernameValue);
    String responseBody = call.postLogin(login).execute().body().toString();
    String requiredString = responseBody.substring(responseBody.indexOf("=") + 1, responseBody.indexOf(","));


    System.out.println(requiredString);


    return token;


}






@Then("I get the list of favourites with {string} and {string}")
public void iGetTheListOfFavouritesWithAnd(String username, String password) throws Exception {

    String favouritesResponseBody = favecall.getFavourites(true, LoginApi(username, password)).execute().body().toString();
    System.out.println(favouritesResponseBody);
}

}

Aucun commentaire:

Enregistrer un commentaire