Java Reference
In-Depth Information
The query string is built using the
add()
method. The
post()
method actually sends
the data to the server by opening a
URLConnection
to the specified URL, setting its
doOutput
field to
true
, and writing the query string on the output stream. It then returns
the input stream containing the server's response.
The
main()
method is a simple test for this program that sends the name “Elliotte Rusty
Harold” and the email address
elharo@biblio.org
to the resource at
http://www.cafeau‐
lait.org/books/jnp4/postquery.phtml
. This resource is a simple form tester that accepts
any input using either the
POST
or
GET
method and returns an HTML page showing the
names and values that were submitted. The data returned is HTML; this example simply
displays the HTML rather than attempting to parse it. It would be easy to extend this
program by adding a user interface that lets you enter the name and email address to
be posted—but because doing that triples the size of the program while showing nothing
more of network programming, it is left as an exercise for the reader. Once you under‐
stand this example, it should be easy to write Java programs that communicate with
other server-side scripts.
Example 7-14. Posting a form
import
java.io.*
;
import
java.net.*
;
public
class
FormPoster
{
private
URL
url
;
// from Chapter 5, Example 5-8
private
QueryString
query
=
new
QueryString
();
public
FormPoster
(
URL
url
)
{
if
(!
url
.
getProtocol
().
toLowerCase
().
startsWith
(
"http"
))
{
throw
new
IllegalArgumentException
(
"Posting only works for http URLs"
);
}
this
.
url
=
url
;
}
public
void
add
(
String
name
,
String
value
)
{
query
.
add
(
name
,
value
);
}
public
URL
getURL
()
{
return
this
.
url
;
}
public
InputStream
post
()
throws
IOException
{
// open the connection and prepare it to POST
URLConnection
uc
=
url
.
openConnection
();
uc
.
setDoOutput
(
true
);