如何在 Java 中向改造请求添加不记名令牌

Fea*_*lQA 4 java testing cucumber web-api-testing retrofit2

嗨,我正在尝试向 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);
}
Run Code Online (Sandbox Code Playgroud)

}

在此处输入图片说明

小智 10

要在改造中添加不记名令牌,您必须创建一个实现的类 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

现在在 OKHttpClient 对象中添加您的 Interceptor 类并在 Retrofit 对象中添加该对象:

TokenInterceptor interceptor=new TokenInterceptor();

OkHttpClient client = new OkHttpClient.Builder()
            .addInterceptor(interceptor).
            .build();

Retrofit retrofit = new Retrofit.Builder()
            .client(client)
            .baseUrl("add your url here")
            .addConverterFactory(JacksonConverterFactory.create())
            .build();
Run Code Online (Sandbox Code Playgroud)