简体   繁体   English

Rest 保证:如何将 JSON 响应作为字符串返回? (爪哇)

[英]Rest Assured: How do I return JSON response as a String? (Java)

How will I return a JSON response as a String with my code?如何使用我的代码将 JSON 响应作为字符串返回?

Purpose : I want to call getAccessToken() after it has obtained the accessToken from a json response body and need to return it as a String to be used in other methods.目的:我想在getAccessToken()从 json 响应正文中获取 accessToken 后调用它,并且需要将其作为String返回以用于其他方法。

The response example I'm trying to obtain:我试图获得的响应示例:

"accessToken" : "The ID I need from here"

Code:代码:

private String apiAccessToken;

public JsonPath getAccessToken() {
    JsonPath jsonPath = given().header("X-API-KEY", Config.API_KEY).header("session", this.sessionID)
            .header("username", this.userNameId).queryParam("code", verifiedCode).log().all()
            .get(baseUri + basePath + "/vm1/verifyCode").then().log().all().extract().jsonPath();

    this.apiAccessToken = jsonPath.get("accessToken");
    return new JsonPath(apiAccessToken);
}

[ Added - Showing how I'm using solutions from comments below ] [已添加 - 显示我如何使用以下评论中的解决方案]

Example of how I call this method我如何调用此方法的示例

public static String getToken(String key) {
    String res = given()
            .header("X-API-KEY", Config.API_KEY)
            .header("session", this.SessionId)
            .header("username", this.UserName)
            .queryParam("code", verifiedCode)
            .log().all()
            .get(baseUri + basePath + "/vm1 /verifyCode")
            .then()
            .log().all()
            .extract().asString();

    JsonPath js = new JsonPath(res);
    return js.get(key).toString();
}

public static String getJsonPath(Response response, String key) {
    String complete = response.asString();
    JsonPath js = new JsonPath(complete);
    return js.get(key).toString();
}

@Test
    public void testAuthValidator() throws InterruptedException, IOException, GeneralSecurityException {
        String sentCode = GmailUtility.getVerificationCode(); // Uses GMAIL API service to to read and get code from email and sends to getAccessToken
        System.out.println(sentCode);
        String Token = getToken("accessToken"); // Validates verification code. Spits out response for accessToken
        System.out.println(validator);
        driver = initializeDriver(); // Invokes Chrome
        driver.get(env.API_Website); // Goes to api website
        AuthApi auth = new AuthApi(driver);
        auth.getAuthorizeButton().click(); // Clicks a text field on webpage
        auth.getValueField().sendKeys("Token " + Token); // Need to call extracted response for the accessToken from getAccessToken.

Just write a simple reusable method to extract values using JSONPath and call the method in your code, here's a sample只需编写一个简单的可重用方法来使用 JSONPath 提取值并在代码中调用该方法,这是一个示例

Reusable Method:可重复使用的方法:

public static String getJsonPath(Response response, String key) {
    String complete = response.asString();
    JsonPath js = new JsonPath(complete);
    return js.get(key).toString();
}

Test:测试:

public static void main(String[] args) {

    Response res = given().header("X-API-KEY", Config.API_KEY).header("session", this.sessionID)
            .header("username", this.userNameId).queryParam("code", verifiedCode).log().all()
            .get(baseUri + basePath + "/vm1/verifyCode").then().log().all().extract().response();
    String value = getJsonPath(res, "accessToken");
    
    System.out.println(value);
}

Update:更新:

public static String getToken(String key) {
    String res = given().header("X-API-KEY", Config.API_KEY).header("session", this.SessionId)
            .header("username", this.UserName).queryParam("code", verifiedCode).log().all()
            .get(baseUri + basePath + "/vm1 /verifyCode").then().log().all().extract().asString();
    JsonPath js = new JsonPath(res);
    return js.get(key).toString();
}

@Test
public void testAuthValidator() throws InterruptedException, IOException, GeneralSecurityException {
    String sentCode = GmailUtility.getVerificationCode();
    System.out.println(sentCode);
    String Token = getToken("accessToken");
    System.out.println(Token);
    driver = initializeDriver();
    driver.get(env.API_Website);
    AuthApi auth = new AuthApi(driver);
    auth.getAuthorizeButton().click();
    auth.getValueField().sendKeys("Token " + Token);
}

You can get any value using this您可以使用它获得任何价值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何让 Rest Assured 在我的 REST 响应中返回文本(非加密或流式传输)值? - How do I get Rest Assured to return the text (non-encrypted or streamed) value in my REST response? 如何在json响应中获取数组的大小? 放心API、JAVA - How get size of an array in json response? rest assured API, JAVA 将字符串(Json)转换为可确保保证的响应 - Convert String (Json) to Rest Assured Response Rest 保证在 java 响应中提取 json 响应中的值 - Rest assured extracting values in json response in java response.jsonPath() 元素周围有方括号,如何检索字符串值? Rest 放心 - response.jsonPath() has square brackets around the element, how do I retrieve the string value? Rest Assured 如何验证 Json 中的响应值 Rest Assured - how to validate Json Response value in Rest Assured 放心:json响应的大小 - Rest assured: Size of json response 如何将JSON响应转换为Java列表-使用Rest Assure确保进行API测试 - How to convert JSON response to Java List- Using Rest Assured for API Testing 不解析 JSON 文档以返回访问令牌变量 - Rest Assured / Java - Not parsing JSON document to return access token variable - Rest Assured / Java 如何使用带有JSON响应的Rest Assured声明基于正文项? - How to assert based on body item with Rest Assured with JSON response?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM