首页 > 解决方案 > 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 类,但结果是一样的。

标签: javaseleniumhttpurlconnection

解决方案


发现了一个问题,就这样吧。

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 :)


推荐阅读