Thứ Tư, 5 tháng 12, 2012

Java : Xài dịch vụ Web dạng REST với Client API của Jersey

Trong bài "Tạo dịch vụ Web dạng REST (JAX-RS)" ta đã tạo và đăng (publish) dịch vụ Web ở phía máy chủ (server). Bài này ta sẽ tạo một ứng dụng phần máy khách (client) để tiêu thụ dịch vụ Web này.
Ta tải về máy thư viện Jersey tại http://jersey.java.net/.
Tạo một thư mục dự án như sau :

Như ta thấy ở hình trên, trong ứng dụng khách này ta sử dụng hai tập tin jar jersey-client và jersey-core của thư viện Jersey vừa tải về.
Ta dùng JAXB để phát sinh lớp MobilePhones từ tập tin "mobile phone.xsd". Xem chi tiết tại đây.



Nội dung lớp MobilePhoneClient dùng để xài (consume) ứng dụng Web getListMobile như sau:
package com.openspace;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;

import javax.ws.rs.core.MediaType;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

import com.openspace.entity.MobilePhones;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

public class MobilePhoneClient {

 private static WebResource webResource;

 public MobilePhoneClient() {
 }

 public static void main(String[] args) {
  getXMLMobileList();
 }

 public static void getXMLMobileList() {
  Client client = Client.create();
  webResource = client.resource("http://localhost:8080/WebServiceRS");
  ClientResponse clientResponse = webResource
    .path("/services/getListMobile")
    .accept(MediaType.APPLICATION_XML).get(ClientResponse.class);
  if (clientResponse.getStatus() == 200) {
   MobilePhones mobilePhones = clientResponse.getEntity(MobilePhones.class);
   
   try {
    JAXBContext jc = JAXBContext.newInstance(MobilePhones.class);
    Marshaller m = jc.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
    OutputStream os = new FileOutputStream("reponseXML.xml");
    m.marshal(mobilePhones, os);
   } catch (JAXBException e) {
    e.printStackTrace();
   } catch (FileNotFoundException e) {
    e.printStackTrace();
   }
  }
 }
}

Giải thích:
- Đầu tiên ta tạo một thể hiện (instance) của Client bằng cách gọi hàm Client.create().
- Sau đó tạo một WebResource trỏ đến địa chỉ mà dịch vụ Web đuợc đăng (http://localhost:8080/WebServiceRS)
- Ta dùng ClientReponse để gọi phương thức GET của HTTP đến dịch vụ Web tại địa chỉ http://localhost:8080/WebServiceRS/services/getListMobile, kết quả trả về dưới dạng XML.
- Nếu phương thức GET được gọi thành công, ta nhận được kết quả trả về của dịch vụ Web getListMobile. Lấy kết quả này dưới dạng một đối tượng MobilePhones.
- Sau đó ta chuyển xẹp đối tượng này vào tập tin reponseXML.xml

1 nhận xét: