2

I'm creating a Swing application that connects to a web server, running some servlets (created by myself). On the 1st time a user connects, he get a "playerID" that is saved on his session on the servlets. When I try to make another call from the Swing application to the servlet, the "PlyaerID" seems not to be recognized. I'm making a simple call to get the PlayerID. The servlets recognize this type of request and send a JSON with the "playerID" and if it is not set (null) than it sends -1. The swing application always getting the "-1" reply from the servlet. I tried running it from a browser and everything was just fine.

Is it possible that my Swing client can not make a request and a session will not be saved on the servlet?

I can tell you for sure that the swing method that communicate with the servlet works well.

Shai
  • 1,093
  • 4
  • 13
  • 20
  • 3
    Cookies are probably not persisted across requests in your client. See http://stackoverflow.com/questions/1455856/cookies-turned-off-with-java-urlconnection on how to do that. – nos Sep 22 '11 at 20:26

1 Answers1

3

The servlet session is backed by a cookie. You basically need to grab all Set-Cookie headers from the response of the first request and then pass the name=value pairs back as Cookie header of the subsequent requests.

It's unclear what HTTP client you're using, but if it's java.net.URLConnection, then you could use the java.net.CookieHandler for this.

// First set the default cookie manager.
CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));

// All the following subsequent URLConnections will use the same cookie manager.
URLConnection connection = new URL(url).openConnection();
// ...

connection = new URL(url).openConnection();
// ...

connection = new URL(url).openConnection();
// ...

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555