I want to read a response from a non-wsdl web service call using JAXB. I am sending a POST request using HttpURLConnection, and getting a response. My question is do I make an xml doc from the response stream, then use jaxb to make the java objects? Or, is it possible to use use jaxb on the fly with the response stream? This will be a web application, and I will not be able to store a generated xml doc anywhere, so if i need to make an xml doc, how do i store it for jaxb to use, if I cannot do the jaxb on the fly?
JAXB — Java Architecture for XML Binding — is used to convert objects from/to XML. JAXB offers a fast and suitable way to marshal (write) Java objects into XML and unmarshal (read) XML into Java objects. It supports Java annotations to map XML elements to Java attributes.
To read XML, first get the JAXBContext . It is entry point to the JAXB API and provides methods to unmarshal, marshal and validate operations. Now get the Unmarshaller instance from JAXBContext . It's unmarshal() method unmarshal XML data from the specified XML and return the resulting content tree.
DOM Parser is the easiest java xml parser to learn. DOM parser loads the XML file into memory and we can traverse it node by node to parse the XML. DOM Parser is good for small files but when file size increases it performs slow and consumes more memory.
Here is an example:
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();
For more information see:
The Unmarshaller.unmarshal
can take an InputStream, which would eliminated the need to parse it to an XML doc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With