java - 发送 GET 请求后,HttpURLConnection 返回响应代码 500,即使它在本地工作

标签 java selenium httpurlconnection

我正在尝试发送 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
    }

GET Response Code :: 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 header ,具体来说就是 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=2ohpfb3jmhtddcgx1lidm5zwcs; path=/; domain=domain.com]

然后它是 PHPSESSID 的子字符串:

2ohpfb3jmhtddcgx1lidm5zwcs

之后我需要修改我的 sendGET 方法:

String sessionID = getPhpSessionID()
con.setRequestProperty("Cookie", "PHPSESSID=${sessionID}")

结果是:

GET Response Code :: 200

希望它对将来的人有所帮助:)

关于java - 发送 GET 请求后,HttpURLConnection 返回响应代码 500,即使它在本地工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60810225/

相关文章:

java - Swing 应用程序全局模式

java - Servlet session 超时

java - 主线程异常 : Unable to locate an element with the x path expression

java - Selenium xpath 计数

java - 使用 HttpUrlConnection Android 将 base64 编码的图像发送到服务器

android - HttpURLConnection 似乎没有在 Android 上使用缓存

java - 403 拒绝访问 tomcat 7.0.42

java - CalendarView 环绕当前月份的高度

selenium - 无法使用带有docker-compose的Selenium RemoteWebDriver运行Springboot应用程序

Java HTTPUrlConnection 返回 500 状态码