Retrofit 2处理不仅限于XML或Json响应的情况

huangapple go评论57阅读模式
英文:

Retrofit 2 working with response that is not always XML or Json

问题

我正在构建一个Android应用程序,应该读取服务器响应并处理数据。

作为用户,我能够控制是否获得XML或Json类型的响应。然而,在某些情况下,数据可能不是XML或Json格式,而是原始的HTML格式,这就是我遇到困难的地方。

目前我正在处理XML格式的响应。我现在正在使用HttpUrlConnection,其中我获得响应作为字符串。然后,我在响应字符串中使用 <?xml version="1.0" encoding="utf-8"?> 并在其中查找它。如果找到它,那么我知道请求成功了,我得到了所需的响应,所以我继续解析和处理数据;如果未找到它,那么我只显示一个错误,就是这样。

现在,我正在尝试切换到Retrofit 2以及它的转换器,我已经成功地使用SimpleXML进行了实现,我能够解析我收到的XML数据,但是一旦我得到HTML数据,应用程序就会崩溃,因为它无法用XML解析器解析HTML,这是可以理解的。

因此,我的问题是:

  1. 有没有处理这种情况的方法?
  2. 是否有可能用Retrofit获得字符串响应?如果是这样,通过Retrofit进行相同的过程是否有任何优势,而不是使用HttpUrlConnection?
英文:

I am building an Android app that should read the server response and process the data.

As user I am able to control whether I get XML or Json type of response. However, in certain cases, it is possible that the data will not be in either XML or Json format but raw HTML and this is where I am struggling.

At this moment I am working with XML formatted response. Right now I am using HttpUrlConnection where I get the response as String. Then, I use <?xml version="1.0" encoding="utf-8"?> and look for it in the response string. If it is found, then I know that the request was successful and I got the response that I needed so I proceed to parse and work with data and if It was not found then I just display an error and that's it.

Now, I am trying to move to Retrofit 2 with its converters and I have successfully implemented it with SimpleXML and I am able to parse the XML data that I am receiving, but as soon as I get HTML data, the app crashes because it is not able to parse HTML with XML parser, which is understandable.

So my questions are:

  1. Is there a way to deal with this?
  2. Would it be possible to get String response with Retrofit and if so, would there be any advantage to going through the same process but with Retrofit instead of HttpUrlConnection?

答案1

得分: 0

有几件事情你可以尝试:

  • 要求 Retrofit 原样返回 String 响应,并手动处理它。

  • 要求 Retrofit 返回 Object,并执行运行时的 instanceof 检查,以确定下一步的操作。

你可能还想查看这个链接

英文:

There are a couple of things you could try :-

  • Ask retrofit to return String response as is and handle it manually

  • Ask retrofit to return Object and perform runtime instanceof checks to determine your next course of action.

You might also want to look into this.

huangapple
  • 本文由 发表于 2020年10月4日 18:45:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/64193651.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定