2

I have page like localhost:7001/MyServlet. I am making a http connection request from like below

String url = "http://localhost:7001/MyServlet"
PostMethod method = new PostMethod(url); 
HttpClient client = new HttpClient();

However "MyServlet" is protected by j_security_check. So when I am making my connection , getting redirected to login page.

How to get authenticated and access my url , in one HttpConnection

Note: I use apache common httpclient

import org.apache.commons.httpclient.HttpClient; 
import org.apache.commons.httpclient.methods.PostMethod;
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
Jijoy
  • 12,386
  • 14
  • 41
  • 48

1 Answers1

0

I doubt you can log in and call the server in a single request, unless HTTP BASIC authentication is enabled. While I do not know the details of HTTPClient's API yet, basically you will need to track a session using cookies; POST your login to /j_security_check; then access the servlet. (The same basic process works for /j_acegi_security_check if using ACEGI Security.)

A nasty wrinkle in Tomcat is that just posting right away to /j_security_check gives a 400 "bad request"; its authenticator is rather finicky about state transitions and was clearly not designed with programmatic clients in mind. You need to first access /loginEntry (you can throw away the response other than session cookies); then post your login information to /j_security_check; then follow the resulting redirect (back to /loginEntry I think) which will actually store your new login information; finally post to the desired servlet! NetBeans #5c3cb7fb60fe shows this in action logging in to a Hudson server using Tomcat's container authentication.

Jesse Glick
  • 24,539
  • 10
  • 90
  • 112