Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

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

Posted on 2003-11-20
10
Medium Priority
?
1,191 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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

Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

Question has a verified solution.

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

Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
This video teaches viewers about errors in exception handling.
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…
Suggested Courses

618 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