Making http calls from swing application to a servlet, session not saved
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开发者_如何学JAVA 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.
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:
- Using java.net.URLConnection to fire and handle HTTP requests - Maintaining the session
- How do servlets work? Instantiation, sessions, shared variables and multithreading
精彩评论