繁体   English   中英

使用带有 JSON 标头的 selenium 的 POST API 自动化

[英]POST API automation using selenium with JSON Header

我想使用 selenium(java) 自动化 REST API,这可能吗? 如果它有 json 形式的标题和正文部分

在 Java 中,您可以使用 ApacheHttpClient 例如从https://www.mkyong.com/java/apache-httpclient-examples/ lerned

例如 ApacheHttpClientPost 中的一个方法可能是这样的:

public static String post(String tokenMobile, String method, String version, String body) throws Exception{

    try {
        HttpClient httpClient = HttpClientBuilder.create().build();

        URIBuilder builder = new URIBuilder();
        builder.setScheme("https").setHost(host).setPath(method)
                   .setParameter("", ""); //Params
        URI uri = builder.build();
        HttpGet httpget = new HttpGet(uri);

        HttpPost postRequest = new HttpPost(httpget.getURI()); //Header
        postRequest.addHeader("Content-Type", "application/json");
        postRequest.addHeader("version", version);
        postRequest.addHeader("Authorization", "Bearer "+tokenMobile);

        StringEntity input = new StringEntity(body); //Body in json
        input.setContentType("application/json");
        postRequest.setEntity(input);
        HttpResponse response = httpClient.execute(postRequest);
        BufferedReader br = new BufferedReader(
                new InputStreamReader((response.getEntity().getContent())));
        String output;
        while ((output = br.readLine()) != null) {
            StringBuilder stringBuilder = new StringBuilder();
            outputs = stringBuilder.append(output).toString();
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return outputs;
}

Selenium 是一种设计用于 UI 或 e2e 测试用例自动化的工具。 您可以将 Selenium 测试用例与 API 测试用例集成,但这总是一个坏主意。

如果您想自动化 API 测试用例Rest-Assured, Postman, HTTPClient请尝试使用Rest-Assured, Postman, HTTPClient

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM