Calling RESTful Service with Java Client using java.net.URL Example

Reading and Writing using the URL and HttpURLConnection Class

The URL class represents and Uniform Resource Locator — an address to a location on the internet to some resource whether it be a web page for your Web browser, a file for FTP or a service to produce or consume some data. The following URL shown below takes you to this post using the http protocol, hosted on www.avaldes.com domain, using port 8080 (actually, I am using port 80 which is the default port so it can be omitted from the URL), with this path or reference.

URL Structure

URL structure

Common components of a URL

Although there can be more components in a URL, the most common form has four components detailed above. Additional components may include query parameters which are separated by a question mark (?) after the Path and each additional query parameter is separated by ampersand (&).

ComponentDescription
ProtocolEvery URL begins with the protocol or scheme. Common protocols include http, https, ftp, file, cvs, svn, mailto, ldap, or chrome all followed by colon (:) and two slashes (//).
HostIn my example, it is avaldes.com for my domain. Other domains include google.com, cnn.com, foxnews.com, whitehouse.gov, army.mil, and nyu.edu. Notice that domain names also contain a dot (.) and extension depending on the type of domain it is: com for company, org for organization, edu for education, mil for military, gov for government.
PortPort at which the internet (web, ftp, ldap, etc) server is listening to for resource requests from clients.
PathWeb page or resource you are actually looking for. In this example, calling-restful-service-with-java-client-using-java-net-url-example is the web page we are seeking.

Example using GET Request with Web Service

package com.avaldes.tutorial;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HttpURLGetConnectionExample {
  public static void main(String[] args) {
    String URLAddress = "http://localhost:8080/RestfulWebServiceExample/rest/actors/124";
    String inputString = null;
    int responseCode = 0;
    
    try {
      URL url = new URL(URLAddress);
      try {
        // Get an HttpURLConnection subclass object instead of URLConnection
        HttpURLConnection myHttpConnection = (HttpURLConnection) url.openConnection();
        
        // ensure you use the GET method
        myHttpConnection.setRequestMethod("GET");
        
        // get the response-code from the response 
        responseCode = myHttpConnection.getResponseCode();
        
        // print out URL details
        System.out.format("Connecting to %s\nConnection Method: '%s'\nResponse Code is: %d\n", URLAddress, "GET", responseCode);
        System.out.println("----[ URL DETAILS ]-----------------");
        System.out.println("URL Protocol....: " + url.getProtocol());
        System.out.println("URL Host........: " + url.getHost());
        System.out.println("URL Port........: " + url.getPort());
        System.out.println("URL Authority...: " + url.getAuthority());
        System.out.println("URL Path........: " + url.getPath());
        System.out.println("URL User Info...: " + url.getUserInfo());
        System.out.println("URL Query Info..: " + url.getQuery());
        
        System.out.println("----[ OUTPUT BELOW ]-----------------------------------------------------------------");
        
        // open the contents of the URL as an inputStream and print to stdout
        BufferedReader in = new BufferedReader(new InputStreamReader(
            myHttpConnection.getInputStream()));
        while ((inputString = in.readLine()) != null) {
          System.out.println(inputString);
        }
        in.close();   
        System.out.println("-------------------------------------------------------------------------------------");
      } catch (IOException e) {
        e.printStackTrace();
      }
    } catch (MalformedURLException e) {
      e.printStackTrace();
    }
  }
}

Output of RESTful Web Service using GET

Connecting to http://localhost:8080/RestfulWebServiceExample/rest/actors/124
Connection Method: 'GET'
Response Code is: 200
----[ URL DETAILS ]-----------------
URL Protocol....: http
URL Host........: localhost
URL Port........: 8080
URL Authority...: localhost:8080
URL Path........: /RestfulWebServiceExample/rest/actors/124
URL User Info...: null
URL Query Info..: null
----[ OUTPUT BELOW ]-----------------------------------------------------------------
{"id":124,"name":"Jennifer Lawrence","birthName":"Jennifer Shrader Lawrence",
"birthDate":"August 15, 1990","email":"jennifer@mail.com","image":
"http://www.siempre-lindas.cl/wp-content/uploads/2014/11/jennifer-lawrence-164522_w1000.jpg",
"active":true}
-------------------------------------------------------------------------------------

Example using POST Request with Web Service

In this example, we will post a JSON object which will correspond to the Actor class in my Java program. I am building that JSON object using StringBuffer class and using append for each of the fields and their corresponding values.

package com.avaldes.tutorial;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HttpURLPostConnectionExample {

  public static void main(String[] args) {
    String URLAddress = "http://localhost:8080/RestfulWebServiceExample/rest/actors/add";
    String inputString = null;
    int responseCode = 0;
    
    try {
      URL url = new URL(URLAddress);
      try {
        // Get an HttpURLConnection subclass object instead of URLConnection
        HttpURLConnection myHttpConnection = (HttpURLConnection) url.openConnection();
        
        // ensure you use the GET method
        myHttpConnection.setRequestMethod("POST");
        myHttpConnection.setDoOutput(true);
        myHttpConnection.setRequestProperty("Content-Type", "application/json");
        
        // create the JSON message
        StringBuffer msg = new StringBuffer("{");
        msg.append("\"id\":");
        msg.append(333);
        msg.append(",");
        msg.append("\"name\":");
        msg.append("\"Amaury Valdes\"");
        msg.append(",");
        msg.append("\"birthName\":");
        msg.append("\"Amaury Matthew Valdes\"");
        msg.append(",");
        msg.append("\"birthDate\":");
        msg.append("\"September 15, 1982\"");
        msg.append(",");
        msg.append("\"email\":");
        msg.append("\"amaury.valdes@mail.com\"");
        
        msg.append("}");
        
        // Output the JSON string to the REST service
        OutputStream output = myHttpConnection.getOutputStream();
        output.write(msg.toString().getBytes());
        output.flush();
        
        // get the response-code from the response 
        responseCode = myHttpConnection.getResponseCode();
        
        // print out URL details
        System.out.format("Connecting to %s\nConnection Method: '%s'\nResponse Code is: %d\n", URLAddress, "POST", responseCode);
        System.out.println("----[ URL DETAILS ]-----------------");
        System.out.println("URL Protocol....: " + url.getProtocol());
        System.out.println("URL Host........: " + url.getHost());
        System.out.println("URL Port........: " + url.getPort());
        System.out.println("URL Authority...: " + url.getAuthority());
        System.out.println("URL Path........: " + url.getPath());
        System.out.println("URL User Info...: " + url.getUserInfo());
        System.out.println("URL Query Info..: " + url.getQuery());
        
        System.out.println("----[ OUTPUT BELOW ]-----------------------------------------------------------------");
        
        // open the contents of the URL as an inputStream and print to stdout
        BufferedReader in = new BufferedReader(new InputStreamReader(
            myHttpConnection.getInputStream()));
        while ((inputString = in.readLine()) != null) {
          System.out.println(inputString);
        }
        in.close();   
        System.out.println("-------------------------------------------------------------------------------------");
      } catch (IOException e) {
        e.printStackTrace();
      }
    } catch (MalformedURLException e) {
      e.printStackTrace();
    }
  }
}

Output of RESTful Web Service using POST

Connecting to http://localhost:8080/RestfulWebServiceExample/rest/actors/add
Connection Method: 'POST'
Response Code is: 200
----[ URL DETAILS ]-----------------
URL Protocol....: http
URL Host........: localhost
URL Port........: 8080
URL Authority...: localhost:8080
URL Path........: /RestfulWebServiceExample/rest/actors/add
URL User Info...: null
URL Query Info..: null
----[ OUTPUT BELOW ]-----------------------------------------------------------------------------
{"id":333,"name":"Amaury Valdes","birthName":"Amaury Matthew Valdes","birthDate":"September 15, 1982","email":"amaury.valdes@mail.com","active":false}
-------------------------------------------------------------------------------------------------

RESTful Web services details

I am using the following RESTful web service in my calls to return JSON data. For more details on the restful web service itself, please refer to RESTful Web Services with AngularJS, Bootstrap and Java using JAX-RS and Jersey.

package com.avaldes;

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

import com.avaldes.model.Actor;

@Path("/actors")
public class RestfulWSExample {
  static final String api_version = "1.01A rev.18729";
  static Logger logger = Logger.getLogger(RestfulWSExample.class);
  static String xmlString = null;
  static Map<String, Actor> actors = new HashMap<String, Actor>();
  
  static {
    System.out.println("Initializing Internal DataStore...");
    actors.put("123", new Actor(123, "Hugh Jackson", "Hugh Michael Jackman", "October 12, 1968", "hughjackman@mail.com", "https://stocklandmartelblog.files.wordpress.com/2013/07/nino-muncc83oz_hugh-jackman_page_3.jpg", true));
    actors.put("124", new Actor(124, "Jennifer Lawrence", "Jennifer Shrader Lawrence", "August 15, 1990", "jennifer@mail.com", "http://www.siempre-lindas.cl/wp-content/uploads/2014/11/jennifer-lawrence-164522_w1000.jpg", true));
    actors.put("345", new Actor(345, "Jennifer Lopez", "Jennifer Lynn Lopez", "July 24, 1969", "jlo@verizon.com", "http://media1.popsugar-assets.com/files/2013/01/01/5/192/1922398/e0bd827287eb8c5f_145351598.xxxlarge_2.jpg", true));
    actors.put("333", new Actor(333, "Jennifer Anniston", "Jennifer Joanna Aniston", "February 11, 1969", "jennifer.anniston@eonline.com", "http://media1.popsugar-assets.com/files/2013/01/01/5/192/1922398/e59ab35359063e7c_139123757.xxxlarge_2.jpg", true));
    actors.put("444", new Actor(444, "Julia Roberts", "Julia Fiona Roberts ", "October 28, 1967", "julia.roberts@att.com", "http://img2.timeinc.net/people/i/2013/specials/beauties/then-now/julia-roberts-4-435.jpg", true));
    actors.put("777", new Actor(777, "Chris Evans", "Christopher Robert Evans", "June 13, 1981", "chris.evans@comcast.com", "http://assets-s3.usmagazine.com/uploads/assets/celebrities/28454-chris-evans/1311353993_chris-evans-bio-402.jpg", true));
    actors.put("654", new Actor(654, "Robert Downey Jr.", "Robert John Downey Jr", "April 4, 1965", "robertdowney@verizon.com", "http://thehollywoodbillboard.com/wp-content/uploads/2014/10/robert-downey-jr-iron-man-beard-background-1.jpg", true));
    actors.put("255", new Actor(255, "Johnny Depp", "John Christopher Depp II", "June 9, 1963", "johndepp@hollywood.com", "http://images.latinpost.com/data/images/full/9536/johnny-depp-at-transcendence-los-angeles-premiere.jpg?w=600", true));    
    actors.put("989", new Actor(989, "Scarlet Johansson", "Scarlett Ingrid Johansson", "November 22, 1984", "scarjo@mail.com", "http://static.comicvine.com/uploads/original/11111/111117228/4087439-2415305600-Scarl.jpg", true));
  }
    
  @Path("/version")
  @GET
  @Produces(MediaType.TEXT_HTML)
  public String returnVersion() {
    return "<p>Version: " + api_version + "</p>";
  }

  // This is the default @PATH
  @GET
  @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
  public ArrayList<Actor> getAllActors() {
    System.out.println("Getting all actors...");
    ArrayList<Actor> actorList = new ArrayList<Actor>(actors.values());
    return actorList;
  }
  
  @Path("{id}")
  @GET
  @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
  public Actor getActorById(@PathParam("id") String id) {
    System.out.println("Getting actor by ID: " + id);

    Actor actor = actors.get(id);
    if (actor != null) {
    logger.info("Inside getActorById, returned: " + actor.toString());
    } else {
    logger.info("Inside getActorById, ID: " + id + ", NOT FOUND!");
    }
    return actor;
  }
  
  @Path("{id}")
  @PUT
  @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
  @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
  public Actor updateActor(Actor actor) {
    actors.put(""+actor.getId(), actor);
    
    System.out.println("updateActor with ID: " + actor.getId());
    if (actor != null) {
    logger.info("Inside updateActor, returned: " + actor.toString());
    } else {
    logger.info("Inside updateActor, ID: " + actor.getId() + ", NOT FOUND!");
    }
    return actor; 
  }
  
  @Path("/search/{query}")
  @GET
  @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
  public ArrayList<Actor> searchActorByName(@PathParam("query") String query) {
      System.out.println("Searching actor by Name: " + query);
    
      ArrayList<Actor> actorList = new ArrayList<Actor>();    
    for (Actor c: actors.values()) {
      if (c.getName().toUpperCase().contains(query.toUpperCase()))
        actorList.add(c);
    }
    return actorList;
  }
  
  @Path("/add")
  @POST
  @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
  @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
  public Actor addActor(Actor actor) {
    System.out.println("Adding actor with ID: " + actor.getId());
    
    if (actor != null) {
    System.out.println("Inside addActor, returned: " + actor.toString());
    actors.put(""+actor.getId(), actor);
    System.out.println("# of actors: " + actors.size());
    System.out.println("Actors are now: " + actors);
    } else {
    System.out.println("Inside addActor, Unable to add actors...");
    } 
    return actor;
  }
  
  @Path("{id}")
  @DELETE
  @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
  public Actor deleteActorById(@PathParam("id") String id) {
    System.out.println("Deleting actor with ID: " + id);
    
    Actor actor = actors.remove(id);
    if (actor != null) {
    logger.info("Inside deleteActorById, returned: " + actor.toString());
    } else {
    logger.info("Inside deleteActorById, ID: " + id + ", NOT FOUND!");
    }
    return actor;
  }
}

That’s It!

I hope you enjoyed this tutorial. Please continue to share the love and like us so that we can continue bringing you quality tutorials. Happy Coding!!!

java-net-url

Please Share Us on Social Media

Facebooktwitterredditpinterestlinkedinmail

Leave a Reply

Your email address will not be published. Required fields are marked *