我正在尝试发送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
}
首先打印所有cookie:
Cookies:[PHPSESSID = 9ohpfb0jmhtdbmgu1lidm8kfcs;路径= /; domain = pfrs-01.testy.hsi.pl]
然后将其子字符串化为PHPSESSID:
9ohpfb0jmhtdbmgu1lidm8kfcs
此后,我需要修改sendGET方法:
String sessionID = getPhpSessionID()
con.setRequestProperty("Cookie", "PHPSESSID=${sessionID}")
结果是:
获取响应代码:: 200
希望它对以后的人有所帮助:)