带 CookieManager 的 HttpURLConnection 是否应该自动处理会话 cookie? [英] Should HttpURLConnection with CookieManager automatically handle session cookies?

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

问题描述

我有一个 Java 应用程序 (JDK 1.7.0_13),正在使用 java.net.HttpURLConnection 连接到一些基于 servlet 的服务,这些服务进行会话管理.我想弄清楚如何使用 java.net.CookieManager 来跟踪会话 cookie.阅读文档我的印象是,使用 CookieHandler.setDefault(new CookieManager()) 安装 CookieManager 应该会导致 cookie 管理自动发生.但是,对同一 URL 的多个请求似乎不会保留 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 自动为我工作,或者我是否必须求助于从响应中手动提取 cookie 并通过请求重新发送它们?

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?

推荐答案

我运行你的代码并替换这个

I run your code and replace this

CookieHandler.setDefault(new CookieManager()); 

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

它起作用了!

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

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