Android:在PUT/POST之后检测一个BasicHttpResponse的XML或JSON数据类型

时间:2022-09-06 17:03:35

I need to parse the server response from my http post & puts. I originally thought all responses were going to be XML. Now I'm finding out that, for certain calls, the response I'm getting back is JSON. I have no control over the server, so changing this is not an option.

我需要解析来自http post & put的服务器响应。我最初认为所有的响应都是XML。现在我发现,对于某些调用,我得到的响应是JSON。我对服务器没有控制权,所以更改这不是一个选项。

So,I need to decide the best way to detect the data type coming back from the server. My first thought would be to attempt to parse the response as a JSON. If a JSONException is thrown, assume it is XML.

因此,我需要确定检测从服务器返回的数据类型的最佳方式。我的第一个想法是尝试将响应解析为JSON。如果抛出一个JSONException,假设它是XML。

Since I have no control over the server, I'm not sure I can count on the headers being correct.

由于我对服务器没有控制权,所以我不确定我是否可以相信标题是正确的。

Does anyone have any thoughts on the best approach?

有人对最好的方法有什么想法吗?

2 个解决方案

#1


2  

Just look at the content-type header in the html response. If the server is working properly, that should tell you want type of content you're getting.

看看html响应中的内容类型头。如果服务器运行正常,那么应该告诉您需要的内容类型。

#2


0  

As I had stated in my question, I had no control over the server and could not count on it to be set up correctly and/or be passing the appropriate headers. Otherwise, this would have been the obvious answer.

正如我在我的问题中陈述的那样,我无法控制服务器,不能指望它正确地设置和/或传递适当的头信息。否则,这将是显而易见的答案。

My original idea is what ended up working best:

我最初的想法是什么最有效:

"My first thought would be to attempt to parse the response as a JSON. If a JSONException is thrown, assume it is XML."

我的第一个想法是尝试将响应解析为JSON。如果抛出JSONException,假设它是XML。

#1


2  

Just look at the content-type header in the html response. If the server is working properly, that should tell you want type of content you're getting.

看看html响应中的内容类型头。如果服务器运行正常,那么应该告诉您需要的内容类型。

#2


0  

As I had stated in my question, I had no control over the server and could not count on it to be set up correctly and/or be passing the appropriate headers. Otherwise, this would have been the obvious answer.

正如我在我的问题中陈述的那样,我无法控制服务器,不能指望它正确地设置和/或传递适当的头信息。否则,这将是显而易见的答案。

My original idea is what ended up working best:

我最初的想法是什么最有效:

"My first thought would be to attempt to parse the response as a JSON. If a JSONException is thrown, assume it is XML."

我的第一个想法是尝试将响应解析为JSON。如果抛出JSONException,假设它是XML。