Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
689 views
in Technique[技术] by (71.8m points)

java - 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 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...