Monday 10 June 2013

Create a Simple Java REST Web Service Client

A web service is a method of communication between two electronic devices over the World Wide Web.  [Wikipedia]

Unlike some private protocol, RESTful web service use common web protocol and encapsulate data into XML format.

For example, client sent a photo search request to flickr:

http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=b673a1be26fa7463c7036d9d0e3339e7&text=gundam&format=rest&api_sig=028e6e4f5041b8974069d4ead1f7f2ea

And flickr will response

<?xml version="1.0" encoding="utf-8" ?>
<rsp stat="ok">
<photos page="1" pages="1842" perpage="100" total="184172">
<photo id="9004970606" owner="91423658@N05" secret="fb1d4dbf62" server="5340" farm="6" title="gundam" ispublic="1" isfriend="0" isfamily="0" />
<photo id="9004399158" owner="32670813@N07" secret="978879e163" server="7325" farm="8" title="Bandai advertisement in Gundam Seed Destiny Remaster" ispublic="1" isfriend="0" isfamily="0" />
</photos>
</rsp>

 


===============Create the project in Netbeans=================


Create a new Java Application


image


 


Right click on your project –> New –> Other…


In ‘Web Services’ category, select ‘RESTful Java Client’ file


image


Follow the wizard, java codes and xml schema will be generated automatically.


image


In NewJerseyClient.java, all APIs are listed. You only need to call the mapped function with proper parameters and the function will raise a connection and make a request.


The Rsp.java is used to unmarsal the XML response.


 


# Do NOT forget to add the app key in your request.


## Because this in only a very simple example, you need to disable the ‘login’ authority function.


 


Sample code:


public static void main(String[] args) {
// TODO code application logic here
NewJerseyClient flickrREST = new NewJerseyClient();
RestResponse result = flickrREST.photo_search("gundam");
unmarsal(result.getDataAsString());
}

private static void unmarsal(String xml) {
ByteArrayInputStream stream=new ByteArrayInputStream(xml.getBytes());
Rsp rsp = JAXB.unmarshal(stream, Rsp.class);
System.out.println("Stat:"+rsp.getStat());
Rsp.Photos photos = rsp.getPhotos();
System.out.println("Page:" + photos.getPage() + " Pages:" + photos.getPages()
+ " PerPage:" + photos.getPerpage() + " TotalResults:" + photos.getTotal());
for (Rsp.Photo photo : photos.getPhoto()) {
System.out.println("PhotoID:" + photo.getId() + " Title:" + photo.getTitle());
}
}



===========More works could be done to improve the user interface====


image

No comments:

Post a Comment