[英]RESTful WebService consumes XML,how to call it?
UPDATE
我几乎能够完成我的RESTful通信,但我还有其他问题:
1 - 如何将XML分配给连接(下面的代码将举例说明我的情况)?
调用Web服务
public Person getByAccount(Account account) {
URL url = new URL(uri);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/xml");
XStream xstream = new XStream();
String xmlIn = xstream.toXML(account);
// Put the xmlIn into the connection
BufferedReader br = new BufferedReader(new InputStreamReader(
(connection.getInputStream())));
StringBuilder sb = new StringBuilder();
String line;
while((line = br.readLine()) != null)
sb.append(line);
String xmlOut = sb.toString();
connection.disconnect();
return (Person) xstream.fromXML(xmlOut);
}
2 - 考虑到最后一个代码示例(Web服务),下面的类是否会产生有效的XML输出?
要使用RESTful发送的类
@XmlRootElement(name="people")
public class People {
@XmlElement(name="person")
public List<Person> people;
public People() {
people.add(new Person(1, "Jan"));
people.add(new Person(2, "Hans"));
people.add(new Person(3, "Sjaak"));
}
public List<Person> all() {
return people;
}
public Person byName(String name) {
for(Person person : people)
if(person.name.equals(name))
return person;
return null;
}
public void add(Person person) {
people.add(person);
}
public Person update(Person person) {
for(int i = 0; i < people.size(); i++)
if(person.id == people.get(i).id) {
people.set(i, person);
return person;
}
return null;
}
public void remove(Person person) {
people.remove(person);
}
}
网络服务
@GET
@Path("/byAccount")
@Consumes("application/xml")
@Produces("application/xml")
public Person getByAccount(Account account) {
// business logic
return person;
}
试试这个:
conn.setDoOutput(true);
OutputStream output = conn.getOutputStream();
// And write your xml to output stream.
检查此链接是否使用带有标准URL
REST: http : //rest.elkstein.org/2008/02/using-rest-in-java.html
编辑
首先,您需要将getByAccount
请求更改为POST
请求,因为GET
请求不允许传递正文中的任何信息,它只使用url中的请求参数。 但是你发送XML,所以使用POST
。
尝试以下版本的send方法:
public Person getByAccount(Account account) {
URL url = new URL(uri);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept", "application/xml");
connection.setOutput(true);
XStream xstream = new XStream();
xstream.toXML(account, connection.getOutputStream());
Person person = (Person) xstream.fromXML(connection.getInputStream());
connection.disconnect();
return person;
}
对于大多数足够的调用,您可以使用Jersey Client API (另外一个链接 )。
你可以尝试Spring 3 RestTemplate
。 很容易上手,非常强大。
更多信息: http : //blog.springsource.org/2009/03/27/rest-in-spring-3-resttemplate/
http://www.baeldung.com/2012/04/16/how-to-use-resttemplate-with-basic-authentication-in-spring-3-1/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.