Como enviar um http RequestHeader usando o Selenium 2?
Eu precisava enviar uma solicitação Http com alguns cabeçalhos modificados. Depois de várias horas tentando encontrar um método equivalente ao do Selenium RCSelenium.addCustomRequestHeader
para o Selenium 2, desisti e usei JavaScript para meus propósitos. Eu esperava que isso fosse muito mais fácil!
lguém conhece um método melho
Isso é o que eu fiz:
javascript.jsvar 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();
}
// ...
Aviso: Para simplificar este post, editei meu código original. Espero não ter introduzido nenhum erro!