[英]How to deserialize XML result from a HTTP POST request in Java?
在C#中,我發布了一個http帖子,並以字節數組(bret)的形式在響應中獲取了一個xml,我可以很容易地將其反序列化為一個類:
MemoryStream m = new MemoryStream(bret);
XmlSerializer s = new XmlSerializer(typeof(TransactionResults));
TransactionResults t = (TransactionResults)s.Deserialize(m);
在Java中執行相同操作的正確,最簡單的方法是什么?
通過類似的方式發出POST請求
http://www.exampledepot.com/egs/java.net/post.html
或使用HttpClient:
http://hc.apache.org/httpclient-3.x/methods/post.html
根據數據序列化的方式,應使用相應的反序列化器。 對於此類任務,XStream是一個很好的簡單選擇:
誠然,所有這些都是更多的代碼,但這是.NET與Java系統之間的典型折衷(盡管代碼更多,但Java有很多優點)。
使用X-Stream-獲取請求:
XStream xstream = new XStream(new DomDriver());
xstream.alias("person", Person.class);
URL url = new URL("www.foo.bar/person/name/foobar");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
Person foobar = (Person) xstream.fromXML(in);
您可以將調用修改為帖子的 url。
JAXB是Java標准 ( JSR-222 ),用於通過多種實現將對象轉換為XML: Metro , EclipseLink MOXy (我是技術負責人), Apache JaxMe 。
可以使用以下代碼在Java中訪問HTTP操作:
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();
上面的代碼示例來自:
有關JAXB和XStream的比較,請參見:
如果您不想將結果映射到類中,則可能要檢查Resty 。 它使訪問JSON,XML或任何其他數據類型成為一種形式。 這是將Slashdot RSS解析為XML並打印所有鏈接文章的代碼。
Resty r = new Resty();
NodeList nl = r.xml("http://rss.slashdot.org/Slashdot/slashdotGamesatom").get("feed/entry/link");
for (int i = 0, len = nl.getLength(); i < len; i++) {
System.out.println(((Element)nl.item(i)).getAttribute("href"));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.