如何在applet中设置cookie?

时间:2015-03-20 08:56:48

标签: java cookies applet

此代码存在问题。当我向JSP发送applet请求并在JSP上获取cookie时,然后向服务器发送请求,然后在服务器上不启用cookie。

public class Helloworld extends Applet {

String ip;

public void init(){

 resize(350,350);
 int Port = 0;
 try
    {
        if(getDocumentBase().getPort()!=-1){
        Port=getDocumentBase().getPort();
        }
    else
    {
        Port=80;
    }
        Socket socket = new Socket(getDocumentBase().getHost(), Port);
        ip = socket.getLocalAddress().getHostAddress();
       }
       catch(IOException io)
       {
       System.out.println(io.getMessage());
    }
}
  public void paint(Graphics g){
       StringBuffer sb = new StringBuffer()
       .append(" IP address : ").append(ip);
       g.drawString(sb.toString(), 50,100);
}
  public void setCookieUsingCookieHandler() {
      try {
            CookieManager manager = new CookieManager();
            manager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
            CookieHandler.setDefault(manager);
            URL url = new URL("http://LocalHost8081");
           // URL url = applet.getCodeBase();


            URLConnection connection = url.openConnection();
            connection.getContent();

            // get cookies from underlying CookieStore
            CookieStore cookieJar = manager.getCookieStore();
            java.util.List<HttpCookie>  cookies = cookieJar.getCookies();

            for (HttpCookie cookie: cookies) {
                System.out.println("CookieHandler retrieved cookie: " + cookie);
            }
        } catch(Exception e) {
            System.out.println("Unable to get cookie using CookieHandler");
            e.printStackTrace();
        }
        try {
            // instantiate CookieManager
            CookieManager manager = new CookieManager();
            CookieHandler.setDefault(manager);
            CookieStore cookieJar = manager.getCookieStore();

            //create cookies
            HttpCookie cookie = new HttpCookie("IpAddress", "ip");
            //URL connection
            URL url = new URL("http://LocalHost8081");
            //URL url = applet.getCodeBase();
            //cookie jar
            cookieJar.add(url.toURI(), cookie);
            System.out.println("Added cookie using cookie handler");
        } catch(Exception e) {
 System.out.println("Unable to set cookieusingCookieHandler");
            e.printStackTrace();
        }
}
}

0 个答案:

没有答案