Solved

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

Posted on 2003-11-20
10
1,156 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
Resolve Critical IT Incidents Fast

If your data, services or processes become compromised, your organization can suffer damage in just minutes and how fast you communicate during a major IT incident is everything. Learn how to immediately identify incidents & best practices to resolve them quickly and effectively.

 
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

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
hibernate example issues from command prompt 10 50
null output 3 35
jboss wildfly 10.1 10 232
Need help aligning JRadioButton that put in a box using GridBagLayout 2 18
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
This video teaches viewers about errors in exception handling.

839 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