2011-08-24 88 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>