繁体   English   中英

如何用Java对HTTP POST请求反序列化XML结果?

[英]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是一个很好的简单选择:

http://x-stream.github.io/

诚然,所有这些都是更多的代码,但这是.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: MetroEclipseLink 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM