开发者

Handling different XML response documents with one SAX Handler

开发者 https://www.devze.com 2023-01-20 20:34 出处:网络
I am developing a Java application that makes an HTTP Request to a web service, and XML is returned. If the response code is 200, then a requestSucceeded() callback method will send the XML to a SAXPa

I am developing a Java application that makes an HTTP Request to a web service, and XML is returned. If the response code is 200, then a requestSucceeded() callback method will send the XML to a SAXParser with a different SAX Handler, depending on what web service is being called. If the respons开发者_JAVA百科e code is not 200, then a requestFailed() callback method is being called.

The web service that I am calling will return two types of XML documents (with a response code of 200): an XML document containing the successful response information, or an XML error document containing error information (for example, if one of the request parameters wasn't formatted correctly).

My question is this: Given my current setup, what is the best way to look for / handle both kinds of XML documents (a successful XML response or an XML error document)? The SAX Handler is looking for all of the relevant response information and it is storing that information into an object, which is then processed by my application. Is there a better solution than just always first looking for the unique XML Error tags?

Thanks!


Option #1 - Change Respose Code

Why are you returning an error with response code 200? 400 (Bad Request) or another error code might be a better option. Then you could process the XML based on the response code.

Option #2 - Swap Content Handlers

Below is a link to one of my previous answers where I explain how to swap content handlers while processing the document. You could have one content handler that determines if the response is content or error, and then swaps in the appropriate content handler to process the rest.

  • Using SAX to parse common XML elements

Option #3 - Use JAXB

If the end result is that the XML will be converted to an object, have you considered using JAXB? It will build an object based on the XML based on what is returned.

0

精彩评论

暂无评论...
验证码 换一张
取 消