Solved

Is it possible to sent a post request instead of a get in a servlet

Posted on 2003-11-20
10
1,152 Views
Last Modified: 2013-11-24
I'm using form-based authentication and a servlet to redirect to "j_security_check".  Is it possible to do a "post" to j_security_check, rather than a sendRedirect?

Here's my code that works (but displays password in the browser's address bar):

        StringBuffer url = new StringBuffer(100);
            url.append(request.getContextPath() + "/" + authURL);
            url.append("?j_username=" + username);
            url.append("&j_password=" + encryptedPassword);

        if (redirectString == null) {
            // signifies already correct protocol
            if (log.isDebugEnabled()) {
                log.debug("Authenticating user '" + username + "'");
            }

            response.sendRedirect(response.encodeRedirectURL(url.toString()));
        }
0
Comment
Question by:mraible
  • 3
  • 2
  • 2
  • +2
10 Comments
 
LVL 3

Expert Comment

by:applekanna
ID: 9791248
yes you can but u need to keep of track of sessions too...

   PrintWriter out = response.getWriter();

    out.println("<html>");
    out.println("<head><title>Your page</title></head>");
    out.println("<body>");
    out.println("<form name=form1 method=post action=\"../yourURL or servelt or JSP\">");
    out.println("<input type=hidden name=j_username value="+username+">");
    out.println("<input type=hidden name=j_password value="+encrypyedPassword+">");
    out.println("<script language=\"javascript\">document.form1.submit()</script>");
    out.println("</body></html>");

Hope this helps
Cheers!
0
 
LVL 92

Expert Comment

by:objects
ID: 9792631
Just use URLConnection to send request as a POST.
0
 

Expert Comment

by:williment
ID: 9837613
If you want to simulate a HTTP POST of a form from a web you need to set the content type for the request:

       URL url = new URL(<URL you want );

       //open connection then
       HttpURLConnection connection =  (HttpURLConnection)  url.openConnection();  
       connection.setRequestMethod("POST");
       connection.setRequestProperty("Content-type","application/x-www-form-urlencoded");
     
      //write the form contents as a series of name value pairs separated by &
     //ideally this string should be URL encoded
       OutputStream outstrm = connection.getOutputStream();
       DataOutputStream cDataOutputStream = new DataOutputStream(outstrm);
       cDataOutputStream.writeBytes("FORM_FIELD1=VALUE_1&FORM_FIELD2=VALUE_2");
       cDataOutputStream.flush();
       cDataOutputStream.close();

      //read the results of your form POST
       BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
0
Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

 
LVL 1

Author Comment

by:mraible
ID: 9839101
How do I get it to follow the post and display the results?  
0
 

Expert Comment

by:williment
ID: 9841874
You can simply read the results from the post via the connection and display then out via this servlet. So the output on the browser is the result of "j_security_check"

       
       BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
       int n = 1;
       String line;
       while ((line = in.readLine()) != null && n <=10)
       {
           out.println(line);
           n++;
       }    
      out.close();
0
 
LVL 1

Author Comment

by:mraible
ID: 9842462
williment - I just get a blank page with nothing in it.  I think the problem is that the URLConnection probably isn't the same thing as a client connection.  The "j_security_check" is a servlet that containers (i.e. Tomcat) must implement for form-based authentication in servlets.  When using a response.sendRedirect(), the request goes back to the client and seems (to the container) the same as having <form action="j_security_check">.  I'm trying to take a form that has the action of my servlet (rather than "j_security_check") and encrypt the password, then forward to the container for authentication.  Forwarding doesn't work, posting (using the above code) doesn't work - only redirect works.  The problem is that the username and password will show up in access logs on the webserver.

More about form-based authentication at http://www.onjava.com/pub/a/onjava/2001/08/06/webform.html?page=2.
0
 
LVL 1

Author Comment

by:mraible
ID: 9843573
I got this working using Jakarta common's HttpClient.  The code is below.  Is it possible to do this with the native Java API - rather than the HttpClient?  I'll award points to whoever can help me figure that out.

            // Use HttpClient to do a Post
            HttpClient client = new HttpClient();
            client.getHostConfiguration().setHost(request.getServerName(),
                                                  request.getServerPort(),
                                                  request.getScheme());

            PostMethod authPost =
                new PostMethod(request.getContextPath() + "/" + authURL);

            // Prepare login parameters
            NameValuePair user = new NameValuePair("j_username", username);
            NameValuePair pass =
                new NameValuePair("j_password", encryptedPassword);
            authPost.setRequestBody(new NameValuePair[] { user, pass });

            client.executeMethod(authPost);

            // release any connection resources used by the method
            authPost.releaseConnection();

            // Usually a successful form-based login results in a redirect to
            // another url
            int statuscode = authPost.getStatusCode();

            if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY) ||
                    (statuscode == HttpStatus.SC_MOVED_PERMANENTLY) ||
                    (statuscode == HttpStatus.SC_SEE_OTHER) ||
                    (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) {
                Header header = authPost.getResponseHeader("location");

                if (header != null) {
                    String newuri = header.getValue();

                    if ((newuri == null) || (newuri.equals(""))) {
                        newuri = "/";
                    }

                    GetMethod redirect = new GetMethod(newuri);

                    client.executeMethod(redirect);

                    if (newuri.indexOf("jsessionid=") > -1) {
                        String jsessionid =
                            newuri.substring(newuri.indexOf("jsessionid=") +
                                             11, newuri.length());

                        response.addHeader("Set-Cookie",
                                           "JSESSIONID=" + jsessionid +
                                           ";Path=" + request.getContextPath());
                    }

                    response.sendRedirect(newuri);
                }
            }
0
 
LVL 92

Expert Comment

by:objects
ID: 9843819
If you call setDoOutput(true); on your URLConnection it should automaticall perform a post.
Example of using POST at:
http://java.sun.com/docs/books/tutorial/networking/urls/readingWriting.html

0
 
LVL 1

Accepted Solution

by:
DarthMod earned 0 total points
ID: 11688315
Submitted to PAQ with points refunded (150)

DarthMod
Community Support Moderator
0

Featured Post

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Java Timer (static) 9 44
Java Options in Zimbra Server 2 54
javap bin 2 34
Java Restore security prompts not working 10 13
Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

809 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question