簡體   English   中英

如何在沒有 api 密鑰的情況下使用改造調用 REST api 並將其顯示在 Android 的列表視圖中?

[英]How to call a REST api using retrofit without api key and present it in listview in 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是類別列表中每個項目對應的 Class:

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/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM