Solved

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

Posted on 2003-11-20
10
1,159 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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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

Webinar: Aligning, Automating, Winning

Join Dan Russo, Senior Manager of Operations Intelligence, for an in-depth discussion on how Dealertrack, leading provider of integrated digital solutions for the automotive industry, transformed their DevOps processes to increase collaboration and move with greater velocity.

Question has a verified solution.

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

Suggested Solutions

Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…

733 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