Posting Form Data

indexadjustmentInternet and Web Development

Nov 13, 2013 (3 years and 10 months ago)

62 views

Posting Form Data

Pp 167..., Corejava

Sending Info from Browser to Server


When user clicks Submit button, text in text fields
and clickbox settings, etc, are sent back to web
server


Web server calls a program that processes user
input


Many techs enable web servers to call programs


Java servlets


JavaServer Faces


Microsoft ASP


CGI scripts in Perl, C++, or whatever language


Will call them all “scripts”!!!
--

not nice!!

Commands (“methods”) to send info
back to server


We won't discuss server
-
side scripts but just
how to send info to server


Two commands commonly used are POST and
GET


GET is easier, simply attach params to the end
of the URL


ttp://host/script?parameters


example


For example, Yahoo has a script, py/maps.py, at
the host maps.yahoo.com


Scripts requires 2 params, addr and csz


You separate the params by an & (ampersand)
and encode the parameters using URL Encoding


Replace all spaces with a +


Replace all nonalphanumeric chars by a % followed by
a 2
-
digit hex number (ASCII code)


S. Main is S%2e+Main


Because hex 2e is the period in ASCII code


Try requesting
http://maps.yahoo.com/py/maps.py?addr=1+Infinite+Loop&c
sz=Cupertino+CA

POST command


GET is easy but often limited (visible, short)


In POST, you don't attach params to a URL


Instead, you get an output stream from the
URLConnection


Then write name/value pairs to the output
stream


Still have to URL
-
encode the values and
separate them with & character

Generic Example of POST

URL url = new URL(“
ttp://host/script
”);

URLConnection connection = url.openConnection();

connection.setDoOutput(true); //default is input from server to
browser

PrintWriter out = new
PrintWriter(connection.getOutputStream());


//PrintWriter good for sending text to server

out.print(name1 + “=” + URLEncoder.encode(value1, “UTF
-
8”) + “&”);

out.print(name2 + “=” + URLEncoder.encode(value2, “UTF
-
8”));

out.close();


Then, call getInputStream and read the server resposne.


See the PostTest example.