2011-08-24 34 views
15

Ở đây tôi không tạo dịch vụ RESTful thực sự tôi phải gọi dịch vụ Restful bên ngoài từ mã java của mình. Hiện tại tôi đang thực hiện điều này bằng cách sử dụng Apache HttpClient. Câu trả lời tôi nhận được từ dịch vụ web ở định dạng XML. Tôi cần trích xuất dữ liệu từ XML và đặt chúng trên các đối tượng Java. Thay vì sử dụng trình phân tích cú pháp SAX, tôi nghe nói rằng chúng ta có thể sử dụng JAX-RS và JERSEY để tự động ánh xạ các thẻ xml cho các đối tượng java tương ứng.gọi Dịch vụ an toàn từ Java

Tôi đang xem xét nhưng không thể tìm thấy nguồn để bắt đầu. tôi đã nhìn vào các liên kết hiện có Consuming RESTful APIs using Java RESTful call in Java

Any help is appreciated trong việc di chuyển về phía trước.

Cảm ơn !!

+0

Nếu bạn có thể gọi dịch vụ và nhận lại json, gson/Jackson Apis dễ dàng hơn jaxb, bạn không cần chú thích trên đối tượng mô hình – Kevin

+0

Xin chào Kevin, tôi có dịch vụ REST bên ngoài và tôi muốn gọi nó từ ứng dụng web. Cách tốt nhất để làm điều đó là gì? Dịch vụ REST trả về định dạng JSON dưới dạng phản hồi. bạn nói thật dễ dàng để xử lý phản hồi JSON. Bạn có thể giải thích như thế nào? – Jignesh

Trả lời

16

CẬP NHẬT

như theo dõi với điều này: Tôi có thể làm theo cách này ?? nếu xml được trả lại là 4 ..... Nếu tôi đang xây dựng đối tượng Person, tôi tin rằng điều này sẽ bị nghẹt thở. Tôi có thể chỉ liên kết các phần tử xml mà tôi muốn không? nếu Có, tôi có thể làm như thế nào .

Bạn có thể lập bản đồ XML này như sau:

đầu vào.xml

<?xml version="1.0" encoding="UTF-8"?> 
<Persons> 
    <NumberOfPersons>2</NumberOfPersons> 
     <Person> 
      <Name>Jane</Name> 
      <Age>40</Age> 
     </Person> 
     <Person> 
      <Name>John</Name> 
      <Age>50</Age> 
     </Person> 
</Persons> 

Người

package forum7177628; 

import java.util.List; 

import javax.xml.bind.annotation.XmlAccessType; 
import javax.xml.bind.annotation.XmlAccessorType; 
import javax.xml.bind.annotation.XmlElement; 
import javax.xml.bind.annotation.XmlRootElement; 

@XmlRootElement(name="Persons") 
@XmlAccessorType(XmlAccessType.FIELD) 
public class Persons { 

    @XmlElement(name="Person") 
    private List<Person> people; 

} 

Person

package forum7177628; 

import javax.xml.bind.annotation.XmlAccessType; 
import javax.xml.bind.annotation.XmlAccessorType; 
import javax.xml.bind.annotation.XmlElement; 

@XmlAccessorType(XmlAccessType.FIELD) 
public class Person { 

    @XmlElement(name="Name") 
    private String name; 

    @XmlElement(name="Age") 
    private int age; 

} 

Demo

package forum7177628; 

import java.io.File; 

import javax.xml.bind.JAXBContext; 
import javax.xml.bind.Marshaller; 
import javax.xml.bind.Unmarshaller; 

public class Demo { 

    public static void main(String[] args) throws Exception { 
     JAXBContext jc = JAXBContext.newInstance(Persons.class); 

     Unmarshaller unmarshaller = jc.createUnmarshaller(); 
     Persons persons = (Persons) unmarshaller.unmarshal(new File("src/forum7177628/input.xml")); 

     Marshaller marshaller = jc.createMarshaller(); 
     marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); 
     marshaller.marshal(persons, System.out); 
    } 

} 

Output

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
<Persons> 
    <Person> 
     <Name>Jane</Name> 
     <Age>40</Age> 
    </Person> 
    <Person> 
     <Name>John</Name> 
     <Age>50</Age> 
    </Person> 
</Persons> 

ĐÁP ORIGINAL

Dưới đây là một ví dụ về cách gọi một dịch vụ RESTful sử dụng các API Java SE bao gồm JAXB:

String uri = 
    "http://localhost:8080/CustomerService/rest/customers/1"; 
URL url = new URL(uri); 
HttpURLConnection connection = 
    (HttpURLConnection) url.openConnection(); 
connection.setRequestMethod("GET"); 
connection.setRequestProperty("Accept", "application/xml"); 

JAXBContext jc = JAXBContext.newInstance(Customer.class); 
InputStream xml = connection.getInputStream(); 
Customer customer = 
    (Customer) jc.createUnmarshaller().unmarshal(xml); 

connection.disconnect(); 

Để biết thêm thông tin:

+1

theo dõi điều này: Tôi có thể làm theo cách này không ?? nếu xml được trả lại như 4 ..... Nếu tôi xây dựng một đối tượng Person , Tôi tin điều này sẽ bị nghẹt thở. Tôi có thể chỉ liên kết các phần tử xml mà tôi muốn không? nếu có, tôi có thể làm như thế nào. – Rishi

6

JAX-RS là api Java cho webservice yên tĩnh. Jersey là một triển khai từ mặt trời/oracle.

Bạn cần jaxb để chuyển đổi xml thành POJO. Nhưng nó không phải là trường hợp luôn luôn, đối tượng chuyển đổi có thể được sử dụng mà không cần bất kỳ sự biến đổi nào. Nếu đây là kịch bản SAXParser là một giải pháp tốt đẹp.

Here là hướng dẫn hay về JAXB.

3

Tôi sử dụng Apache CXF để xây dựng các dịch vụ RESTful của mình, một dịch vụ JAX-RS khác (nó cũng cung cấp triển khai JAX-WS). Tôi cũng sử dụng lớp "org.apache.cxf.jaxrs.client.WebClient" của nó trong các bài kiểm tra đơn vị, điều này sẽ quản lý hoàn toàn tất cả các marshalling và unmarshalling dưới bìa. Bạn cung cấp cho nó một URL và yêu cầu một đối tượng của một loại cụ thể, và nó làm tất cả các công việc. Tôi không biết liệu Jersey có cơ sở tương tự hay không.

1

Nếu bạn cũng cần phải chuyển đổi mà chuỗi xml mà đến như là một phản ứng với các cuộc gọi dịch vụ, một đối tượng x bạn cần có thể làm điều đó như sau:

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.io.StringReader; 
import java.net.HttpURLConnection; 
import java.net.MalformedURLException; 
import java.net.URL; 
import java.util.ArrayList; 
import java.util.List; 

import javax.xml.bind.JAXB; 
import javax.xml.bind.JAXBException; 
import javax.xml.parsers.DocumentBuilder; 
import javax.xml.parsers.DocumentBuilderFactory; 
import javax.xml.parsers.ParserConfigurationException; 

import org.w3c.dom.CharacterData; 
import org.w3c.dom.Document; 
import org.w3c.dom.Element; 
import org.w3c.dom.Node; 
import org.w3c.dom.NodeList; 
import org.xml.sax.InputSource; 
import org.xml.sax.SAXException; 

public class RestServiceClient { 

// http://localhost:8080/RESTfulExample/json/product/get 
public static void main(String[] args) throws ParserConfigurationException, 
    SAXException { 

try { 

    URL url = new URL(
     "http://localhost:8080/CustomerDB/webresources/co.com.mazf.ciudad"); 
    HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
    conn.setRequestMethod("GET"); 
    conn.setRequestProperty("Accept", "application/xml"); 

    if (conn.getResponseCode() != 200) { 
    throw new RuntimeException("Failed : HTTP error code : " 
     + conn.getResponseCode()); 
    } 

    BufferedReader br = new BufferedReader(new InputStreamReader(
     (conn.getInputStream()))); 

    String output; 

    Ciudades ciudades = new Ciudades(); 
    System.out.println("Output from Server .... \n"); 
    while ((output = br.readLine()) != null) { 
    System.out.println("12132312"); 
    System.err.println(output); 

    DocumentBuilder db = DocumentBuilderFactory.newInstance() 
     .newDocumentBuilder(); 
    InputSource is = new InputSource(); 
    is.setCharacterStream(new StringReader(output)); 

    Document doc = db.parse(is); 
    NodeList nodes = ((org.w3c.dom.Document) doc) 
     .getElementsByTagName("ciudad"); 

    for (int i = 0; i < nodes.getLength(); i++) { 
     Ciudad ciudad = new Ciudad(); 
     Element element = (Element) nodes.item(i); 

     NodeList name = element.getElementsByTagName("idCiudad"); 
     Element element2 = (Element) name.item(0); 

     ciudad.setIdCiudad(Integer 
      .valueOf(getCharacterDataFromElement(element2))); 

     NodeList title = element.getElementsByTagName("nomCiudad"); 
     element2 = (Element) title.item(0); 

     ciudad.setNombre(getCharacterDataFromElement(element2)); 

     ciudades.getPartnerAccount().add(ciudad); 
    } 
    } 

    for (Ciudad ciudad1 : ciudades.getPartnerAccount()) { 
    System.out.println(ciudad1.getIdCiudad()); 
    System.out.println(ciudad1.getNombre()); 
    } 

    conn.disconnect(); 

} catch (MalformedURLException e) { 
    e.printStackTrace(); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 
} 

public static String getCharacterDataFromElement(Element e) { 
Node child = e.getFirstChild(); 
if (child instanceof CharacterData) { 
    CharacterData cd = (CharacterData) child; 
    return cd.getData(); 
} 
return ""; 
} 

}

Lưu ý rằng cấu trúc xml mà tôi mong đợi trong ví dụ này là như sau:

<ciudad><idCiudad>1</idCiudad><nomCiudad>BOGOTA</nomCiudad></ciudad>  
Các vấn đề liên quan