如何使用Selenium 2发送http RequestHeader?

我需要发送带有一些修改后的标头的Http请求。在尝试寻找与Selenium.addCustomRequestHeaderSelenium 2

的Selenium RC等效的方法几个小时后,我放弃了JavaScript并将其用于我的目的。我期望这会容易得多!

有人知道更好的方法吗?

这是我所做的:

javascript.js

var test = {

"sendHttpHeaders": function(dst, header1Name, header1Val, header2Name, header2Val) {

var http = new XMLHttpRequest();

http.open("GET", dst, "false");

http.setRequestHeader(header1Name,header1Val);

http.setRequestHeader(header2Name,header2Val);

http.send(null);

}

}

MyTest.java

// ...

@Test

public void testFirstLogin() throws Exception {

WebDriver driver = new FirefoxDriver();

String url = System.getProperty(Constants.URL_PROPERTY_NAME);

driver.get(url);

// Using javascript to send http headers

String scriptResource = this.getClass().getPackage().getName()

.replace(".", "/") + "/javascript.js";

String script = getFromResource(scriptResource)

+ "test.sendHttpHeaders(\"" + url + "\", \"" + h1Name

+ "\", \"" + h1Val + "\", \"" + h2Name + "\", \"" + h2Val + "\");";

LOG.debug("script: " + script);

((JavascriptExecutor)driver).executeScript(loginScript);

// ...

}

// I don't like mixing js with my code. I've written this utility method to get

// the js from the classpath

/**

* @param src name of a resource that must be available from the classpath

* @return new string with the contents of the resource

* @throws IOException if resource not found

*/

public static String getFromResource(String src) throws IOException {

InputStream is = Thread.currentThread().getContextClassLoader().

getResourceAsStream(src);

if (null == is) {

throw new IOException("Resource " + src + " not found.");

}

InputStreamReader isr = new InputStreamReader(is);

BufferedReader br = new BufferedReader(isr);

StringWriter sw = new StringWriter();

PrintWriter pw = new PrintWriter(sw);

String line = null;

int nLines = 0;

while (null != (line = br.readLine())) {

pw.println(line);

nLines ++;

}

LOG.info("Resource " + src + " successfully copied into String (" + nLines + " lines copied).");

return sw.toString();

}

// ...

注意:为了简化本文,我已经编辑了原始代码。希望我没有介绍任何错误!

回答:

不幸的是,您无法使用Selenium 2更改标头。这是团队方面的明智决定,因为我们正在尝试创建一个模拟用户可以执行的浏览器自动化框架。

以上是 如何使用Selenium 2发送http RequestHeader? 的全部内容, 来源链接: utcz.com/qa/423871.html

回到顶部