有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何使用REST Assured自动获取承载令牌

我目前正在使用Postman生成无记名令牌,我正在自动测试中使用该令牌。现在,我还想使用Java中的REST Assured自动化承载令牌生成过程。请帮帮我。谢谢

enter image description here

Response response =
      given()
          .auth()
          .oauth(
              "n0pCrq5SPgraZ3CyY0Nd",
              "xvvx-LVd5dszLi9OO_1qjbU4eUQ4dXwLrDZN7oioSITr_EXrgsyyOvPvZmv85Ew2",
              "",
              "",
                  "HMAC-SHA256")
          .when()
          .get(url)
          .then()
          .contentType(ContentType.JSON)
          .extract()
          .response();

共 (1) 个答案

  1. # 1 楼答案

    这很有效。谢谢@wilfred clement

    public static String getOauthToken(String consumerKey, String consumerSecret, String endpoint ) {
    
    log.info("GET ACCESS TOKEN=" + endpoint);
    URI uri = null;
    try {
      uri = new URI(endpoint);
    } catch (URISyntaxException e) {
      log.error("Not proper oauth url=" + endpoint);
      throw new RuntimeException(e);
    }
    
    ValidatableResponse res = given()
            .header("Content-Type", "application/json")
            .auth().oauth(consumerKey,
                    consumerSecret,
                    "",
                    "")
            .body("{\"grantType\": \"client_credentials\"}").when().post(uri).then();
    
    int responseCode = res.extract().statusCode();
    
    if (HttpURLConnection.HTTP_OK == responseCode) {
      String token = res.extract().jsonPath().get("accessToken").toString();
      log.info("Auth token=" + token);
      return token;
    } else {
      String msg = "Access token retrieve failed. Http response code=" + responseCode;
      log.error(msg);
      throw new RuntimeException(msg);
    }
    

    }