如何在 java URL 中维护会话



我正在使用java URLConnection登录网站后,尝试登录网站并获取页面网站的页面源代码。我面临的问题是我无法维护会话,因此服务器给了我此警告并且不允许我连接:

此系统需要使用 HTTP cookie 来验证授权信息。 我们的系统检测到您的浏览器已禁用或不支持 HTTP cookie。 有关如何正确配置浏览器以与此系统配合使用的更多信息,请参阅浏览器中的帮助页面。

起初,我

尝试发送空cookie,让服务器了解我正在处理会话,但它也没有给我会话ID。

这是我的源代码:

try {
        // Construct data
        String data = URLEncoder.encode("usr", "UTF-8") + "=" + URLEncoder.encode("usr", "UTF-8");
        data += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode("pass", "UTF-8");
        // Send data
        URL url = new URL("https://loginsite.com");
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestProperty("Cookie", "SESSID=");
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(data);
        wr.flush();
        // Get the response
        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        while ((line = rd.readLine()) != null) {
            System.out.println(line);
        }
        wr.close();
        rd.close();
        String headerName=null;
        for (int i=1; (headerName = conn.getHeaderFieldKey(i))!=null; i++) {
            if (headerName.equals("Set-Cookie")) {
                String cookie = conn.getHeaderField(i);
                System.out.println(cookie.split(";", 2)[0]);
            }
        }
        } catch (Exception e) {
    }

您应该使用HTTP库来处理会话管理和HTTP协议的其他细节,例如支持Cookie和开箱即用的Keep-Alive,代理等东西。尝试 Apache HttpComponents

最新更新