Java Reference
In-Depth Information
Creating
a
Client
for
a
RESTful
Service
Using
Sockets
Problem
You want to invoke a publicly available RESTful service to work with a real API.
Solution
Use the URL class to get a socket connection. Post the data in the URL and create the HTTP
headers from scratch. Then use the input stream on the socket to read the XML response.
Discussion
The Digital Library for Earth System Education is a free library of articles available online
for learners from grade school through graduate school. It exposes its catalog as a RESTful
API. You can read about its services at http://www.dlese.org/dds/services/ddsws1-1/ser-
vice_specification.jsp . I'm using it here because it's simple and requires no registration, so
you can focus on the example.
Example 8-4 is a Java class that kicks it old school. It simply performs a basic search and gets
an XML response, which you print to the console.
Example8-4.DigitalLibraryRestSearch.java
package simplerestclient;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.URLEncoder;
/**
* Invokes a RESTful service.
*/
public class DigitalLibraryRestSearch {
public static void main(String... args) throws Exception {
doDigLib();
Search WWH ::




Custom Search