Java Reference
In-Depth Information
public
static
void
main
(
String
[]
args
)
{
try
{
URL
u
=
new
URL
(
args
[
0
]);
HttpURLConnection
uc
=
(
HttpURLConnection
)
u
.
openConnection
();
try
(
InputStream
raw
=
uc
.
getInputStream
())
{
printFromStream
(
raw
);
}
catch
(
IOException
ex
)
{
printFromStream
(
uc
.
getErrorStream
());
}
}
catch
(
MalformedURLException
ex
)
{
System
.
err
.
println
(
args
[
0
]
+
" is not a parseable URL"
);
}
catch
(
IOException
ex
)
{
System
.
err
.
println
(
ex
);
}
}
private
static
void
printFromStream
(
InputStream
raw
)
throws
IOException
{
try
(
InputStream
buffer
=
new
BufferedInputStream
(
raw
))
{
Reader
reader
=
new
InputStreamReader
(
buffer
);
int
c
;
while
((
c
=
reader
.
read
())
!=
-
1
)
{
System
.
out
.
print
((
char
)
c
);
}
}
}
}
Redirects
The 300-level response codes all indicate some sort of redirect; that is, the requested
resource is no longer available at the expected location but it may be found at some
other location. When encountering such a response, most browsers automatically load
the document from its new location. However, this can be a security risk, because it has
the potential to move the user from a trusted site to an untrusted one, perhaps without
the user even noticing.
By default, an
HttpURLConnection
follows redirects. However, the
HttpURLConnec
tion
class has two static methods that let you decide whether to follow redirects:
public
static
boolean
getFollowRedirects
()
public
static
void
setFollowRedirects
(
boolean
follow
)
The
getFollowRedirects()
method returns
true
if redirects are being followed,
false
if they aren't. With an argument of
true
, the
setFollowRedirects()
method makes
HttpURLConnection
objects follow redirects. With an argument of
false
, it prevents
them from following redirects. Because these are static methods, they change the be‐
havior of all
HttpURLConnection
objects constructed after the method is invoked. The
setFollowRedirects()
method may throw a
SecurityException
if the security man‐
ager disallows the change. Applets especially are not allowed to change this value.