简体   繁体   中英

How to maintain sessions in java URLConnection?

I am trying to login to a website and get page source of a page site after I login to the web site with java URLConnection. The problem I am facing is I can't maintain session so server gives me this warning and doesn't let me to get connected:

This system requires the use of HTTP cookies to verify authorization information. Our system has detected that your browser has disabled HTTP cookies, or does not support them. Please refer to the Help page in your browser for more information on how to correctly configure your browser for use with this system.

At first I am trying to send empty cookie to let server to understand I am handling sessions but it doesn't give me session id either.

This is my source code:

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) {
    }

You should use an HTTP library which handles session management and other details of the HTTP protocol for you, eg supports Cookies and things like Keep-Alive, Proxies etc. out of the box. Try Apache HttpComponents

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM