Java提取URL某个参数的值

Java提取URL某个参数的值

public static String getParam(String url, String name) {
    String params = url.substring(url.indexOf("?") + 1, url.length());
    Map<String, String> split = Splitter.on("&").withKeyValueSeparator("=").split(params);
    return split.get(name);
}

本文转载自博客园文章:Java提取URL某个参数的值

Java接口自动化可以使用Rest Assured和Apache HttpClient等库进行实现,其涉及到的主要步骤如下: 1. 使用Excel读取测试数据,将请求参数存储在一个Map; 2. 发送第一个接口请求获取响应数据,并解析出需要的参数; 3. 将第一个接口返回的参数填充到第二个接口请求参数; 4. 发送第二个接口请求获取响应数据; 5. 将响应数据与预期结果进行比对,输出测试结果。 下面是一个简单的代码示例: ```java public class ApiTest { private static final String BASE_URL = "http://api.example.com"; private static final String TEST_DATA_FILE = "test_data.xlsx"; @Test public void testApi() throws Exception { // 读取测试数据 List<Map<String, String>> testData = readTestData(TEST_DATA_FILE); // 发送第一个接口请求 Map<String, String> requestBody1 = testData.get(0); String response1 = sendRequest(BASE_URL + "/api1", requestBody1); // 解析第一个接口返回的参数 String param = extractParam(response1); // 将第一个接口返回的参数填充到第二个接口请求参数 Map<String, String> requestBody2 = testData.get(1); requestBody2.put("param", param); // 发送第二个接口请求 String response2 = sendRequest(BASE_URL + "/api2", requestBody2); // 比对响应数据和预期结果 String expectedResponse = testData.get(1).get("expected_response"); Assert.assertEquals(expectedResponse, response2); } private List<Map<String, String>> readTestData(String testDataFile) throws Exception { List<Map<String, String>> testData = new ArrayList<>(); FileInputStream file = new FileInputStream(new File(testDataFile)); XSSFWorkbook workbook = new XSSFWorkbook(file); XSSFSheet sheet = workbook.getSheetAt(0); for (int i = 1; i <= sheet.getLastRowNum(); i++) { XSSFRow row = sheet.getRow(i); Map<String, String> data = new HashMap<>(); for (int j = 0; j < row.getLastCellNum(); j++) { XSSFCell cell = row.getCell(j); data.put(sheet.getRow(0).getCell(j).getStringCellValue(), cell.getStringCellValue()); } testData.add(data); } workbook.close(); file.close(); return testData; } private String sendRequest(String url, Map<String, String> requestBody) throws Exception { HttpClient client = HttpClientBuilder.create().build(); HttpPost post = new HttpPost(url); post.addHeader("Content-Type", "application/json"); post.setEntity(new StringEntity(new Gson().toJson(requestBody))); HttpResponse response = client.execute(post); return EntityUtils.toString(response.getEntity()); } private String extractParam(String response) { // 解析返回数据,获取需要的参数 return "param_value"; } } ``` 以上示例,readTestData()方法用于读取测试数据,sendRequest()方法用于发送HTTP POST请求,extractParam()方法用于解析第一个接口返回的参数。测试用例包含了一个简单的测试步骤,即发送两个接口请求,并比对第二个接口的响应数据与预期结果。
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值