Java新手求教:从API响应提取accountId转为int变量并复用
Java提取API响应JSON数据并复用至自动化登录
完全可以从API响应中提取数据,针对你给出的JSON格式,下面是具体实现步骤:
1. 引入JSON解析依赖
Java本身没有内置JSON解析工具,推荐用Jackson(常用且易上手)。如果用Maven管理项目,在pom.xml中添加以下依赖:
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.15.2</version> <!-- 可替换为最新稳定版 --> </dependency>
2. 编写API调用与数据提取方法
封装一个工具方法,负责调用生成账号的API、解析响应并返回int类型的accountId:
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import java.util.Scanner; public class ApiUtils { public static int getGeneratedAccountId() throws IOException { // 替换为实际的生成账号API地址 URL apiUrl = new URL("https://your-api-endpoint/generate-account"); HttpURLConnection connection = (HttpURLConnection) apiUrl.openConnection(); connection.setRequestMethod("GET"); // 若API要求POST,可改为POST connection.connect(); // 读取API响应内容 Scanner scanner = new Scanner(apiUrl.openStream()); String responseJson = scanner.useDelimiter("\\A").next(); scanner.close(); // 解析JSON并提取accountId ObjectMapper objectMapper = new ObjectMapper(); JsonNode rootNode = objectMapper.readTree(responseJson); String accountIdStr = rootNode.get("accountId").asText(); // 转换为int类型返回 return Integer.parseInt(accountIdStr); } }
3. 在自动化测试中复用提取的数据
修改你的failedAuthorization测试类,添加测试方法,调用工具类拿到accountId后,填入登录页面的账号输入框:
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.io.IOException; import java.util.concurrent.TimeUnit; public class failedAuthorization { WebDriver driver; @BeforeMethod public void setup() { System.setProperty("webdriver.chrome.driver","C:\\Users\\imagineName.imagineSurname\\chromedriver\\chromedriver.exe"); driver=new ChromeDriver(); driver.manage().deleteAllCookies(); driver.get("https://login.live.com/"); driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS); } @Test public void testLoginWithGeneratedAccount() throws IOException { // 调用API获取生成的accountId int accountId = ApiUtils.getGeneratedAccountId(); // 定位账号输入框并填入accountId(转成字符串) driver.findElement(By.id("username")).sendKeys(String.valueOf(accountId)); // 可继续补充密码输入、登录按钮点击等后续逻辑 // driver.findElement(By.id("password")).sendKeys("your-test-password"); // driver.findElement(By.id("submit-button")).click(); } }
补充提示
- 若API需要请求头(如认证token、Content-Type),可在
connection.connect()前添加:connection.setRequestProperty("Authorization", "Bearer your-token"); - 若API为POST请求,需写入请求体,示例:
connection.setDoOutput(true); OutputStream os = connection.getOutputStream(); os.write("{\"param1\":\"value1\"}".getBytes()); // 替换为实际请求体 os.flush(); os.close(); - 实际测试中可添加try-catch块处理IO异常,避免测试中断
内容的提问来源于stack exchange,提问作者Danny Fenton
相关产品推荐
相关产品推荐

