Java Reference
In-Depth Information
try
(
OutputStreamWriter
out
=
new
OutputStreamWriter
(
uc
.
getOutputStream
(),
"UTF-8"
))
{
// The POST line, the Content-type header,
// and the Content-length headers are sent by the URLConnection.
// We just need to send the data
out
.
write
(
query
.
toString
());
out
.
write
(
"\r\n"
);
out
.
flush
();
}
// Return the response
return
uc
.
getInputStream
();
}
public
static
void
main
(
String
[]
args
)
{
URL
url
;
if
(
args
.
length
>
0
)
{
try
{
url
=
new
URL
(
args
[
0
]);
}
catch
(
MalformedURLException
ex
)
{
System
.
err
.
println
(
"Usage: java FormPoster url"
);
return
;
}
}
else
{
try
{
url
=
new
URL
(
"http://www.cafeaulait.org/books/jnp4/postquery.phtml"
);
}
catch
(
MalformedURLException
ex
)
{
// shouldn't happen
System
.
err
.
println
(
ex
);
return
;
}
}
FormPoster
poster
=
new
FormPoster
(
url
);
poster
.
add
(
"name"
,
"Elliotte Rusty Harold"
);
poster
.
add
(
"email"
,
"elharo@ibiblio.org"
);
try
(
InputStream
in
=
poster
.
post
())
{
// Read the response
Reader
r
=
new
InputStreamReader
(
in
);
int
c
;
while
((
c
=
r
.
read
())
!=
-
1
)
{
System
.
out
.
print
((
char
)
c
);
}
System
.
out
.
println
();
}
catch
(
IOException
ex
)
{
System
.
err
.
println
(
ex
);
}
}
}