使用JAXB解析响应XML

bmw*_*128 6 java xml jaxb

我想阅读使用JAXB的非wsdl Web服务调用的响应.我正在使用HttpURLConnection发送POST请求,并获得响应.我的问题是我是否从响应流中创建了一个xml doc,然后使用jaxb来创建java对象?或者,是否可以使用响应流动态使用jaxb?这将是一个Web应用程序,我将无法在任何地方存储生成的xml文档,所以如果我需要创建一个xml doc,如何在jaxb中存储它以供使用,如果我不能在运行中执行jaxb ?

bdo*_*han 7

这是一个例子:

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();
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅


sbl*_*ndy 3

可以Unmarshaller.unmarshal采用 InputStream,这样就无需将其解析为 XML 文档。