Reading XML form URL with Retrofit 2
suggest changeWe will use retrofit 2 and SimpleXmlConverter to get xml data from url and parse to Java class.
Add dependency to Gradle script:
compile 'com.squareup.retrofit2:retrofit:2.1.0' compile 'com.squareup.retrofit2:converter-simplexml:2.1.0'
Create interface
Also create xml class wrapper in our case Rss class
public interface ApiDataInterface{ // path to xml link on web site @GET (data/read.xml) Call<Rss> getData(); }
Xml read function
private void readXmlFeed() { try { // base url - url of web site Retrofit retrofit = new Retrofit.Builder() .baseUrl(http://www.google.com/) .client(new OkHttpClient()) .addConverterFactory(SimpleXmlConverterFactory.create()) .build(); ApiDataInterface apiService = retrofit.create(ApiDataInterface.class); Call<Rss> call = apiService.getData(); call.enqueue(new Callback<Rss>() { @Override public void onResponse(Call<Rss> call, Response<Rss> response) { Log.e("Response success", response.message()); } @Override public void onFailure(Call<Rss> call, Throwable t) { Log.e("Response fail", t.getMessage()); } }); } catch (Exception e) { Log.e("Exception", e.getMessage()); } }
This is example of Java class with SimpleXML annotations
More about annotations SimpleXmlDocumentation
@Root (name = "rss") public class Rss { public Rss() { } public Rss(String title, String description, String link, List<Item> item, String language) { this.title = title; this.description = description; this.link = link; this.item = item; this.language = language; } @Element (name = "title") private String title; @Element(name = "description") private String description; @Element(name = "link") private String link; @ElementList (entry="item", inline=true) private List<Item> item; @Element(name = "language") private String language;
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents