Android - 網(wǎng)絡(luò)請求之 Retrofit2 + RxJava

老婆保佑,代碼無BUG

目錄

  • 引用
  • 與其他開源請求庫對比
  • Retrofit注解
  • 使用
    • GET請求
    • POST請求
  • Retrofit2 + RxJava
    • 基礎(chǔ)使用
    • 優(yōu)化
    • 封裝Retrofit2 + RxJava

一:引用

retrofit 官網(wǎng)

compile 'com.squareup.retrofit2:retrofit:2.3.0'

二:與其他開源請求庫對比

image

三:Retrofit注解

四:使用

GET請求

(1) 定義接口


public interface ApiService {
    @GET
    Call<ResponseBody> getGetData(@Url String url);
    
    //Get請求,方法中指定@Path參數(shù)和@Query參數(shù)
    //@path參數(shù)用于替換url中{}的部分,
    //@Query將在url地址中追加類似"page=1"的字符串
    @GET("{mobile}/get?") 
    Call<ResponseBody> getPathData(@Path("mobile") String mobile, @Query("phone") String phone, @Query("key") String key);

    @GET("mobile/get?")
    Call<ResponseBody> getQueryMapData(@QueryMap Map<String, String> map);

}

(2) Activity

    public void btnYS(View view) {
        String baseUrl = "http://apis.juhe.cn/";
        String url = baseUrl + "mobile/get?phone=18856907654&key=5778e9d9cf089fc3b093b162036fc0e1";
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .build();
        ApiService apiService = retrofit.create(ApiService.class);
        
        //第一種
        Call<ResponseBody> call = apiService.getGetData(url);
        
        //第二種
        HashMap<String, String> map = new HashMap<>();
        map.put("phone", "18856907654");
        map.put("key", "5778e9d9cf089fc3b093b162036fc0e1");
        Call<ResponseBody> call = apiService.getQueryMapData(map);
        
        //第三種
        apiService.getPathData("mobile","18856907654","5778e9d9cf089fc3b093b162036fc0e1");
        
        
        
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                //主線程
                try {
                    Logger.e("response---->" + response.body().string());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Logger.e("Throwable---->" + t.getMessage());
            }
        });
    }

POST請求

(1) 定義接口

public interface ApiService {
    @FormUrlEncoded
    @POST("mobile/get")  //注意  不是 /  結(jié)束
    Call<ResponseBody> postFile(@Field("phone") String phone,
                                @Field("key") String key);
                                
    @FormUrlEncoded
    @POST("mobile/get")  //注意  不是 /  結(jié)束
    Call<ResponseBody> postFile(@FieldMap Map<String,String> map);
}

(2) Activity

    public void btnPostFile(View view) {
        String baseUrl = "http://apis.juhe.cn/";
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .build();
        ApiService apiService = retrofit.create(ApiService.class);
        
        //第一種
        Call<ResponseBody> call = apiService.postFile("18856907654", "5778e9d9cf089fc3b093b162036fc0e1");
        
        //第二種
        HashMap<String, String> map = new HashMap<>();
        map.put("phone", "18856907654");
        map.put("key", "5778e9d9cf089fc3b093b162036fc0e1");
        Call<ResponseBody> call = apiService.postFile(map);
         //省略一下代碼
    }

以上講的都是廢話,哈哈下面才是正確的打開放式


Retrofit2 + RxJava

引入 依賴

//Retrofit2
compile 'com.squareup.retrofit2:retrofit:2.3.0'
//RxJava
compile 'io.reactivex.rxjava2:rxjava:2.1.7'
//RxAndroid
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
//Retrofit 支持Rxjava 的支持庫
compile 'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0'

先導(dǎo)入,然后慢慢說,這些都是干啥的

按套路出牌,肯定先寫接口

public interface ApiService {
    @GET
    Observable<ResponseBody> getGetData(@Url String url);
}

看到這,就有兄弟說了,哥們你這里寫錯了,不應(yīng)該是Observable應(yīng)該是Call

u=1804519813,2654766997&fm=27&gp=0.jpg

都說了 之前說的都是屁話,這才是正確的打開方式,我們使用的是Observable,RxJava ,都是這么玩的 哈哈

so 繼續(xù)

Activity 先來一個看看

package com.allens.retrofitdemo;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;
import retrofit2.Retrofit;

public class MainActivity extends AppCompatActivity {

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

        String baseUrl = "http://apis.juhe.cn/";
        String url = baseUrl + "mobile/get?phone=18856907654&key=5778e9d9cf089fc3b093b162036fc0e1";


        // 設(shè)置網(wǎng)絡(luò)請求的Url地址
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://fanyi.youdao.com/")
                // 支持RxJava平臺
                //compile 'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0'   是他 就是他 
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();

        retrofit.create(ApiService.class)
                .getGetData(url)//注意看,這里返回的對象時什么,和原生的返回不同,也是我們把上面接口改的原因
                //在子線程取數(shù)據(jù)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                //在主線程顯示ui 
                // compile 'io.reactivex.rxjava2:rxandroid:2.0.1'  這個庫下才有AndroidSchedulers.mainThread
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        
                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }
}

是不是感覺很簡單。哈哈,對就是這么簡單。Post 請求也這么玩,其他都不變,改一下接口,改成 Observable,然后使用RxJava 切換線程就哦了,

如果只是這種程度你就滿足了,哈哈,大兄弟,你也太容易了,

其實我們還可以這么玩


