UPDATERESTful WebService使用XML,如何調用它?
我幾乎能完成我的REST風格的溝通,雖然我有剩下的問題:
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 - 下面結果類是有效的XML輸出,考慮到最後的代碼示例(Web服務)?
conn.setDoOutput(true);
OutputStream output = conn.getOutputStream();
// And write your xml to output stream.
檢查此鏈接使用REST標準:
類使用REST風格
@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);
}
}
Web服務
@GET
@Path("/byAccount")
@Consumes("application/xml")
@Produces("application/xml")
public Person getByAccount(Account account) {
// business logic
return person;
}
我確實看到了使用InputStream和OutputStream很多例子。雖然,在上面的情況(更新我的問題),我不知道如何使它的工作。我該如何解決這種情況?感謝您一直以來的幫助! – Aquillo
@Aquillo,我已經更新了我的回答 –
感謝Nikita! 該解決方案簡化了我的代碼,並做得很好。 – Aquillo