应该HttpURLConnection与CookieManager自动处理会话cookie吗? [英] Should HttpURLConnection with CookieManager automatically handle session cookies?

查看:219
本文介绍了应该HttpURLConnection与CookieManager自动处理会话cookie吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Java应用程序(JDK 1.7.0_13),并使用java.net.HttpURLConnection连接到一些基于servlet的服务,进行会话管理。我试图找出如何使用java.net.CookieManager跟踪会话cookie。阅读文档我得到的印象是,使用CookieHandler.setDefault(新的CookieManager())安装CookieManager应该会导致cookie管理自动发生。但是,对同一网址的多个请求似乎不保留Cookie。我必须手动从响应中提取Cookie,并在我自己的请求中重新发送它们,还是CookieManager会自动为我执行此操作?如果CookieManager没有,那么它添加什么值?

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. I am trying to figure out how to use java.net.CookieManager to track session cookies. Reading the docs I get the impression that installing CookieManager with CookieHandler.setDefault(new CookieManager()) should cause cookie management to happen automatically. However, multiple requests to the same URL's does not seem to preserve cookies. 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? If CookieManager doesn't, then what value does it add?

为了测试,我有一个servlet,每当我的浏览器访问一个URL成功增加一个计数器。这工作正常从Safari,FireFox和Chrome ...但是,我不能让它工作从一个独立的Java应用程序。

To test things, I have a servlet that successfully increments a counter each time my browser visits a URL. This works fine from Safari, FireFox, and Chrome... However, I can't get it to work from a standalone Java application.

这是一个非常简单的测试程序以说明我所希望的简单工作。它在开始时安装CookieManager,然后在控制台中输入URL时重复调用fetch(String urlString)方法。

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.

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

}

servlet从这个应用程序清楚地获取从服务器的会话cookie。但是,再次调用会获取新的会话Cookie。

Invoking my servlet from this app clearly gets a session cookie back from the server. However, invoking again gets a new session 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-----

所以,总之,我必须做别的事情使CookieManager为我自动工作,或者我必须诉诸手动提取cookies

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?

推荐答案

我运行你的代码并替换

CookieHandler.setDefault(new CookieManager()); 

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

可以工作!

这篇关于应该HttpURLConnection与CookieManager自动处理会话cookie吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