五:優(yōu)化

1. 設(shè)置數(shù)據(jù)解析器

(1)添加一條依賴

//gson 解析器
compile 'com.squareup.retrofit2:converter-gson:2.3.0'

修改接口

public interface ApiService {
    @GET
    Observable<Bean> getGetData(@Url String url);
}

找不同,哈哈 原來的是ResponseBody,現(xiàn)在是Bean,至于Bean 是什么,Bean 對象啊,大兄弟,這個不知道的話,表示。。。。

修改一下Activity中的代碼

Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://fanyi.youdao.com/")
                // 設(shè)置數(shù)據(jù)解析器
                .addConverterFactory(GsonConverterFactory.create()) 
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
retrofit.create(ApiService.class)
                .getGetData(url)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Bean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Bean bean) {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

可以看到,原來返回的是ResponseBody,現(xiàn)在返回的是已經(jīng)解析成功的Bean 對象,

關(guān)于數(shù)據(jù)解析器(Converter)

  • Retrofit支持多種數(shù)據(jù)解析方式
  • 使用時需要在Gradle添加依賴
數(shù)據(jù)解析器 Gradle依賴
Gson com.squareup.retrofit2:converter-gson:2.0.2
Jackson com.squareup.retrofit2:converter-jackson:2.0.2
Simple XML com.squareup.retrofit2:converter-simplexml:2.0.2
Protobuf com.squareup.retrofit2:converter-protobuf:2.0.2
Moshi com.squareup.retrofit2:converter-moshi:2.0.2
Wire com.squareup.retrofit2:converter-wire:2.0.2
Scalars com.squareup.retrofit2:converter-scalars:2.0.2

網(wǎng)絡(luò)請求適配器(CallAdapter)

還記得compile 'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0' 么,他其實就是一個網(wǎng)絡(luò)請求適配器
使用時如使用的是 Android 默認(rèn)的 CallAdapter,則不需要添加網(wǎng)絡(luò)請求適配器的依賴,否則則需要按照需求進(jìn)行添加
Retrofit 提供的 CallAdapter
使用時需要在Gradle添加依賴:

網(wǎng)絡(luò)請求適配器 Gradle依賴 備注
guava com.squareup.retrofit2:adapter-guava:2.0.2 沒用過
Java8 com.squareup.retrofit2:adapter-java8:2.0.2 沒用過
rxjava com.squareup.retrofit2:adapter-rxjava:2.0.2 retrofit現(xiàn)在只支持到rxjava1.XX
rxjava com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0. 大神寫的這個庫可以支持到rxjava2.X

到這里就是不是就感覺,人生圓滿了呢,哈哈
還有后招呢,現(xiàn)在我想把服務(wù)端返回的數(shù)據(jù)全部打印出來,怎么做呢

u=1379330171,3486067710&fm=27&gp=0.jpg

2.加入攔截器

(1)導(dǎo)入庫

compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'

(2)初始化HttpLoggingInterceptor

HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                //打印retrofit日志
                Log.i("RetrofitLog","retrofitBack = "+message);
            }
        });
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

(3)配置okhttp

client = new OkHttpClient.Builder()
                    .addInterceptor(loggingInterceptor)
                    .connectTimeout(mTimeOut, TimeUnit.SECONDS)
                    .readTimeout(mTimeOut, TimeUnit.SECONDS)
                    .writeTimeout(mTimeOut, TimeUnit.SECONDS)
                    .build();

然后嘛,

就可以在控制臺看到請求的Log啦

12-28 04:29:07.337 3922-3944/com.allens.test E/XRetrofit: retrofitBack -> <-- 200 OK http://devapi.water.com/Oauth/authorize (185ms)
12-28 04:29:07.337 3922-3944/com.allens.test E/XRetrofit: retrofitBack -> Date: Thu, 28 Dec 2017 09:29:10 GMT
12-28 04:29:07.337 3922-3944/com.allens.test E/XRetrofit: retrofitBack -> Server: Apache/2.4.17 (Win64) OpenSSL/1.0.2d PHP/5.6.16
12-28 04:29:07.337 3922-3944/com.allens.test E/XRetrofit: retrofitBack -> X-Powered-By: PHP/5.6.16
12-28 04:29:07.337 3922-3944/com.allens.test E/XRetrofit: retrofitBack -> Content-Length: 104
12-28 04:29:07.337 3922-3944/com.allens.test E/XRetrofit: retrofitBack -> Keep-Alive: timeout=5, max=100
12-28 04:29:07.337 3922-3944/com.allens.test E/XRetrofit: retrofitBack -> Connection: Keep-Alive
12-28 04:29:07.337 3922-3944/com.allens.test E/XRetrofit: retrofitBack -> Content-Type: application/json; charset=utf-8
12-28 04:29:07.338 3922-3944/com.allens.test E/XRetrofit: retrofitBack -> 
12-28 04:29:07.338 3922-3944/com.allens.test E/XRetrofit: retrofitBack -> {"is_success":true,"result":{"code":"9405f14110770bf8bd09d1397173e382eab923b19820b9330ce7d533cb3d4722"}}
12-28 04:29:07.338 3922-3944/com.allens.test E/XRetrofit: retrofitBack -> <-- END HTTP (104-byte body)

六: 最后在優(yōu)化

哈哈,自己封裝了一下,有興趣的小伙伴可以點擊查看,及使用

XRetrofit ,點擊查看如何使用

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

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

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