从Java调用Restful Service
在这里,我并不是在创建RESTful服务,实际上我必须从Java代码中调用外部Restful服务。目前,我正在使用Apache
HttpClient实现此功能。我从Web服务获得的响应是XML格式。我需要从XML提取数据并将其放在Java对象上。听说不是使用SAX解析器,而是可以使用JAX-
RS和JERSEY来自动将xml标记映射到相应的Java对象。
我一直在浏览,但是找不到开始使用的资源。我确实查看了现有链接 使用Java中的Java
RESTful调用消耗RESTful API
感谢您提供任何帮助。
谢谢!!
回答:
跟进此:我可以这样吗?如果xml返回为4
......如果我正在构造一个Person对象,我相信这会阻塞。我可以只绑定我想要的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>
以下是使用包括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
以上是 从Java调用Restful Service 的全部内容, 来源链接: utcz.com/qa/405589.html