This post is all about how to integrate an XML converter with Retrofit. Before we go on, let's have a look at the other articles in the series of Retrofit posts.
Retrofit Series Overview
- Getting Started and Creating an Android Client
- Basics of API Description
- Creating a Sustainable Android Client
- URL Handling, Resolution and Parsing
- How to Change API Base Url at Runtime
- Multiple Server Environments (Develop, Staging, Production)
- Share OkHttp Client and Converters between Retrofit Instances
- Upgrade Guide from 1.9
- Beyond Android: Retrofit for Java Projects
- How to use OkHttp 3 with Retrofit 1
- Synchronous and Asynchronous Requests
- Send Objects in Request Body
- Add Custom Request Header
- Manage Request Headers in OkHttp Interceptor
- Dynamic Request Headers with @HeaderMap
- Multiple Query Parameters of Same Name
- Optional Query Parameters
- Send Data Form-Urlencoded
- Send Data Form-Urlencoded Using FieldMap
- How to Add Query Parameters to Every Request
- Add Multiple Query Parameter With QueryMap
- How to Use Dynamic Urls for Requests
- Constant, Default and Logic Values for POST and PUT Requests
- Cancel Requests
- Reuse and Analyze Requests
- Optional Path Parameters
- How to Send Plain Text Request Body
- Customize Network Timeouts
- How to Trust Unsafe SSL certificates (Self-signed, Expired)
- Dynamic Endpoint-Dependent Interceptor Actions
- How to Update Objects on the Server (PUT vs. PATCH)
- How to Delete Objects on the Server
- Introduction to (Multiple) Converters
- Adding & Customizing the Gson Converter
- Implementing Custom Converters
- How to Integrate XML Converter
- Access Mapped Objects and Raw Response Payload
- Supporting JSON and XML Responses Concurrently
- Handling of Empty Server Responses with Custom Converter
- Send JSON Requests and Receive XML Responses (or vice versa)
- Unwrapping Envelope Responses with Custom Converter
- Wrapping Requests in Envelope with Custom Converter
- Define a Custom Response Converter
Define XML Converter
We assume you’re familiar with the basics of Retrofit and you know how to configure Retrofits RestAdapter
(Retrofit
in Retrofit 2). If not, please have a look at the getting started post in this series.
Here, we’ll show you how to integrate an XML converter to map HTTP responses from XML to Java objects.
Define Gradle Dependency
First stop is the build.gradle
file. The Retrofit project already has an XML converter available which you need to add to your project as a peer-dependency. Have a look at our previous post about how to create or define your custom response converter if you want to know more about existing converters for Retrofit.
Here we go, define the dependency in your build.gradle
.
Retrofit 1.9
dependencies {
// Retrofit XML converter (Simple)
compile 'com.squareup.retrofit:converter-simplexml:1.9.0'
}
Retrofit 2
dependencies {
// Retrofit XML converter (Simple)
compile 'com.squareup.retrofit2:converter-simplexml:2.5.0'
}
Once you added the dependency for the SimpleXML converter to your build.gradle
file, sync the project and wait for Android Studio to finish the process. Afterwards, proceed with the next steps described in the section below :)
XMLConverter feat. RestAdapter/Retrofit
Now, we have to define the SimpleXMLConverter
as converter for the RestAdapter
(Retrofit
in Retrofit 2).
Retrofit 1.9
RestAdapter adapter = new RestAdapter.Builder()
.setClient(new OkClient(new OkHttpClient())
.setEndpoint(yourBaseUrl)
.setConverter(new SimpleXMLConverter())
.build();
Just pass the new SimpleXMLConverter()
constructor to the .setConverter()
method to override the default converter (GSON).
Retrofit 2
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.client(new OkHttpClient())
.addConverterFactory(SimpleXmlConverterFactory.create())
.build();
The handling of response converters changed in Retrofit 2. You don’t override existing converters. That results in the possibility to define multiple converters for your Retrofit instance. Internally, Retrofit will try to parse the response with the first added converter. If that fails, it will proceed with the next one, and so on …
Objects Love Annotations
Retrofit will map your XML response to Java objects, doesn’t matter which XML converter you’re using. Therefore, we need to annotate the Java objects for correct tag to property mapping.
We’ll use the Task
class below and add annotations to map the corresponding tasks.xml
file.
tasks.xml
This XML file does not appear to have any style information associated with it. The document tree is shown below.
<rss xmlns:atom="http://www.w3.org/2005/Atom" version="2.0">
<task>
<id link="http://url-to-link.com/task-id">1</id>
<title>Retrofit XML Converter Blog Post</title>
<description>Write blog post: XML Converter with Retrofit</description>
<language>de-de</language>
</task>
</rss>
Task
@Root(name = "task")
public class Task {
@Element(name = "id")
private long id;
@Element(name = "title")
private String title;
@Element(name = "description")
private String description;
@Attribute(required = false)
private String link;
public Task() {}
}
The annotations define the element name which gets mapped to the class property. Within the example, all elements have the same name in the XML file and the Java class. For sure, you can use a different naming and just put the element name to the @Element
annotation.
That’s it. Just go ahead and make your request :)
Feel free to contact us @futurestud_io if you run into any problem. We’re happy to help.