开发者

how to check if a response is in xml format instead of HTML?

开发者 https://www.devze.com 2023-03-20 23:39 出处:网络
Im working with a server which always sends me XML responds. But sometimes when server is lack or something it reports me about it by sending me back a HTML page (it just a html page informing about

Im working with a server which always sends me XML responds. But sometimes when server is lack or something it reports me about it by sending me back a HTML page (it just a html page informing about the error) but i didn't expect that and my XML parser crashed.

Im using Def开发者_高级运维aultHttpClient() and I do send header like mHttpRequest.setHeader("Accept", "text/xml");

So what is the proper way to ensure i got XML (or other specific format) response?


As Kristian suggested, see if it provides a different Content-Type when HTML is emitted. Failing that I would check for a <?xml... line, as apposed to a doctype or whatever is on the HTML page.


Can you check the content type header on the response?

Something like (if I understand the Android documentation correctly):

"text/xml".equals(httpResponse.getEntity().getContentType().getValue());


Every XML contains document descriptor <?xml version="1.0" encoding="utf-8"?> in the beginning. You can check for this before parsing it.

However, I think you need some error handling and result validation in your parser. Network is not a safe environment - you can easily get a half-broken, malformed, or even forged XML from the network. Good parser should detect that and report corresponding errors, not just crash.

0

精彩评论

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