如何通过Selenium发送API头请求并获得响应

时间:2015-10-09 07:13:14

标签: java http selenium header testng

我必须通过selenium + TestNG(Java)自动化API。我知道使用selenium代码自动化API并不是一个好习惯,但我仍然需要这样做。

场景 - 有一个登录API,必须发送电子邮件和密码并获得回复(响应代码200)。我们也可以打印响应信息吗?

1 个答案:

答案 0 :(得分:0)

如果你正在使用java,你可以使用相同的JAVA套接字库:

以下是POST API的示例代码:

    URL obj = new URL(url);
    con = (HttpsURLConnection) obj.openConnection();
    // add request header
    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", USER_AGENT);

    String urlParameters = "j_username=" + user + "&j_password=" + pass
            + "";

    // Send post request
    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.flush();
    wr.close();

    responseCode = con.getResponseCode();
    System.out.println("\nSending 'POST' request to URL : " + url);
    System.out.println("Post parameters : " + urlParameters);
    System.out.println("Response Code : " + responseCode);

对于GET API:

obj = new URL(url);
    obj.openConnection();
    con = (HttpsURLConnection) obj.openConnection();

    // optional default is GET
    con.setRequestMethod("GET");
    CookieHandler.setDefault(new CookieManager());

    // add request header
    con.setRequestProperty("User-Agent", USER_AGENT);
    con.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.8l");
    con.setRequestProperty("Accept", "*/*");
    con.setRequestProperty(
            "Cookie",
            "BIGipServerPRODCAN-Default=423078080.2087.0000; __utma=44365112.1659763098.1418886605.1427784911.1441869730.4; __utmc=44365112; __utmz=44365112.1427784911.3.2.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided); JSESSIONID="
                    + cookieValue);

    responseCode = con.getResponseCode();
    System.out.println("\nSending 'GET' request to URL : " + url);
    System.out.println("Response Code : " + responseCode);
    BufferedReader in = new BufferedReader(new InputStreamReader(
            con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    File file = new File(prop.getFilePath() + "//XMLs//" + fileName
            + ".xml");
    file.delete();
    FileWriter fstream = new FileWriter(prop.getFilePath() + "//XMLs//"
            + fileName + ".xml", true);

    BufferedWriter out = new BufferedWriter(fstream);
    while ((inputLine = in.readLine()) != null) {

        out.write(inputLine.toString());
        out.newLine();

        response.append(inputLine);
    }

    in.close();
    out.close();`