简体   繁体   English

如果HttpURLConnection与CookieManager自动处理会话cookie?

[英]Should HttpURLConnection with CookieManager automatically handle session cookies?

I have a Java application (JDK 1.7.0_13) and am using java.net.HttpURLConnection to connect to some servlet based services that do session management. 我有一个Java应用程序(JDK 1.7.0_13),并使用java.net.HttpURLConnection连接到一些基于servlet的服务进行会话管理。 I am trying to figure out how to use java.net.CookieManager to track session cookies. 我试图弄清楚如何使用java.net.CookieManager来跟踪会话cookie。 Reading the docs I get the impression that installing CookieManager with CookieHandler.setDefault(new CookieManager()) should cause cookie management to happen automatically. 阅读文档我得到的印象是,使用CookieHandler.setDefault(新的CookieManager())安装CookieManager会导致cookie管理自动发生。 However, multiple requests to the same URL's does not seem to preserve cookies. 但是,对同一URL的多个请求似乎不保留cookie。 Do I have to manually extract cookies from responses and resend them in requests on my own or is CookieManager going to do this for me automatically? 我是否必须手动从响应中提取cookie并在我自己的请求中重新发送它们,或者CookieManager是否会自动为我执行此操作? If CookieManager doesn't, then what value does it add? 如果CookieManager没有,那么它添加了什么值?

To test things, I have a servlet that successfully increments a counter each time my browser visits a URL. 为了测试一些东西,我有一个servlet,每当我的浏览器访问一个URL时,它都会成功递增一个计数器。 This works fine from Safari, FireFox, and Chrome... However, I can't get it to work from a standalone Java application. 这可以在Safari,FireFox和Chrome中正常工作......但是,我无法从独立的Java应用程序中使用它。

Here's a very simple test program to illustrate what I was hoping would simple work. 这是一个非常简单的测试程序,用于说明我希望简单的工作。 It installs the CookieManager at the start and then calls a fetch(String urlString) method repeatedly as URLs are typed in at the console. 它在开始时安装CookieManager,然后在控制台输入URL时重复调用fetch(String urlString)方法。

package com.brilliant.experimental;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpFetcher {  
    public static void fetch(String urlString) {
        try {
            URL url = new URL(urlString);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            InputStream in = conn.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            int status = conn.getResponseCode();
            System.out.println("Status = " + status);
            String key;
            System.out.println("Headers-------start-----");
            for (int i = 1; (key = conn.getHeaderFieldKey(i)) != null; i++) {
                System.out.println(key + ":" + conn.getHeaderField(i));
            }
            System.out.println("Headers-------end-----");
            System.out.println("Content-------start-----");
            String inputLine;
            while ((inputLine = reader.readLine()) != null) {
                System.out.println(inputLine);
            }
            System.out.println("Content-------end-----");
            in.close();
        } catch (Exception e) {
            System.out.println(e);
        }
    }

    public static void main(String[] args) {
        CookieHandler.setDefault(new CookieManager());

        for (int i = 0; i < args.length; i++) {
            fetch(args[i]);
        }

        InputStreamReader isr = new InputStreamReader(System.in);
        BufferedReader reader = new BufferedReader(isr);
        String prompt = "> ";
        String urlString;
        try {
            for (System.out.print(prompt);
                    (urlString = reader.readLine()) != null; 
                    System.out.print(prompt)) 
            {
                fetch(urlString);
            }
        } catch (IOException ioe) {
            System.out.println(ioe);
        }
    }

}

Invoking my servlet from this app clearly gets a session cookie back from the server. 从这个应用程序调用我的servlet显然从服务器返回一个会话cookie。 However, invoking again gets a new session cookie. 但是,再次调用会获得一个新的会话cookie。

> http://localhost:8080/brilliant/TestServlet
Status = 200
Headers-------start-----
Server:Resin/4.0.34
Cache-Control:private
Set-Cookie:JSESSIONID=aaaMp0uKke4gp9_-nUuZt; path=/
Content-Length:19
Date:Wed, 13 Feb 2013 18:02:31 GMT
Headers-------end-----
Content-------start-----
Session count is 0
Content-------end-----
> http://localhost:8080/brilliant/TestServlet
Status = 200
Headers-------start-----
Server:Resin/4.0.34
Cache-Control:private
Set-Cookie:JSESSIONID=aaaZ-oPaC1I9WdEDoUuZt; path=/
Content-Length:19
Date:Wed, 13 Feb 2013 18:02:33 GMT
Headers-------end-----
Content-------start-----
Session count is 0
Content-------end-----

So, to summarize, do I have to do something else to make CookieManager work automatically for me, or do I have to resort to manually extracting cookies from responses and resending them with requests? 因此,总而言之,我是否必须做其他事情才能让CookieManager自动为我工作,或者我是否必须手动从响应中提取Cookie并使用请求重新发送它们?

I run your code and replace this 我运行你的代码并替换它

CookieHandler.setDefault(new CookieManager()); 

by 通过

CookieHandler.setDefault( new CookieManager( null, CookiePolicy.ACCEPT_ALL ) );

It work! 这行得通!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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