Java Reference
In-Depth Information
Pass each name and value in the query string to
URLEncoder.encode()
before
adding it to the query string.
4. Open a
URLConnection
to the URL of the program that will accept the data.
5. Set
doOutput
to
true
by invoking
setDoOutput(true)
.
6. Write the query string onto the
URLConnection
's
OutputStream
.
7. Close the
URLConnection
's
OutputStream
.
8. Read the server response from the
URLConnection
's
InputStream
.
GET
should only be used for safe operations that can be bookmarked and linked to.
POST
should be used for unsafe operations that should not be bookmarked or linked to.
The
getOutputStream()
method is also used for the
PUT
request method, a means of
storing files on a web server. The data to be stored is written onto the
OutputStream
that
getOutputStream()
returns. However, this can be done only from within the
HttpURLConnection
subclass of
URLConnection
, so discussion of
PUT
will have to wait
a little while.
Security Considerations for URLConnections
URLConnection
objects are subject to all the usual security restrictions about making
network connections, reading or writing files, and so forth. For instance, a
URLConnec
tion
can be created by an untrusted applet only if the
URLConnection
is pointing to the
host that the applet came from. However, the details can be a little tricky because dif‐
ferent URL schemes and their corresponding connections can have different security
implications. For example, a
jar
URL that points into the applet's own
jar
file should be
fine. However, a file URL that points to a local hard drive should not be.
Before attempting to connect a URL, you may want to know whether the connection
will be allowed. For this purpose, the
URLConnection
class has a
getPermission()
method:
public
Permission
getPermission
()
throws
IOException
This returns a
java.security.Permission
object that specifies what permission is
needed to connect to the URL. It returns
null
if no permission is needed (e.g., there's
no security manager in place). Subclasses of
URLConnection
return different subclasses
of
java.security.Permission
. For instance, if the underlying URL points to
www.gwbush.com
,
getPermission()
returns a
java.net.SocketPermission
for the
host
www.gwbush.com
with the connect and resolve actions.