Java类CookieHandler和CookieManager如何工作?

时间:2015-04-26 04:22:44

标签: java httpsurlconnection cookiemanager

我可以使用CookieHandler.setDefault(new CookieManager);以编程方式登录任何网址的唯一方法。哪个没问题,但我想了解每个新HttpsURLConnection之间如何维护cookie。

有人可以说明如何让以下代码登录到Gmail帐户而不必使用CookieHandler.setDefault(new CookieManager);吗?感谢。

**注:
- 用您自己的电子邮件和密码替换 - CookieHandler.setDefault(new CookieManager);已在下面的代码中注释掉。

public class GmailApp {

    private List<String> cookies;
    private HttpsURLConnection conn;

    public static void main(String[] args) throws Exception {

        String url = "https://accounts.google.com/ServiceLoginAuth";
        String gmail = "https://mail.google.com/mail/";

        GmailApp http = new GmailApp();

        // CookieHandler.setDefault(new CookieManager());

        String page = http.GetPageContent(url);
        String postParams = http.getFormParams(page, "myemail@gmail.com", "mypassword");
        http.sendPost(url, postParams);

        String result = http.GetPageContent(gmail);
        System.out.println(result);
    }

    private void sendPost(String url, String postParams) throws Exception {

        URL obj = new URL(url);
        conn = (HttpsURLConnection) obj.openConnection();
        conn.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(postParams);
        wr.flush();
        wr.close();

        int responseCode = conn.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + postParams);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in =
                new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
    }

    private String GetPageContent(String url) throws Exception {

        URL obj = new URL(url);
        conn = (HttpsURLConnection) obj.openConnection();
        conn.setRequestMethod("GET");
        conn.setUseCaches(false);
        if (cookies != null) {
            for (String cookie : this.cookies) {
                conn.addRequestProperty("Cookie", cookie.split(";", 1)[0]);
            }
        }
        int responseCode = conn.getResponseCode();
        System.out.println("\nSending 'GET' request to URL : " + url);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in =
                new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        setCookies(conn.getHeaderFields().get("Set-Cookie"));
        return response.toString();
    }

    public String getFormParams(String html, String username, String password)
            throws UnsupportedEncodingException {

        System.out.println("Extracting form's data...");

        Document doc = Jsoup.parse(html);

        Element loginform = doc.getElementById("gaia_loginform");
        Elements inputElements = loginform.getElementsByTag("input");
        List<String> paramList = new ArrayList<String>();
        for (Element inputElement : inputElements) {
            String key = inputElement.attr("name");
            String value = inputElement.attr("value");

            if (key.equals("Email"))
                value = username;
            else if (key.equals("Passwd"))
                value = password;
            paramList.add(key + "=" + URLEncoder.encode(value, "UTF-8"));
        }

        StringBuilder result = new StringBuilder();
        for (String param : paramList) {
            if (result.length() == 0) {
                result.append(param);
            } else {
                result.append("&" + param);
            }
        }
        return result.toString();
    }

    public void setCookies(List<String> cookies) {
        this.cookies = cookies;
    }

} 

1 个答案:

答案 0 :(得分:1)

当您通过CookieHandler静态设置默认java.net.CookieHandler.setDefault()时,当前和未来HttpURLConnection(通过其基础HTTP客户端类)将检查是否存在此默认Cookie处理程序,并且发现它将使用它来检索请求的cookie,并存储设置/返回的新cookie。只要您想在所有请求中维护cookie,这就提供了一个静态cookie-jar。请务必设置所需的CookiePolicy,否则java.net.CookiePolicy.ACCEPT_ORIGINAL_SERVER是默认设置。

请注意您的代码存在一些问题:

cookie.split(";", 1)[0]

如果要从第一个分号开始截断字符串,则此分割不会执行任何操作,您需要cookie.split(";", 2)[0](1-&gt; 2)。

此外,您只在GET请求后调用setCookies - 您还需要在POST登录响应中捕获cookie。