2

In C#, I make an http post and get an xml in the response in the form of a byte array (bret), which I deserialize into a class easily:

MemoryStream m = new MemoryStream(bret);
XmlSerializer s = new XmlSerializer(typeof(TransactionResults));
TransactionResults t = (TransactionResults)s.Deserialize(m);

What would be the correct and easiest way to do the same in Java?

bdoughan
  • 147,609
  • 23
  • 300
  • 400
juan
  • 80,295
  • 52
  • 162
  • 195

4 Answers4

1

Make your POST request via something like

http://www.exampledepot.com/egs/java.net/post.html

or use HttpClient:

http://hc.apache.org/httpclient-3.x/methods/post.html

Depending on how you have serialized your data, you should use a corresponding de-serializer. XStream is a good simple choice for such tasks:

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

All of this is admittedly more code, but this is a typical tradeoff of .NET vs Java systems (although it's more code, there are advantages to Java).

facundofarias
  • 2,973
  • 28
  • 27
kvista
  • 5,039
  • 1
  • 23
  • 25
0

Using X-Stream - for a get request :

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);

You can modify the call to url for a post.

Joel
  • 29,538
  • 35
  • 110
  • 138
0

JAXB is the Java standard (JSR-222) for converting objects to XML with multiple implementations: Metro, EclipseLink MOXy (I'm the tech lead), Apache JaxMe.

The HTTP operations can be accessed in Java using code like:

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();

The above code sample is from:

For a comparsion of JAXB and XStream see:

bdoughan
  • 147,609
  • 23
  • 300
  • 400
0

If you don't want to map your result into classes, you might want to check out Resty. It makes accessing JSON, XML or any other data type a one-liner. Here is code that parses the Slashdot RSS as XML and prints all the linked articles.

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"));
}
Jochen Bedersdorfer
  • 4,093
  • 24
  • 26