Android 如何使用“改造”调用简单的 GET 方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25381710/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 09:23:39  来源:igfitidea点击:

How to call simple GET method using "Retrofit"

androidgetretrofit

提问by Rethinavel

It would be nice if you help me to call a simple API GET method using Retrofit. I have added the Gson and Retrofit jar file to the build path.

如果您能帮我使用 Retrofit 调用一个简单的 API GET 方法,那就太好了。我已将 Gson 和 Retrofit jar 文件添加到构建路径中。

Here is the interface:

这是interface

  public interface MyInterface {
        @GET("/my_api/shop_list")
        Response getMyThing(@Query("mid") String param1);
    }

I am getting results only (in log cat) if i call the following in AsyncTask else i am getting NetworkOrMainThreadExceptionHow should i call this?

如果我在 AsyncTask 中调用以下内容,我只会得到结果(在 log cat 中),否则我会得到NetworkOrMainThreadException我应该如何称呼它?

@Override
    protected Void doInBackground(Void... params) {
        // TODO Auto-generated method stub

        RestAdapter restAdapter = new RestAdapter.Builder()
                .setEndpoint("http://IP:Port/")
                .setLogLevel(RestAdapter.LogLevel.FULL).build();
        MyInterface service = restAdapter
                .create(MyInterface.class);
        mResponse = service.getMyThing("455744");

        return null;
    }
  • Do i really have to call the Restadapter in AsyncTask?
  • How can i get the JsonObject from the response?
  • 我真的必须在 AsyncTask 中调用重新适配器吗?
  • 如何从响应中获取 JsonObject?

回答by Miguel Lavigne

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

Retrofit 为您提供同步和异步选项。根据您声明接口方法的方式,它可以是同步的或异步的。

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.

如果您同步声明您的 API,那么您将负责在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.

请阅读 Retrofit网站上的“SYNCHRONOUS VS. ASYNCHRONOUS VS. OBSERVABLE”部分。这将向您解释如何为您的不同需求声明 API 的基础知识。

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.

访问 JSON 类对象的最简单方法是将其映射到 Java 对象,并让 Retrofit 为您进行转换。

If for example the returned JSON for your rest api was

例如,如果您的休息 api 返回的 JSON 是

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

Then you could create a Javaclasses like so

然后你可以Java像这样创建一个类

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

然后简单地像这样声明你的api

@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

根据您在评论中提供的 JSON,您必须对这样的事情做

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

这有点难看,但这是因为 JSON。我的建议是通过删除“响应”内部对象来简化您的 JSON,如果可以的话,就像这样

{
    "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

那么你的 POJO 就可以像这样变得更简单了

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