November 2013
Intermediate to advanced
392 pages
8h 59m
English
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.
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 methods:
publicclassURL{publicURL(java.lang.Strings)throwsjava.net.MalformedURLException{}publicjava.net.URLConnectionopenConnection()throwsjava.io.IOException{}...}
From a URL, you can create an HttpURLConnection that allows you to invoke specific requests. Here’s an example of doing a simple GET request:
URLurl=newURL("http://example.com/customers/1");connection=(HttpURLConnection)url.openConnection();connection.setRequestMethod("GET");connection.setRequestProperty("Accept","application/xml");if(connection.getResponseCode()!=200){thrownewRuntimeException("Operation failed: "+connection.getResponseCode());}System.out.println("Content-Type: "+connection.getContentType());BufferedReaderreader=newBufferedReader(newInputStreamReader(connection.getInputStream()));Stringline=reader.readLine();while(line!=null){System.out.println(line);line=reader.readLine();}connection ...
Read now
Unlock full access