java - HttpURLConnection 在发送 GET 请求后返回响应代码 500,即使它在本地工作也是如此
问题描述
我正在尝试发送 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 类,但结果是一样的。
解决方案
发现了一个问题,就这样吧。
Well, what was the issue? Turned out my request lacked a Cookie header that could authenticate the user, and to be specific it was the PHPSESSID. To get the current PHPSESSID I created a method that retrieves all cookies and then substring 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
}
First it prints all the cookies:
Cookies: [PHPSESSID=2ohpfb3jmhtddcgx1lidm5zwcs; path=/; domain=domain.com]
And then it substrings PHPSESSID:
2ohpfb3jmhtddcgx1lidm5zwcs
After that I needed to modify my sendGET method:
String sessionID = getPhpSessionID()
con.setRequestProperty("Cookie", "PHPSESSID=${sessionID}")
And the result was:
GET Response Code :: 200
Hope it helps someone in the future :)
推荐阅读
- python - 无法使用收集 RDD
- python - jsonpickle:如何正确编码和显示重复对象而不是引用?
- mongodb - MongoDB Mongoose - 鉴别器性能
- python-3.x - 用于计算介于 ! 之间的字符的 Python 程序 和 2 ##
- c++ - 具有泛型类的模板
- git - 我应该什么时候使用 git add,在对文件进行更改之前或之后?
- logging - 在 Docker 应用程序中使用 Logback 更改动态日志级别
- javascript - 如何在 javascript 中处理两个 API 调用?
- html - 如何使页脚适合所有屏幕
- twitter - Twitter 应用程序显示代码:89 无效或过期的令牌