I am new to Groovy and I am trying to parse both a valid rest resource and an invalid one. For example:
this code works fine -
def entity = new XmlSlurper().parse('http://api.twitter.com/1/users/show/slashdot.xml')
println entity.name()
println entity.screen_name.text()
user
slashdot
def entity = new XmlSlurper().parse('http://api.twitter.com/1/users/show/slashdotabc.xml')
println entity.name()
println entity.screen_name.text(
I get this error message:
Caught: java.io.FileNotFoundException: http://api.twitter.com/1/users/show/slashdotabc.xml
at xmltest.run(xmltest.groovy:1)
Although the url returns an hash code (like below) with an error message which I would like to parse and display it.
<hash>
<request>/1/users/show/slashdotabc.xml</request>
<error>Not found</error>
</hash>
How can I parse a url which returns a 404 but with error information?
Any help will be appreciated.
-- Thanks & Regards, Frank Covert
The response you want to see is available on the URL connection's errorStream instead of the inputStream. Fortunately, given the InputStream, XmlSlurper.parse can read an InputStream as well.
Here's a sample to switch to reading the errorStream when you don't get a 200 status:
def con = new URL("http://api.twitter.com/1/users/show/slashdotaxxxbc.xml").openConnection()
def xml = new XmlSlurper().parse(con.responseCode == 200 ? con.inputStream : con.errorStream)
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