Java applet获取文档cookie?

时间:2011-11-03 21:41:40

标签: java cookies applet

对于我的生活,我无法弄清楚为什么我无法访问applet源文件的cookie。相同的页面,相同的IP地址。当我实际通过Java建立连接时,我看到发送的cookie(在wireshark中),所以我知道它们就在那里。

有没有人有其他方法可以尝试从Java访问文档Cookie?我在互联网上搜索过,除了getRequestProperty()方法之外,似乎找不到任何有用的东西!

我有以下applet代码:

import java.applet.*;
import java.net.*;
import java.util.*;
import java.io.*;
import netscape.javascript.*;

public class test extends Applet {
    public void init() {
    try {
        URL url = new URL("http://10.0.0.5/java/test.html");            
        String inputLine;
        URLConnection conn = url.openConnection();

        System.out.print("Cookies:\n");
        String m = conn.getRequestProperty("Cookie");
        // Returns null :-/
        System.out.println(m);

        // Read page content => works fine... (sends cookie)
        //BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        //while ((inputLine = in.readLine()) != null) 
        //    System.out.println(inputLine);
        //in.close();        
    } catch (Exception e) { 
        System.out.println("Error :(");
        System.out.println(e.getMessage());
    }
    String alert = "alert(document.cookie);";
    JSObject win = (JSObject) JSObject.getWindow(this);
    win.eval(alert);
    }
}

还有办法让JSObject窗口到我的URLConnection吗?否则它会将我设置在当前applet窗口的上下文中......

1 个答案:

答案 0 :(得分:1)

HttpURLConnection.getRequestProperty

仅返回通过addRequestProperty添加的内容,以便在通过connect建立连接时发送。响应标头可能包含Cookie或Set-Cookie标头,可以为您提供有关服务器cookie的一些线索。

要获取Applet页面的cookie:

  1. 1.定义一个javascript函数,如下所示 - 这应该是包含applet的页面的一部分。

    function getDocumentCookies() 
    {
      return document.cookie;
    }
    
  2. 要调用jsobject,例如:

    private String getDocumentCookies()
    {
      JSObject window = (JSObject)JSObject.getWindow(this);
      return window.call ("getDocumentCookies", new String[0]);
    }