2011-08-24 87 views
15

這裏我沒有創建一個RESTful服務,的確我必須從我的java代碼調用一個外部Restful服務。目前我正在使用Apache HttpClient來實現這一點。 我從Web服務獲得的響應是​​XML格式。 我需要從XML中提取數據並將它們放在Java對象上。 我聽說我們可以使用JAX-RS和JERSEY自動將xml標籤映射到相應的java對象,而不是使用SAX解析器。從Java調用Restful服務

我正在瀏覽但無法找到來源開始。 我也看一下現有的鏈接 Consuming RESTful APIs using Java RESTful call in Java

任何幫助,在前進的讚賞。

謝謝!

+0

如果你可以調用服務,並得到回JSON相反,GSON /傑克遜蜜蜂比JAXB更容易,因爲你並不需要在模型上標註對象 – Kevin

+0

嗨凱文,我有一個外部REST服務我想從Web應用程序調用它。什麼是最好的方式來做到這一點? REST服務返回JSON格式作爲響應。你說這很容易處理JSON響應。你能解釋一下嗎? – Jignesh

回答

16

UPDATE

爲跟進這樣的:我能做到這樣?如果xml被返回 as 4 ..... 如果我正在構造一個Person對象,我相信這會窒息。 我可以只綁定我想要的xml元素嗎?如果是的,我該怎麼做 那。

輸入:

如下您可以映射此XML。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> 

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; 

} 

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; 

} 

演示

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); 
    } 

} 

輸出

<?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> 

原來的答案

下面是調用使用Java SE API,其中包括JAXB RESTful服務的一個示例:

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(); 

欲瞭解更多信息:

+1

作爲跟進:我可以這樣做嗎?? 如果如果我構建Person對象的XML返回爲 4 ..... ,我相信這會窒息。 我可以只綁定我想要的xml元素嗎?如果是的我該怎麼做。 – Rishi

6

JAX-RS是Java API來RESTful Web服務。 Jersey是sun/oracle的一個實現。

您需要jaxb將您的xml轉換爲POJO。但並非總是如此,轉換後的對象可以在沒有任何轉換的情況下使用。如果這是場景SAXParser是一個不錯的解決方案。

Here是一個很好的JAXB教程。

3

我使用Apache CXF構建我的RESTful服務,這是另一個JAX-RS實現(它也提供了JAX-WS實現)。我還在單元測試中使用它的「org.apache.cxf.jaxrs.client.WebClient」類,它將完全管理所有封裝下的編組和解組。你給它一個URL並要求一個特定類型的對象,它完成所有的工作。我不知道澤西島是否有類似的設施。

1

如果您還需要自帶作爲服務調用的響應是XML字符串轉換,你需要如下能做到這一點的x對象:

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 ""; 
} 

}

注意,我預期的例子中的XML結構如下:

<ciudad><idCiudad>1</idCiudad><nomCiudad>BOGOTA</nomCiudad></ciudad>