Retrofit簡(jiǎn)單使用三

接口
http://fy.iciba.com/ajax.php?a=fy&f=auto&t=auto&w=hello%20world

Retrofit在使用的過程中是支持泛型的,使用泛型可以簡(jiǎn)化代碼,避免不必要的數(shù)據(jù)解析
在前面的兩個(gè)例子中,使用的都是ResponseBody,關(guān)于泛型的使用其實(shí)就是類似java的Bean,
這是接口返回json,所有的json基本都是這個(gè)結(jié)構(gòu),可能名稱不一樣。比如status 在可能是code,content是data,

{
    "status": 1,
    "content": {
        "from": "en-EU",
        "to": "zh-CN",
        "out": "示例",
        "vendor": "ciba",
        "err_no": 0
    }
}

在使用泛型的時(shí)候需要使用一些別的支持
使用gson解析數(shù)據(jù),提供bean,gson自動(dòng)解析數(shù)據(jù)

    //依賴地址
    compile 'com.squareup.retrofit2:converter-gson:2.1.0'

使用上面的json寫個(gè)javabean,作為retrofit的泛型

  public class Bean{
    private int status;

    private content content;
    private static class content {
        private String from;
        private String to;
        private String vendor;
        private String out;
        private int errNo;
    }

    //定義 輸出返回?cái)?shù)據(jù) 的方法
    public void show() {
           Log.i("bean",status);
       Log.i("bean",content.from);
        Log.i("bean",content.to);
        Log.i("bean",content.vendor);
        Log.i("bean",content.out);
        Log.i("bean",content.errNo+"");
    }
}

接口類中

這里放了兩個(gè)接口,注意Call的泛型
public interface Api {
    @GET("GetMoreWeather")
    Call<ResponseBody> getWeather(@QueryMap Map<String,String> map);

    @GET("ajax.php?a=fy&f=auto&t=auto&w=hello%20world")
    Call<Bean> getCall();
}

activity的diam

   //步驟4:創(chuàng)建Retrofit對(duì)象
        Retrofit retrofit = new Retrofit.Builder()
                // 設(shè)置 網(wǎng)絡(luò)請(qǐng)求 Url
                .baseUrl("http://fy.iciba.com/")
                //設(shè)置使用Gson解析(記得加入gson依賴,如果不加依賴而是用泛型,會(huì)報(bào)錯(cuò),當(dāng)然也有別的解析方法,不過gson最常使用)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        Api api = retrofit.create(Api.class);
        //對(duì) 發(fā)送請(qǐng)求 進(jìn)行封裝
        Call<Bean> call = api.getCall();

        //步驟6:發(fā)送網(wǎng)絡(luò)請(qǐng)求(異步)
        call.enqueue(new Callback<Bean>() {
            //請(qǐng)求成功時(shí)回調(diào)
            @Override
            public void onResponse(Call<Bean> call, Response<Bean> response) {
                // 步驟7:處理返回的數(shù)據(jù)結(jié)果
                response.body().show();
            }

            //請(qǐng)求失敗時(shí)回調(diào)
            @Override
            public void onFailure(Call<Bean> call, Throwable throwable) {
                System.out.println("連接失敗");
            }
        });

ps :個(gè)人建議這個(gè)泛型的使用在簡(jiǎn)單的json上使用,有時(shí)候復(fù)雜的json還是自己解析的,bean嵌套太深,不方便維護(hù)。而且后臺(tái)返回的數(shù)據(jù)不一定都有用,使用gson全解析太浪費(fèi)時(shí)間。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容