Handle the XML Response from HTTP Request using Retrofit.

Updated 26 October 2021

Save

In this blog, we will learn how to handle the XML Response from HTTP request using Retrofit.

Well, we all want to make our apps faster. In order to do the same, we try to use the fastest networking library.
Currently, Retrofit2 is one of the fastest networking libraries and the main advantage of using Retrofit in Android Programming is that you don’t have to traverse the whole response all by yourself to create an object and then use it.

The retrofit does this for us and all we need to do is to tell the Retrofit call that how the response object would be.

If you are new to Retrofit2, you should read  these two articles :

Using Retrofit library to make Http Requests

Using Retrofit library to make Http Requests

After getting the basic introduction to the Retrofit, the question is what if you receive the response in XML and not in JSON.

APPROACH :

The Retrofit object will look into the converter Factory applicable to the response received and will convert it to the object automatically.

All you need to do is to set the correct Converter Factory in your retrofit Object.

If you are sure about getting only one type of the response from all the APIs then you need to add only one converter Factory, but  if you are not exactly sure or some of your requests return JSON and some of your requests return XML, then you need to add two converter Factories in your retrofit Object.

And then create a model object class.On the declaration

On the declaration of the class, add a Root annotation with the tag name in which you will receive your data.
And on each Element, add the Element Annotation with the name of the element.

Create the getters and setters to access the data from your model.

CODE:

The Retrofit Object :

That’s it the above code will apply both the converter factories as applicable and feasible to the response.

EXAMPLE XML OBJECT CLASS :

EXAMPLE GSON OBJECT CLASS :

That’s all you need to do in your code and the retrofit will automatically build the object and allocate the variables according to the response received.

Keep coding and Keep Sharing.

author
. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


2 comments

  • Pushpendra Singh
    • anchit (Moderator)
  • Start a Project


      Message Sent!

      If you have more details or questions, you can reply to the received confirmation email.

      Back to Home