Java Reference
In-Depth Information
public URLConnection openConnection() throws IOException
The
openConnection()
method opens a socket to the specified URL and returns a
URLConnection
object. A
URLConnection
represents an open connection to a network
resource. If the call fails,
openConnection()
throws an
IOException
. For example:
try
{
URL
u
=
new
URL
(
"https://news.ycombinator.com/"
);
try
{
URLConnection
uc
=
u
.
openConnection
();
InputStream
in
=
uc
.
getInputStream
();
// read from the connection...
}
catch
(
IOException
ex
)
{
System
.
err
.
println
(
ex
);
}
}
catch
(
MalformedURLException
ex
)
{
System
.
err
.
println
(
ex
);
}
You should use this method when you want to communicate directly with the server.
The
URLConnection
gives you access to everything sent by the server: in addition to the
document itself in its raw form (e.g., HTML, plain text, binary image data), you can
access all the metadata specified by the protocol. For example, if the scheme is HTTP
or HTTPS, the
URLConnection
lets you access the HTTP headers as well as the raw
HTML. The
URLConnection
class also lets you write data to as well as read from a URL
—for instance, in order to send email to a mailto URL or post form data. The
URLCon
nection
class will be the primary subject of
Chapter 7
.
An overloaded variant of this method specifies the proxy server to pass the connection
through:
public
URLConnection
openConnection
(
Proxy
proxy
)
throws
IOException
This overrides any proxy server set with the usual
socksProxyHost
,
socksProxyPort
,
http.proxyHost
,
http.proxyPort
,
http.nonProxyHosts
, and similar system proper‐
ties. If the protocol handler does not support proxies, the argument is ignored and the
connection is made directly if possible.
public final Object getContent() throws IOException
The
getContent()
method is the third way to download data referenced by a URL. The
getContent()
method retrieves the data referenced by the URL and tries to make it into
some type of object. If the URL refers to some kind of text such as an ASCII or HTML
file, the object returned is usually some sort of
InputStream
. If the URL refers to an
image such as a GIF or a JPEG file,
getContent()
usually returns a
java.awt.Image
Producer
. What unifies these two disparate classes is that they are not the thing itself
but a means by which a program can construct the thing: