使用 Retrofit 2 读取 XML 表单 URL
我们将使用 retrofit 2 和 SimpleXmlConverter 从 url 获取 xml 数据并解析为 Java 类。
向 Gradle 脚本添加依赖项:
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-simplexml:2.1.0'
创建界面
在我们的 Rss 类中创建 xml 类包装器
public interface ApiDataInterface{
// path to xml link on web site
@GET (data/read.xml)
Call<Rss> getData();
}
Xml 读取功能
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());
}
}
这是带有 SimpleXML 注释的 Java 类的示例
有关注释 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;