Retrofit2 使用心得

三次使用 Retrofit2

開始想做安卓的網絡請求,發現安卓本身的httpURLConnection太過簡單,使用有大量工作量,就想到使用第三方架包代替,通過了解選擇了Retrofit. 它是結合rxjava一起使用的,比較方便,不過其中也遇到很多問題。

第一次使用Retrofit

引用depencies

//Retrofit
compile 'com.squareup.retrofit2:retrofit:2.0.2'

//Gson
compile 'com.google.code.gson:gson:2.4'

然後

   public class RetrofitClient {
       private static Retrofit retrofit = null;

        public static Retrofit getClient(String baseUrl) {
           if (retrofit == null) {
               retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
            }
          return retrofit;
       }
    }

創建 YourService

 public interface YourService{

   @POST("register")
   Call<UserResponse> register(@Body User user);

 }

調用接口

    YourService yourService =  RetrofitClient.getClient(Constants.BaseUrl)
                                    .create(YourService.class);
    final User user = new User("Jack");
    Call<UserResponse> call = yourService.register(user);
    call.enqueue(new Callback<UserResponse>() {
        @Override
        public void onResponse(Call<UserResponse> call,       
                                Response<UserResponse> response) {
        }

        @Override
        public void onFailure(Call<UserResponse> call, Throwable t) {
            System.out.println("onFailure");
            System.out.println(t.getMessage());
        }
    });

第二次使用Retrofit2 with Rxjava1.x

引入Rxjava可以對網絡請求增加功能,例如可以設置retry, 當發生error時可以再次請求網絡。

引用depencies

//Retrofit
compile 'com.squareup.retrofit2:retrofit:2.0.2'

//RxAndroid
compile 'io.reactivex:rxandroid:1.2.1'
compile 'io.reactivex:rxjava:1.1.6'

//Gson
compile 'com.google.code.gson:gson:2.4'

//converters 
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.0'

然後

public class RetrofitClient {
    private static Retrofit retrofit = null;

    public static Retrofit getClient(String baseUrl) {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(baseUrl)
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}

創建 YourService

public interface YourService{

   @POST("register")
   Observable<UserResponse> register(@Body User user);

   @GET("login?")
   Observable<UserResponse> login(@Query("q") String username);
 }

Note: in Retrofit 2.0, the endpoint path string should NOT start with “/”

@GET(“/login?”) –> incorrect
@GET(“login?”) –> correct

Note: baseUrl 應該以”/”結尾, 之前就因爲這個問題浪費很多時間

調用接口

    YourService yourService = RetrofitClient.getClient(Constants.BaseUrl).create(YourService.class);
    final User user = new User("Jack");
    Observable<UserResponse> register = yourService.register(user);

    register.subscribeOn(Schedulers.newThread())
          .retry(2)
          .observeOn(AndroidSchedulers.mainThread())
          .subscribe(new Subscriber<UserResponse>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(UserResponse userResponse) {

            }
        });

第三次使用Retrofit2 with Rxjava2.x

引用depencies

 //Retrofit
compile'com.squareup.retrofit2:retrofit:2.2.0'

//Rxjava2
compile'io.reactivex.rxjava2:rxjava:2.0.7'
compile'io.reactivex.rxjava2:rxandroid:2.0.1'

//Gson
compile 'com.google.code.gson:gson:2.4'

//converters 
compile'com.squareup.retrofit2:converter-gson:2.2.0'
compile'com.squareup.retrofit2:adapter-rxjava2:2.2.0'

然後

public class RetrofitClient {
    private static Retrofit retrofit = null;

    public static Retrofit getClient(String baseUrl) {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(baseUrl)
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}

創建 YourService

public interface YourService{

       @POST("register")
       Observable<UserResponse> register(@Body User user);
}

調用接口

YourService yourService = RetrofitClient.getClient(Constants.BaseUrl).create(YourService.class);
        final User user = new User("Jack");
        Observable<UserResponse> register = yourService.register(user);
        call.subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<UserResponse>() {
                    Disposable disposable;

                    @Override
                    public void onSubscribe(Disposable d) {
                          this.disposable = d;
                    }

                    @Override
                    public void onNext(UserResponse userResponse) {

                    }

                    @Override
                    public void onError(Throwable e) {
                        disposable.dispose();
                    }

                    @Override
                    public void onComplete() {
                        disposable.dispose();
                    }
                });

Note for Retrofit2 and Rxjava2 Proguard

使用progaurd可能導致生成的apk訪問服務器出現問題,是因爲model convert to json代碼混淆了。
可以通過以下以下兩種方法解決:
1、First you can add a @SerializedName(“field_name”) for each field that you don’t want to be obfuscate.
在你的json類裏給變量加上 @SerializedName(“field_name”), 使它不被混淆。
2、To make short to fix it you just have to add a -keep class configuration in your proguard rules of the package where your Pojo class is stored like the 3 last line from this example

# Application classes that will be serialized/deserialized over Gson
-keep class com.your.package.model.request.** { *; }
-keep class com.your.package.model.response.** { *; }
-keep class com.your.package.model.gson.** { *; }
##--- End:GSON ----
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章