Your First Cup: An Introduction to the Java EE Platform

ProcedureGetting Duke's Current Age

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.

  1. 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;
    }
  2. Right-click in the editor window and select Format.

  3. Right-click in the editor window and select Fix Imports.

  4. Choose the java.net.HttpURLConnection fully-qualified name for the HttpURLConnection class.

  5. Choose the java.net.ProtocolException fully-qualified name for the ProtocolException exception.

  6. Choose the java.net.URL fully-qualified name for the URL class.

  7. Click OK.