如何在Java中为更新请求添加承载令牌

问题描述 投票:2回答:1

您好,我试图在Java中的改造调用中添加不记名令牌,但我似乎无法通过它。

当前,我使用一种方法登录,这会创建一个承载令牌,并且我试图将令牌添加到Get Call中,但是它只是返回401错误,我是否已将令牌正确添加到调用中?

@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;


@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);
}

}

enter image description here

您好,我试图在Java中的改造调用中添加不记名令牌,但我似乎无法通过它。目前,我使用一种方法登录,这会创建一个承载令牌,并且我试图将令牌添加到...

java testing cucumber retrofit2 web-api-testing
1个回答
1
投票

要在改造中添加承载令牌,您必须创建一个实现Interceptor的类>

public class TokenInterceptor implements Interceptor{

    @Override
    public Response intercept(Chain chain) throws IOException {

       //rewrite the request to add bearer token
        Request newRequest=chain.request().newBuilder()
                .header("Authorization","Bearer "+ yourtokenvalue)
                .build();

        return chain.proceed(newRequest);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.