Java Reference
In-Depth Information
Host:lesswrong.com
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.31
(KHTML, like Gecko) Chrome/26.0.1410.65 Safari/537.31
A web server can use this information to serve different pages to different clients, to get
and set cookies, to authenticate users through passwords, and more. Placing different
fields in the header that the client sends and the server responds with does all of this.
It's important to understand that this is not the HTTP header that the
server sends to the client that is read by the various getHeader
Field() and getHeaderFieldKey() methods discussed previously.
This is the HTTP header that the client sends to the server .
Each URLConnection sets a number of different name-value pairs in the header by de‐
fault. Here's the HTTP header that a connection from the SourceViewer2 program of
Example 7-1 sends:
User-Agent: Java/1.7.0_17
Host: httpbin.org
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Connection: close
As you can see, it's a little simpler than the one Chrome sends, and it has a different user
agent and accepts different kinds of files. However, you can modify these and add new
fields before connecting.
You add headers to the HTTP header using the setRequestProperty() method before
you open the connection:
public void setRequestProperty ( String name , String value )
The setRequestProperty() method adds a field to the header of this URLConnection
with a specified name and value. This method can be used only before the connection
is opened. It throws an IllegalStateException if the connection is already open. The
getRequestProperty() method returns the value of the named field of the HTTP
header used by this URLConnection .
HTTP allows a single named request property to have multiple values. In this case, the
separate values will be separated by commas. For example, the Accept header sent by
Java 7 in the previous code snippet has the four values text/html, image/gif, image/jpeg,
and *.
Search WWH ::




Custom Search