gpt4 book ai didi

selenium - 如何使用 Selenium 2 发送 http RequestHeader?

转载 作者:行者123 更新时间:2023-12-03 22:22:01 25 4
gpt4 key购买 nike

我需要发送一个带有一些修改过的 header 的 Http 请求。几个小时后试图找到与 Selenium RC 等效的方法 Selenium.addCustomRequestHeader对于 Selenium 2,我放弃并使用 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);
}
}

我的测试程序

// ...

@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 - 如何使用 Selenium 2 发送 http RequestHeader?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6478672/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com