如何从一个 API 响应 body(在一个 class 中)提取访问令牌值到另一个 API header(在另一个 class 中)放心码

How to extract accesss token value from one API response body(in one class) into another API header(in another class) in rest assured code

在一个 class 中生成一个令牌 API,这会给出以下响应。

{
    "access_token": "eyJraWQiOiJNR2FOQUtYXC9pa0grNE1wTE9aS05wMGtqbXNOd0lzXC9WXC9EYm1LZ0pZdTZNPSIsImFsZyI6IlJTMjU2In0.eyJzdWIiOiIxYjBtcjc4cHNjMHIyM25nYnJqMml1MnNkNCIsInRva2VuX3VzZSI6ImFjY2VzcyIsInNjb3BlIjoic2dwZi5wcm9kdWN0XC",
 "expires_in": 3600,
    "token_type": "Bearer"
}

然后在另一个 class 中有另一个 Get API ,我想在其中提取此 access_token 中 header 中的值以放心代码。那么如何在另一个 class 中获取该访问令牌值?

public class Get_Service_List {
    
    private Response response;
    String BaseUrl = "https://dev.api.sgf.eus.nt/pro";
    
    
    
    
    
    @Given("Get Service list API")
    public void get_Service_list_API() {
     
        RestAssured.baseURI = BaseUrl;
        
    }

    @When("call the API with valid token and details")
    public void call_the_API_with_valid_token_and_details() {

        response = RestAssured.given()
                .header("Content-Type", "application/json")
                .header("Authorization", "Bearer "+TokenGeneration.accessToken)
                .when()
                .get("/api/protsvc/ser");
    
    }

    @Then("validate the resonse body with list of services")
    public void validate_the_resonse_body_with_list_of_services() {
       
        String response_body = response.getBody().asString();
        System.out.println("response is: " +response_body);
    }

    @Then("validate for 200 status code")
    public void validate_for_status_code() {
      
        int status_code = response.getStatusCode();
        System.out.println("status is: " +status_code);
    
    
    }
}

我不太了解黄瓜的分享状态。下面是从响应中提取 access_token 的方法。

String accessToken = response.jsonPath().getString("access_token");