android - 如何在没有 api 密钥的情况下使用改造调用 REST api 并将其呈现在 Android 的列表视图中?
问题描述
REST API 是“ http://citywall.in/category.php ”
代码的O/P:
{
"category": [{
"id": "1",
"name": "Recipe",
"image": "receipe.jpg",
"createdDate": "2019-03-27 00:00:00"
}, {
"id": "2",
"name": "Gardening",
"image": "gardening.jpg",
"createdDate": "2019-03-27 00:00:00"
}, {
"id": "3",
"name": "Services",
"image": "services.jpg",
"createdDate": "2019-03-27 00:00:00"
}, {
"id": "4",
"name": "Tourism",
"image": "tourism.jpg",
"createdDate": "2019-03-27 00:00:00"
}, {
"id": "5",
"name": "Lifestyle",
"image": "lifestyle.jpg",
"createdDate": "2019-03-27 00:00:00"
}, {
"id": "6",
"name": "Other",
"image": "other.jpg",
"createdDate": "2019-03-27 00:00:00"
}]
}
解决方案
你需要实例化改造的拳头:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://citywall.in/")
.build();
然后你应该Category
为类别列表中的每个项目创建和接口对应的类:
public interface CategoryServiceInterface{
@Get("/category.php")
Call<Response> getCategoryList();
}
Response
类是一个数据类:
public class Response{
@SerializedName("category")
private List<Category> categoryList = new ArrayList()
/**
Getters and setters....
*/
}
public class Category{
@SerializedName("id")
private String id;
@SerializedName("name")
private String name;
@SerializedName("image")
private String imageName;
@SerializedName("createdDate")
private Date createdDate;
/**
Getters and setters....
*/
}
现在你有了所有的基本知识。只需拨打以下电话:
CategoryServiceInterface service = retrofit.create(CategoryServiceInterface.class)
Response response = service.getCategoryList().body()
现在你有数据模型需要出现在 android 列表中。有关更多详细信息,请参阅以下链接: https ://square.github.io/retrofit/