接口自动化如何自定义工具类
时间: 2024-03-06 21:39:21 浏览: 65
Python接口自动化-简单总结
在接口自动化中,自定义工具类可以提高代码复用性和可维护性。下面是一个自定义工具类的示例:
```java
public class HttpUtils {
private static final Logger logger = LoggerFactory.getLogger(HttpUtils.class);
/**
* 发送 GET 请求
* @param url 请求 URL
* @param params 请求参数
* @return 响应内容
*/
public static String sendGet(String url, Map<String, String> params) {
String result = "";
try {
// 构造请求参数
StringBuilder paramsStr = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
paramsStr.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), "UTF-8")).append("&");
}
if (paramsStr.length() > 0) {
paramsStr.deleteCharAt(paramsStr.length() - 1);
}
String fullUrl = url + "?" + paramsStr.toString();
// 发送请求
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(fullUrl);
CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
// 处理响应
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
result = EntityUtils.toString(entity);
}
EntityUtils.consume(entity);
httpResponse.close();
httpClient.close();
} catch (Exception e) {
logger.error("Failed to send GET request: {}", e.getMessage());
}
return result;
}
/**
* 发送 POST 请求
* @param url 请求 URL
* @param params 请求参数
* @return 响应内容
*/
public static String sendPost(String url, Map<String, String> params) {
String result = "";
try {
// 构造请求参数
List<NameValuePair> paramList = new ArrayList<>();
for (Map.Entry<String, String> entry : params.entrySet()) {
paramList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
// 发送请求
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(paramList, "UTF-8"));
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
// 处理响应
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
result = EntityUtils.toString(entity);
}
EntityUtils.consume(entity);
httpResponse.close();
httpClient.close();
} catch (Exception e) {
logger.error("Failed to send POST request: {}", e.getMessage());
}
return result;
}
}
```
该工具类实现了发送 GET 和 POST 请求的方法,可以通过传入 URL 和参数来发送请求,并返回响应内容。使用时,只需要在测试代码中调用该方法即可:
```java
Map<String, String> params = new HashMap<>();
params.put("key1", "value1");
params.put("key2", "value2");
String result = HttpUtils.sendGet("http://example.com/api", params);
System.out.println(result);
```
这样,就可以实现接口自动化测试中的 HTTP 请求部分的代码复用,提高代码的可维护性和可读性。
阅读全文