How to call simple GET method using “Retrofit”

自古美人都是妖i 提交于 2019-12-02 17:39:05

Retrofit gives you the option of synchronous and asynchronous. Depending on how you declare your interface method, it will either be synchronous or asynchronous.

public interface MyInterface {
    // Synchronous declaration
    @GET("/my_api/shop_list") 
    Response getMyThing1(@Query("mid") String param1);

    // Asynchronous declaration
    @GET("/my_api/shop_list")
    void getMyThing2(@Query("mid") String param1, Callback<Response> callback);
}

If you declare your API synchronously then you'll responsible of executing it in a Thread.

Please read the "SYNCHRONOUS VS. ASYNCHRONOUS VS. OBSERVABLE" section on Retrofit's website. This will explain to you the basics on how to declare your APIs for your different needs.

The simplest way of getting access to your JSON class object is to map it to a Java object and let Retrofit do the conversion for you.

If for example the returned JSON for your rest api was

[{"id":1, "name":"item1"}, {"id":2, "name":"item2"}]

Then you could create a Java classes like so

public class Item {
    public final int id;
    public final String name;

    public Item(int id, String name) {
        this.id = id;
        this.name = name;
    }
}

Then simply declare your api like so

@GET("/my_api/shop_list")
void getMyThing(@Query("mid") String param1, Callback<List<Item>> callback);  // Asynchronous

And use it

api.getMyThing("your_param_here", new Callback<List<Item>>() {
        @Override
        public void success(List<Item> shopList, Response response) {
            // accecss the items from you shop list here
        }

        @Override
        public void failure(RetrofitError error) {

        }
    });

Based on the JSON you've provided in the comments you would have do to something like this

public class MyThingResponse {
    public InnerResponse response;
}

public class InnerResponse {
    public String message;
    public String status;
    public List<Item> shop_list;
}

This is kind of ugly but it's because of the JSON. My recommendation would be to simplify your JSON by removing the "response" inner object if you can, like so

{
    "message": "Shops shown",
    "status": 1,
    "shop_list": [
        {
            "id": "1",
            "city_id": "1",
            "city_name": "cbe",
            "store_name": "s"
        }
    ]
}

Then your POJO could then become simpler like so

public class MyThingResponse {
    public String message;
    public String status;
    public List<Item> shop_list;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!