tags:

views:

504

answers:

2

I am a newbie to ICEfaces and i have a requirement where i need to download a document from a given url (http://ipaddress/formexec?objectid=201).

This URL uses a form based authentication that is deployed through ICEFaces.

i tracked the request of this URL and i get the following line:

&ice.submit.partial=false&ice.event.target=loginForm%3Aj_id33&ice.event.captured=loginForm%3Aj_id33

Is there any libraries or code to download the document by successfully passing the username and password.

A: 

Form based auth is not much different from other requests. All you have to do is to submit an a request to the auth form providing required parameters, such as user and password and in some cases additional token that you would have to get from the source page. Then you need to get cookies from the auth response or session id parameter and copy them to your next request that will fetch the data.

Eugene Kuleshov
A: 

You need to extract the jsessionid from the Set-Cookie response header and append it as URL attribute to the subsequent requests as http://example.com/path/page.jsf;jsessionid=XXX.

Here's a kickoff example with help of "plain vanilla" java.net.URLConnection:

// Prepare stuff.
String loginurl = "http://example.com/login";
String username = "itsme";
String password = "youneverguess";
URLConnection connection = null;
InputStream response = null;

// First get jsessionid (do as if you're just opening the login page).
connection = new URL(loginurl).openConnection();
response = connection.getInputStream(); // This will actually send the request.
String cookie = connection.getHeaderField("Set-Cookie");
String jsessionid = cookie.split(";")[0].split("=")[1]; // This assumes JSESSIONID is first field (normal case), you may need to change/finetune it.
String jsessionidurl = ";jsessionid=" + jsessionid;
response.close(); // We're only interested in response header. Ignore the response body.

// Now do login.
String authurl = loginurl + "/j_security_check" + jsessionidurl;
connection = new URL(authurl).openConnection();
connection.setDoOutput(true); // Triggers POST method.
PrintWriter writer = new PrintWriter(new OutputStreamWriter(connection.getOutputStream()));
writer.write("j_username=" + URLEncoder.encode(username, "UTF-8")
          + "&j_password=" + URLEncoder.encode(password, "UTF-8"));
writer.close();
response = connection.getInputStream(); // This will actually send the request.
response.close();

// Now you can do any requests in the restricted area using jsessionid. E.g.
String downloadurl = "http://example.com/download/file.ext" + jsessionidurl;
InputStream download = new URL(downloadurl).openStream();
// ...

To achieve the same with less bloated code, consider Apache Commons HttpComponents Client.

BalusC