Retrofit + RxJava 之 Android 應(yīng)用

本文出自 “阿敏其人” 簡書博客,轉(zhuǎn)載或引用請注明出處。

前言,為什么要使用RxJava,因?yàn)楫?dāng)異步操作很多的時候,應(yīng)用RxJava可以讓條例更加清晰。
那么為什么用Retrofit呢?因?yàn)镽etrofit2之后內(nèi)置內(nèi)置okhttp,oh是大勢所趨,加上Retrofit和RxJava兩者配合起來非常搭,所以要RxJava+Retrofit。

一、Retrofit的簡單使用

我們就以為一個請求天氣的GET請求展開描述,完整的api

http://apistore.baidu.com/microservice/weather?citypinyin=beijing

請求Json結(jié)果:

{
    "errNum": 0,
    "errMsg": "success",
    "retData": {
        "city": "接口已經(jīng)停用",
        "pinyin": "apistore.baidu.com",
        "citycode": "000000000",
        "date": "201616-05-12",
        "time": "10:00",
        "postCode": "0000000",
        "longitude": 0,
        "latitude": 0,
        "altitude": "0",
        "weather": "多云",
        "temp": "0",
        "l_tmp": "0",
        "h_tmp": "0",
        "WD": "北風(fēng)",
        "WS": "接口已經(jīng)停用,請?jiān)L問APIStore.baidu.com查找對應(yīng)接口",
        "sunrise": "00:00",
        "sunset": "00:00"
    }
}

接口看完了,數(shù)據(jù)看完了,代碼頁可以開始了。

一、1、最簡單的Retrofit調(diào)用

gradle引入

    compile 'com.squareup.retrofit2:retrofit:2.1.0'
    compile 'com.squareup.retrofit2:converter-gson:2.1.0'
    compile 'com.google.code.gson:gson:2.7'

弄一個APIServer接口,寫上我們的請求方法

public interface APIService {
    // 發(fā)送get請求,光是這段地址肯定不完整,待會我們還在在別的地方補(bǔ)上 baseurl 。 這里直接把后面的請求給寫死了(這樣肯定不好)
    @GET("/microservice/weather?citypinyin=beijing")
    Call<WeatherBean> getWeather();
    
}

MainActivity

public class MainActivity extends AppCompatActivity {

    private TextView mTvGetData;
    private TextView mTvResult;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mTvGetData = (TextView) findViewById(R.id.mTvGetData);
        mTvResult = (TextView) findViewById(R.id.mTvResult);

        mTvGetData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getData();
            }
        });

    }

    private void getData() {
        String baseUrl = "http://apistore.baidu.com/";

        // 創(chuàng)建一個  retrofit ,baseUrl必須有
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        // 利用 retrofit 創(chuàng)建一個接口
        APIService apiService = retrofit.create(APIService.class);
        
        // 利用接口創(chuàng)建一個Call對象
        Call<WeatherBean> weatherBeanCall = apiService.getWeather();

        // 請求入隊(duì),回調(diào)請求成功或者失敗
        weatherBeanCall.enqueue(new Callback<WeatherBean>() {
            @Override
            public void onResponse(Call<WeatherBean> call, Response<WeatherBean> response) {
                WeatherBean jo = response.body();
                System.out.println("請求成功:"+response.body().getRetData().getWeather());
                mTvResult.setText("請求成功:"+response.body().getRetData().getWeather());

            }

            @Override
            public void onFailure(Call<WeatherBean> call, Throwable t) {
                System.out.println("請求失敗");
                mTvResult.setText("請求失敗:"+t.toString());
            }
        });
    }
    
}
image.png

一、2、傳參調(diào)用

我們改變一下APIServer的一點(diǎn)代碼

使用了@Query,后面的 citypinyin 是參數(shù)名

public interface APIService {
    // 發(fā)送get請求,光是這段地址肯定不完整,待會我們還在在別的地方補(bǔ)上 baseurl 。 這里直接把后面的請求給寫死了(這樣肯定不好)
    // 請求還是Get
    @GET("/microservice/weather")
    Call<WeatherBean> getWeather(@Query("citypinyin") String city); // 使用了@Query,后面的 citypinyin 是參數(shù)名

}

接著看一下Activity

    private void getData() {
        String baseUrl = "http://apistore.baidu.com/";

        // 創(chuàng)建一個  retrofit ,baseUrl必須有
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        // 利用 retrofit 創(chuàng)建一個接口
        APIService apiService = retrofit.create(APIService.class);

        // 利用接口創(chuàng)建一個Call對象
        Call<WeatherBean> weatherBeanCall = apiService.getWeather("beijing");

        // 請求入隊(duì),回調(diào)請求成功或者失敗
        weatherBeanCall.enqueue(new Callback<WeatherBean>() {
            @Override
            public void onResponse(Call<WeatherBean> call, Response<WeatherBean> response) {
                WeatherBean jo = response.body();
                System.out.println("請求成功:"+response.body().getRetData().getWeather());
                mTvResult.setText("請求成功:"+response.body().getRetData().getWeather());

            }

            @Override
            public void onFailure(Call<WeatherBean> call, Throwable t) {
                System.out.println("請求失敗");
                mTvResult.setText("請求失敗:"+t.toString());
            }
        });
    }

其實(shí)變化的也就是一行代碼

 Call<WeatherBean> weatherBeanCall = apiService.getWeather("beijing");

運(yùn)行效果一致。

一、3、簡單使用三 @Path

可以參考此文
[Android] Retrofit 初步使用

關(guān)鍵如下截圖

image_1am6fr617kjr14tlnprnditc7m.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容