我刚开始使用 Retrofit。我正在开发一个使用 SimpleXML 的项目。谁能给我一个例子,从一个站点例如http://www.w3schools.com/xml/simple.xml获取一个 XML并读出来?
问问题
22769 次
3 回答
52
您将在项目中创建一个接口作为新类:
public interface ApiService {
@GET("/xml/simple.xml")
YourObject getUser();
}
然后在您的活动中,您将调用以下内容:
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint("http://www.w3schools.com")
.setConverter(new SimpleXmlConverter())
.build();
ApiService apiService = restAdapter.create(ApiService.class);
YourObject object = apiService.getXML();
要正确获取您的库,您需要在 build.gradle 文件中执行以下操作:
configurations {
compile.exclude group: 'stax'
compile.exclude group: 'xpp3'
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.squareup.retrofit:retrofit:1.6.1'
compile 'com.mobprofs:retrofit-simplexmlconverter:1.1'
compile 'org.simpleframework:simple-xml:2.7.1'
compile 'com.google.code.gson:gson:2.2.4'
}
然后需要根据xml文件的结构指定YourObject并为其添加注解
@Root(name = "breakfast_menu")
public class BreakFastMenu {
@ElementList(inline = true)
List<Food> foodList;
}
@Root(name="food")
public class Food {
@Element(name = "name")
String name;
@Element(name = "price")
String price;
@Element(name = "description")
String description;
@Element(name = "calories")
String calories;
}
于 2014-08-19T13:35:13.390 回答
2
import java.util.ArrayList;
import java.util.List;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
@Root(name = "breakfast_menu")
public class BrakfastMenu
{
@ElementList(inline = true)
protected List<Food> food;
public List<Food> getConfigurations()
{
if (food == null)
{
food = new ArrayList<Food>();
}
return this.food;
}
public void setConfigurations(List<Food> configuration)
{
this.food = configuration;
}
}
于 2014-08-19T13:39:56.233 回答
1
这是使用Retrofit 2的方法。
首先,您需要一个接口,例如(标题注释是可选的):
public interface ApiService
{
@GET("xml/simple.xml")
@Headers({"Accept: application/xml",
"User-Agent: Retrofit-Sample-App"})
Call<BreakfastMenu> getBreakfastMenu();
}
XML 的带注释的 POJO 与其他答案中的相同。
然后你需要向服务器发出请求:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://www.w3schools.com/")
.addConverterFactory(SimpleXmlConverterFactory.create())
.build();
ApiService apiService = retrofit.create(ApiService.class);
Call<BreakfastMenu> call = apiService.getBreakfastMenu();
Response<BreakfastMenu> response = call.execute();
// response.code() == 200
BreakfastMenu breakfastMenu = response.body();
所需的库是:
- 改造 2.3.0
- 好的http 3.8.0
- 转换器-simplexml 2.3.0
- 简单的 xml 2.7.1
- 爪哇 7
于 2017-11-16T14:14:47.477 回答