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 and 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* 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(
            connection = (HttpURLConnection) serverAddress.openConnection();
            // Make the connection to Duke's Age
            // Read in the response
            rd = new BufferedReader(
    				new InputStreamReader(connection.getInputStream()));
            sb = new StringBuilder();
            while ((line = rd.readLine()) != null) {
            // Convert the response to an int
            age = Integer.parseInt(sb.toString());
        } catch (MalformedURLException e) {
            logger.warning("A MalformedURLException occurred.");
        } catch (ProtocolException e) {
            logger.warning("A ProtocolException occurred.");
        } catch (IOException e) {
            logger.warning("An IOException occurred");
    	return age;
  2. Right-click in the editor window and select Format.

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

  4. Click OK.