我正在尝试发送 HTTP GET 请求以从服务器下载文件,作为 Selenium 测试用例的一部分。
如果我通过任何浏览器在本地执行它,它会工作并返回 HTTP OK 200,并且文件被下载,但是当我尝试使用HttpURLConnection
类发送任务时它不会。
我正在使用的方法:
static sendGET(String URL){
URL obj = new URL(URL)
CookieHandler.setDefault(new CookieManager())
Authenticator.setDefault (new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication ("login", "password".toCharArray());
}
})
HttpURLConnection con = (HttpURLConnection) obj.openConnection()
HttpURLConnection.setFollowRedirects(true)
con.setRequestMethod("GET")
con.setRequestProperty("User-Agent", "Mozilla/5.0")
int responseCode = con.getResponseCode()
System.out.println("GET Response Code :: " + responseCode)
return responseCode
}
获取响应代码 :: 500
从服务器日志我得到:
CRITICAL 08:51:39 php Call to a member function getId() on null
{
"exception": {}
}
调用 getId() 的行:@AndiCover
$response = $transmitter->downloadFile($fileID, $this->getUser()->getId());
这使得用户身份验证似乎存在问题。
我也尝试使用 HttpGet 类,但结果是一样的。
发现一个问题,就这样吧。
那么,问题是什么?结果我的请求缺少可以验证用户身份的 Cookie 标头,具体来说它是 PHPSESSID。为了获取当前的 PHPSESSID,我创建了一个方法来检索所有 cookie,然后将 PHPSESSID 子字符串化:
static getPhpSessionID(){
String cookies = driver.manage().getCookies()
System.out.println("Cookies: ${cookies}")
cookies = cookies.substring(cookies.lastIndexOf("PHPSESSID=") + 10)
cookies = cookies.substring(0, cookies.indexOf(";"))
System.out.println("${cookies}")
return cookies
}
首先它打印所有的cookies:
Cookies: [PHPSESSID=2ohpfb3jmhtddcgx1lidm5zwcs; 路径=/;域=域.com]
然后它子字符串 PHPSESSID:
2ohpfb3jmhtddcgx1lidm5zwcs
之后,我需要修改我的 sendGET 方法:
String sessionID = getPhpSessionID()
con.setRequestProperty("Cookie", "PHPSESSID=${sessionID}")
结果是:
获取响应代码 :: 200
希望它可以帮助未来的人:)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句