Java Reference
In-Depth Information
These methods only really have meaning when the URL being con‐
nected to is an HTTP URL, because only the HTTP protocol makes
use of headers like this. Though they could possibly have other mean‐
ings in other protocols, such as NNTP, this is really just an example of
poor API design. These methods should be part of the more specific
HttpURLConnection class, not the generic URLConnection class.
For instance, web servers and clients store some limited persistent information with
cookies. A cookie is a collection of name-value pairs. The server sends a cookie to a
client using the response HTTP header. From that point forward, whenever the client
requests a URL from that server, it includes a Cookie field in the HTTP request header
that looks like this:
Cookie: username=elharo; password=ACD0X9F23JJJn6G; session=100678945
This particular Cookie field sends three name-value pairs to the server. There's no limit
to the number of name-value pairs that can be included in any one cookie. Given a
URLConnection object uc , you could add this cookie to the connection, like this:
uc . setRequestProperty ( "Cookie" ,
"username=elharo; password=ACD0X9F23JJJn6G; session=100678945" );
You can set the same property to a new value, but this changes the existing property
value. To add an additional property value, use the addRequestProperty() method
instead:
public void addRequestProperty ( String name , String value )
There's no fixed list of legal headers. Servers usually ignore any headers they don't rec‐
ognize. HTTP does put a few restrictions on the content of the names and values of
header fields. For instance, the names can't contain whitespace and the values can't
contain any line breaks. Java enforces the restrictions on fields containing line breaks,
but not much else. If a field contains a line break, setRequestProperty() and addRe
questProperty() throw an IllegalArgumentException . Otherwise, it's quite easy to
make a URLConnection send malformed headers to the server, so be careful. Some
servers will handle the malformed headers gracefully. Some will ignore the bad header
and return the requested document anyway, but some will reply with an HTTP 400, Bad
Request error.
If, for some reason, you need to inspect the headers in a URLConnection , there's a stan‐
dard getter method:
public String getRequestProperty ( String name )
Java also includes a method to get all the request properties for a connection as a Map :
public Map < String , List < String >> getRequestProperties ()
Search WWH ::




Custom Search