How to Call REST in Java

How to Call REST in Java thumbnail
Using RESTful architecture is one way of performing actions online through your Java code.

One of the relatively recent entries into the toolbox of a Web developer is the REST architecture. This architecture utilizes HTTP request methods as part of the request processing stage, e.g. creating unique logic for the same URL depending on whether the request was a GET request or a POST request. This allows for easier client interaction, even without using a Web browser per se--any system capable of making an HTTP request is capable of working with a REST-based architecture.

Things You'll Need

  • Java JDK (version 1.5 or higher)
  • Java Integrated Development Environment such as Eclipse or Netbeans is strongly recommended (though not required)
Show More

Instructions

    • 1

      Create a new URL object to use for connecting to the REST service:

      URL u = new URL("http://www.example.com/");

    • 2

      Get the URLConnection from the URL by opening the connection, casting to HttpURLConnection.

      HttpURLConnection conn = (HttpURLConnection)u.openConnection();

    • 3

      Set the request method to use on the connection, such as GET, POST, DELETE, etc.

      conn.setRequestMethod("POST");

    • 4

      Get the necessary stream for the request, i.e. an InputStream if you're reading data with a GET request, or an OutputStream if you're writing data with a POST request.

      InputStream is = conn.getInputStream();

      // work with stream as appropriate.

Tips & Warnings

  • Note that this code is extremely simplistic. You'll want to add error checking to ensure the request went through correctly, exception handling code, etc.

Related Searches:

References

  • Photo Credit Photos.com/Photos.com/Getty Images

Comments

Related Ads

Featured