更新
我几乎能够完成我的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;
}
答案 0 :(得分:4)
试试这个:
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
请求不允许在正文中传递任何信息,它只使用请求参数网址。但是您发送XML,因此请使用POST
。
尝试以下版本的发送方法:
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;
}
答案 1 :(得分:1)
您可以使用Jersey Client API,(one more link)进行最充分的通话。
答案 2 :(得分:0)
您可以尝试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/