Retrofit+RxJava 실전 로그(2) - 기본 사용

10099 단어
우선 추상적인 기류이다
public abstract class BaseApi {
    public static final String API_SERVER = " "
    private static final OkHttpClient mOkHttpClient = new OkHttpClient();
    private static Retrofit mRetrofit;

    protected static Retrofit getRetrofit() {
            if (Retrofit == null) {
                Context context = Application.getInstance().getApplicationContext();
                // 30 
                mOkHttpClient.setConnectTimeout(30, TimeUnit.SECONDS);
                // , Cookies 
                mOkHttpClient.networkInterceptors()
                            .add(new CookiesInterceptor(context));
                // 
                File cacheDirectory = new File(context.getCacheDir()
                                        .getAbsolutePath(), "HttpCache");
                Cache cache = new Cache(cacheDirectory, 20 * 1024 * 1024);
                mOkHttpClient.setCache(cache);
                // Retrofit
                mRetrofit = new Retrofit.Builder()
                        // 
                        .baseUrl(API_SERVER + "/")  
                        // , Date 
                        .setDateFormat("yyyy-MM-dd HH:mm:ss")  
                        // , Gson
                        .addConverterFactory(ResponseConverterFactory.create())
                        // , RxJava
                        .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                        // OKHttpClient 
                        .client(mOkHttpClient)
                        .build();
            }
            return mRetrofit;
        }
}

그리고 쿠키 차단기.
public class CookiesInterceptor implements Interceptor{
    private Context context;

    public CookiesInterceptor(Context context) {
        this.context = context;
    }
    // , Cookies 
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Request compressedRequest = request.newBuilder()
                .header("cookie", CookieUtil.getCookies(context))
                .build();
        Response response = chain.proceed(compressedRequest);
        CookieUtil.saveCookies(response.headers(), context);
        return response;
    }
}

CookieUtil은 사용자 정의 해석 및 생성 방법과 SharedPreferences에 대한 액세스, 코드 요약
그리고 Api 클래스.
public class UserApi extends BaseApi{
    // 
    private interface UserService {
        //GET @FormUrlEncoded, @Query 
        @GET("user/user_queryProfile")
        Observable queryProfile(@Query("userId") int userId);

        //POST , 
        @FormUrlEncoded
        @POST("user/user_updateUserName")
        Observable updateUserName(@Field("userName") String userName);
    }
    protected static final UserService service = getRetrofit().create(UserService.class);

    // 
    public static Observable queryProfile(int userId){
        return service.queryProfile(userId);
    }

    // 
    public static Observable updateUserName(String userName){
        return service.updateUserName(userName);
    }
}

그리고 Retrofit의 응답 메시지를 Gson을 통해 원하는 데이터 구조로 해석하여 Model 클래스에 있는 BaseResp와 UserProfileResp는 사용자 정의 모델이라고 부른다
서버 약정이 반환되는 Json 형식은
{
    "result":" ,0 ",
    "msg":" , ",
    "userInfo":
    {
        "id":" id",
        "userName":" "
    }
}

그러면 UserProfileResp는 쓸 수 있습니다.
public class UserProfileResp {
    //@SerializedName Json Key 
    // , Key 
    @SerializedName("userInfo")
    private UserProfileModel userInfo;

    public UserProfileModel getUserInfo() {
        return userInfo;
    }
}

UserProfileModel은 구체적인 데이터 구조입니다.
public class UserProfileModel {
        private int userId;
        private String userName;

        public String getUserName(){
            return userName;
        }
}

주의해야 할 것은 @SerializedName을 사용하여 키 이름을 지정하지 않으면 프로젝트가 헷갈릴 때 변수 이름이 원하는 키 이름과 맞지 않게 헷갈릴 수 있습니다.따라서 이러한 모델 클래스를 하나의 프로젝트 디렉터리에 통일시키고proguard-project 파일에 배제 항목을 넣어야 합니다
// Model 
-keep class com.xxx.model.xxx.** { *; }

마지막으로 실제 호출입니다.
public void getProfile(int userId){
    UserApi.queryProfile(userId)
        .subscribeOn(Schedulers.io())
        .subscribe(new Subscriber(){
                        @Override
                        public void onCompleted() {                 
                        }                       
                        @Override
                        public void onError(Throwable e) {                  
                        }                       
                        @Override
                        public void onNext(UserProfileResp userProfileResp) {               
                        }
        });
}

좋은 웹페이지 즐겨찾기