从Java调用Restful Service

从Java调用Restful Service,第1张

从Java调用Restful Service

更新

跟进此:我可以这样吗?如果xml返回为4
......如果我正在构造一个Person对象,我相信这会阻塞。我可以只绑定我想要的xml元素吗?如果是,我该怎么做。

您可以按以下方式映射此XML:

input.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>

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

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

演示版

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>

原始答案

以下是使用包括JAXB的Java SE API调用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();

想要查询更多的信息:

  • http://blog.bdoughan.com/2010/08/creating-restful-web-service-part-55.html


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5616206.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存