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" ?> |
===============Create the project in Netbeans=================
Create a new Java Application
Right click on your project –> New –> Other…
In ‘Web Services’ category, select ‘RESTful Java Client’ file
Follow the wizard, java codes and xml schema will be generated automatically.
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====
No comments:
Post a Comment