While performing this task, you will add some code to the getAge method to access Duke's current age from the JAX-RS web service.
Use the java.net and java.io classes to create an HTTP connection to the Duke's Age web service and read in the result.
Add the following code to the getAge method.
public int getAge() { // Use the java.net.* APIs to access the Duke's Age RESTful web service HttpURLConnection connection = null; BufferedReader rd = null; StringBuilder sb = null; String line = null; URL serverAddress = null; try { serverAddress = new URL( "http://localhost:8080/DukesAgeService/resources/dukesAge"); connection = (HttpURLConnection) serverAddress.openConnection(); connection.setRequestMethod("GET"); connection.setDoOutput(true); connection.setReadTimeout(10000); // Make the connection to Duke's Age connection.connect(); // Read in the response rd = new BufferedReader( new InputStreamReader(connection.getInputStream())); sb = new StringBuilder(); while ((line = rd.readLine()) != null) { sb.append(line); } // Convert the response to an int age = Integer.parseInt(sb.toString()); } catch (MalformedURLException e) { logger.warning("A MalformedURLException occurred."); e.printStackTrace(); } catch (ProtocolException e) { logger.warning("A ProtocolException occurred."); e.printStackTrace(); } catch (IOException e) { logger.warning("An IOException occurred"); e.printStackTrace(); } return age; }
Right-click in the editor window and select Format.
Right-click in the editor window and select Fix Imports.
Click OK.