What does post mean?

Source: Internet
Author: User
Tags html page int size string back

There is no problem with using get in many applications. However, get requires an environment variable to pass its own data to the CGI program. However, if a get string is too long, some Web servers may run out of their own environment (if the string is longer than 200 characters, you should start to care about this). CGI provides a solution for this: POST. By post, the data can be encoded and linked in the same way as get. But post uses standard input to pass the encoded query string to the CGI program. All we have to do is judge the length of the query string, which has been saved in the environment variable CONTENT_LENGTH. Once you know the length, you can freely allocate the storage space and read the specified number of characters from the standard input.
for a CGI program used to control post, the pair and cgi_vector provided by CGITools.h can be used without any change. The following procedure reveals how simple it is to write a CGI program like this. This example will take the "pure" C + +, so the Studio.h library is replaced by iostream (IO data stream). For iostream, we can use two predefined objects: CIN, used with standard input connections, and cout for connection to standard output. There are several ways to read data from Cin and write to cout. But the following program is prepared to use the standard method of sending information to cout with "<<" and reading the data from CIN using a member function (read ()):

 

//: POSTtest.cpp//Cgi_vector works as easily and POST as it//does with get.
Written in "pure" C + +. #include <iostream.h> #include "CGITools.h" void Main () {cout << "content-type:text/plain\n" << End
  L For a CGI "POST," the server puts the length//of the content string in the environment//variable Content_lengt
  h:char* Clen = getenv ("Content_length");
    if (Clen = = 0) {cout << "Zero content_length" << Endl;
  Return
  int len = atoi (Clen);
  char* query_str = new Char[len + 1];
  Cin.read (Query_str, Len);
  Query_str[len] = ' the ';
  Cgi_vector query (QUERY_STR); Test:dump all names with values for (int i = 0; i < query.size (); i++) cout << "query[" << i <&L T "].name () = [" << query[i].name () << "]," << "query[" << I << "].value () = [" &
  lt;< query[i].value () << "]" << Endl; Delete query_str; Release storage}///:~ 

The


getenv () function returns a pointer to a string that indicates the length of the content. If the pointer is zero, it indicates that the CONTENT_LENGTH environment variable has not been set, so it must be a problem somewhere. Otherwise, you must convert the string to an integer using the ANSI C library function atoi (). This length will be used with new, allocating enough storage space to hold the query string (plus its air stop). The read () is then called for CIN (). The read () function needs to get a pointer to the target buffer and the number of bytes to read. It then terminates the QUERY_STR with a null character (NULL), indicating that it has reached the end of the string, which is called "Air stop."
By this time, the query string we got was no different from the get query string, so we passed it to the builder for Cgi_vector. Then, as in the previous precedent, we can free different fields within the vector.
To test this program, it must be compiled into the Cgi-bin directory of the host Web server. You can then write a simple HTML page for testing, as follows:

 

 <HTML> <HEAD> <meta content= "text/html" > <title>a test of Standard HTML post& Lt;/title> </HEAD> Test, uses standard HTML post <form method= "POST" action= "/cgi-bin/posttest" > <p >field1: <input type = "text" NAME = "Field1" VALUE = "size =" ></p> <p>field2: <input type = "text" name = "Field2" VALUE = "size =" ></p> <p>field3: <input TYPE = "text" name = "Field3" V Alue = "" size = "></p> <p>field4: <input TYPE =" text "NAME =" Field4 "VALUE =" "size =" >&L " T;/p> <p>field5: <input TYPE = "text" NAME = "Field5" VALUE = "size =" ></p> <p>field6: & Lt;input type = "text" name = "Field6" VALUE = "size =" ></p> <p><input type = "Submit" name = "Su" Bmit "> </p> </Form>  
 


When you fill out this form and submit it, you get a simple text page that contains the parsed results. You can tell whether the CGI program is working properly.
Of course, it's more interesting to submit data with a single piece of program. However, the submission of post data is a different process. After you invoke the CGI program in a normal way, you must establish a separate connection to the server so that you can feed the query string back to it. The server then handles it and then feeds the query string back into the CGI program via standard input.
to establish a direct connection to the server, you must obtain the URL that you created, and then call OpenConnection () to create a urlconnection. However, since URLConnection generally does not allow us to send data to it, we must make a ridiculous call to the Setdooutput (true) function, which also includes Setdoinput (true) and Setallowuserinteraction (false)--comment ⑥. Finally, you can call Getoutputstream () to create a outputstream (output stream) and encapsulate it in a dataoutputstream so that it can communicate with it in a traditional way. The following is a piece of the program that is used to do the work above, and it must be executed after the data has been collected from its fields:

 

: Posttest.java//An applet so sends its data via a CGI POST import java.awt.*;
Import java.applet.*;
Import java.net.*;

Import java.io.*;
  public class Posttest extends Applet {final static int SIZE = 10;
  button Submit = New button ("Submit");
  textfield[] t = new textfield[size];
  String query = "";
  Label L = new label ();
  TextArea ta = new TextArea (15, 60);
    public void init () {panel p = new Panel ();
    P.setlayout (New GridLayout (T.length + 2, 2));
      for (int i = 0; i < t.length i++) {p.add (New Label ("Field" + i + "", label.right));
    P.add (T[i] = new TextField (30));
    } p.add (L);
    P.add (Submit);
    Add ("North", p);
  Add ("South", TA);
      Public boolean action (Event evt, Object Arg) {if (Evt.target.equals (submit)) {query = ' ";
      Ta.settext ("");
           Encode the query from the field data:for (int i = 0; i < t.length i++) query + + "field" + i + "=" +
   Urlencoder.encode (          T[i].gettext (). Trim ()) + "&";
      Query + + "Submit=submit"; Send the name using CGI ' s POST process:try {url u = new URL (getdocumentbase (), "Cgi-bin/post
        Test ");
        URLConnection URLC = U.openconnection ();
        Urlc.setdooutput (TRUE);
        Urlc.setdoinput (TRUE);
        Urlc.setallowuserinteraction (FALSE);
        DataOutputStream Server = new DataOutputStream (Urlc.getoutputstream ());
        Send the Data server.writebytes (query);
        Server.close (); Read and display the response.
        A//cannot use//getAppletContext (). showdocument (U);
        To display the results as a Web page!
        DataInputStream in = new DataInputStream (Urlc.getinputstream ());
        String s;
        while ((s = in.readline ())!= null) {Ta.appendtext (s + "\ n");
      } in.close ();
       catch (Exception e) { L.settext (E.tostring ());
    else return super.action (EVT, ARG);
  return true; }
} ///:~

⑥: I have to say that I don't really understand what's going on here, which comes from the Elliotte Rusty Harold, "Java network Programming," which was published by O ' Reilly in 1997. In his book, he mentions many confusing bugs that appear in the Java Networking function library. So once you get involved in these areas, it's not about writing code, and then letting it run that simple. Be wary of potential pitfalls!

Once the information is sent to the server, we call getInputStream () and encapsulate the return value into a datainputstream so that we can read the result. One thing to be aware of is that the results are displayed in a textarea (text area) in the form of lines of text. Why not simply use getAppletContext (). showdocument (u)? In fact, this is one of those traps. The code above works well, but if you try to swap showdocument (), almost everything will stop running. That is, showdocument () can actually run, but the return result from Posttest is "Zero content_length" (content length is 0). So for reasons that don't know why, showdocument () prevents the post query from passing to the CGI program. It's hard to tell whether this is a bug that will be fixed in a later release or because I don't understand it (the books I read are vague about it). However, in either case, as long as you can persist in the text area to watch the content returned from the CGI program, the above program will run without problems.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.