Java Reference
In-Depth Information
Here's the response from the server:
% java -classpath .:jnp4e.jar FormPoster
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Query Results</title>
</head>
<body>
<h1>Query Results</h1>
<p>You submitted the following name/value pairs:</p>
<ul>
<li>name = Elliotte Rusty Harold</li>
<li>email = elharo@ibiblio.org
</li>
</ul>
<hr />
Last Modified May 10, 2013
</body>
</html>
The main() method tries to read the first command-line argument from args[0] . The
argument is optional; if there is an argument, it is assumed to be a URL that can be
POSTed to. If there are no arguments, main() initializes url with a default URL, http://
www.cafeaulait.org/books/jnp4/postquery.phtml . main() then constructs a FormPost
er object. Two name-value pairs are added to this FormPoster object. Next, the post()
method is invoked and its response read and printed on System.out .
The post() method is the heart of the class. It first opens a connection to the URL stored
in the url field. It sets the doOutput field of this connection to true because this URL
Connection needs to send output and chains the OutputStream for this URL to an ASCII
OutputStreamWriter that sends the data, then flushes and closes the stream. Do not
forget to close the stream! If the stream isn't closed, no data will be sent. Finally, the
URLConnection 's InputStream is returned.
To summarize, posting data to a form requires these steps:
1. Decide what name-value pairs you'll send to the server-side program.
2. Write the server-side program that will accept and process the request. If it doesn't
use any custom data encoding, you can test this program using a regular HTML
form and a web browser.
3. Create a query string in your Java program. The string should look like this:
name1=value1&name2=value2&name3=value3
Search WWH ::




Custom Search