Java Reference
In-Depth Information
InputStream
in
=
conn
.
getInputStream
();
}
catch
(
IOException
e
)
{
// Handle exception
}
HTTP defines “request methods,” which are the operations that a client can make
on a remote resource. These methods are called:
GET, POST, HEAD, PUT, DELETE, OPTIONS, TRACE
g
d
O
e
Each has slightly different usages, for example:
• GET should only be used to retrieve a document and NEVER should perform
any side effects.
• HEAD is equivalent to GET except the body is not returned—useful if a pro‐
gram wants to quickly check whether a URL has changed.
• POST is used when we want to send data to a server for processing.
By default, Java always uses GET, but it does provide a way to use other methods for
building more complex applications; however, doing so is a bit involved. In this next
example, we're using the search function provided by the BBC website to search for
news articles about Java:
URL
url
=
new
URL
(
"http://www.bbc.co.uk/search"
);
String
rawData
=
"q=java"
;
String
encodedData
=
URLEncoder
.
encode
(
rawData
,
"ASCII"
);
String
contentType
=
"application/x-www-form-urlencoded"
;
HttpURLConnection
conn
=
(
HttpURLConnection
)
url
.
openConnection
();
conn
.
setInstanceFollowRedirects
(
false
);
conn
.
setRequestMethod
(
"POST"
);
conn
.
setRequestProperty
(
"Content-Type"
,
contentType
);
conn
.
setRequestProperty
(
"Content-Length"
,
String
.
valueOf
(
encodedData
.
length
()));
conn
.
setDoOutput
(
true
);
OutputStream
os
=
conn
.
getOutputStream
();
os
.
write
(
encodedData
.
getBytes
()
);
int
response
=
conn
.
getResponseCode
();
if
(
response
==
HttpURLConnection
.
HTTP_MOVED_PERM
||
response
==
HttpURLConnection
.
HTTP_MOVED_TEMP
)
{
System
.
out
.
println
(
"Moved to: "
+
conn
.
getHeaderField
(
"Location"
));
}
else
{
try
(
InputStream
in
=
conn
.
getInputStream
())
{
Files
.
copy
(
in
,
Paths
.
get
(
"bbc.txt"
),
StandardCopyOption
.
REPLACE_EXISTING
);
}
}