Java Reference
In-Depth Information
Chapter 16. Alternative Java Clients
While JAX-RS 2.0 added client support, there are other Java clients you can use to interact
with web services if you do not have JAX-RS 2.0 available in your environment.
java.net.URL
Like most programming languages, Java has a built-in HTTP client library. It's nothing
fancy, but it's good enough to perform most of the basic functions you need. The API is built
around two classes,
java.net.URL
and
java.net.HttpURLConnection
. The
URL
class is
just a Java representation of a URL. Here are some of the pertinent constructors and meth-
ods:
public
public class
class
URL
URL
{
public
public
URL
(
java
.
lang
.
String
s
)
throws
throws
java
.
net
.
MalformedURLException
{}
public
public
java
.
net
.
URLConnection
openConnection
()
throws
throws
java
.
io
.
IOException
{}
...
}
From a
URL
, you can create an
HttpURLConnection
that allows you to invoke specific re-
quests. Here's an example of doing a simple GET request:
URL url
=
new
new
URL
(
"http://example.com/customers/1"
);
connection
= (
HttpURLConnection
)
url
.
openConnection
();
connection
.
setRequestMethod
(
"GET"
);
connection
.
setRequestProperty
(
"Accept"
,
"application/xml"
);
iif
(
connection
.
getResponseCode
() !=
200
) {
throw
throw new
new
RuntimeException
(
"Operation failed: "
+
connection
.
getResponseCode
());
}
System
.
out
.
println
(
"Content-Type: "
+
connection
.
getContentType
());
BufferedReader reader
=
new
new
InputStreamReader
(
connection
.
getInputStream
()));
new
BufferedReader
(
new
String line
=
reader
.
readLine
();
while
while
(
line
!=
null
null
) {