I have a java web application that uses form based authentication. If a standard web user hits my site they are redirected to login.jsp, they submit their credentials and then the resource is given to them.
I have a simple java client that needs to post information to my web app on occasion. When my java client posts the information the server sends back login.jsp which I would expect. I can submit a second request to j_security_check with the credentials but any additional request I send still goes through as if I’m unauthenticated.
I know browsers store session information in the headers and transfer that back and froth to the server to help maintain state, but how do I do something similar from a java client so that subsequent requests are authenticated.
This happens because you do not send cookies.
When you turn to server first time it creates session for you. The session has ID. This ID is sent to client as special cookie, e.g. server sends HTTP header
Set-Cookie. Typically java based servers use cookie namedjsessionidbut it actually does not matter. You at client side should get the value of response headerSet-Cookieand send it back using HTTP headerCookie. In this case server will process your second and third (etc.) requests in context of the same session. Your second request (post of the login form) makes session authenticated, so you will not be redirected to the login form again and again.If you can configure the server side, you can do it easier. The server should be configured to support basic authentication too (additionally to form based authentication). So, your client can send header
Authorizationwith valueBasic USER:PASSWORDwhere USER & PASSWORD should be sent in Base64 form.
EDIT: you can use Jakarta HttpClient. It simplifies everything when you are dealing with HTTP. But standard Java
HttpURLConnectioncan do the job too.