Java Reference
In-Depth Information
would open a connection to the URL
http://www.dmoz.org/search/?q=java
and read the
resulting input stream.
Example 5-10
does exactly this.
Example 5-10. Do an Open Directory search
import
java.io.*
;
import
java.net.*
;
public
class
DMoz
{
public
static
void
main
(
String
[]
args
)
{
String
target
=
""
;
for
(
int
i
=
0
;
i
<
args
.
length
;
i
++)
{
target
+=
args
[
i
]
+
" "
;
}
target
=
target
.
trim
();
QueryString
query
=
new
QueryString
();
query
.
add
(
"q"
,
target
);
try
{
URL
u
=
new
URL
(
"http://www.dmoz.org/search/q?"
+
query
);
try
(
InputStream
in
=
new
BufferedInputStream
(
u
.
openStream
()))
{
InputStreamReader
theHTML
=
new
InputStreamReader
(
in
);
int
c
;
while
((
c
=
theHTML
.
read
())
!=
-
1
)
{
System
.
out
.
print
((
char
)
c
);
}
}
}
catch
(
MalformedURLException
ex
)
{
System
.
err
.
println
(
ex
);
}
catch
(
IOException
ex
)
{
System
.
err
.
println
(
ex
);
}
}
}
Of course, a lot more effort could be expended on parsing and displaying the results.
But notice how simple the code was to talk to this server. Aside from the funky-looking
URL and the slightly greater likelihood that some pieces of it need to be x-www-form-
url-encoded, talking to a server-side program that uses
GET
is no harder than retrieving
any other HTML page.
Accessing Password-Protected Sites
Many popular sites require a username and password for access. Some sites, such as the
W3C member pages, implement this through HTTP authentication. Others, such as the
New York Times
website, implement it through cookies and HTML forms. Java's
URL