RxJava+retrofit2 네트워크 요청

4649 단어
1. 새 네트워크 요청이 결과를 되돌려주는 실례(자신의 실제 수요에 따라)
public class HttpResult {
    private int code;
    private String message;
    private T result;
    public int getCode() {
        returncode;    
    }
    public void setCode(intcode) {
        this.code = code;    
    }
    public String getMessage() {
        return message;    
    }
    public void setMessage(String message) {
        this.message = message;    
    }
    public T getResult() {
        return result;    
    }
    public void setResult(T result) {
        this.result = result;    
    }
}

2. 네트워크 요청 도구 클래스 만들기
public classHttpRequestUtils{
    public static finalString BASE_URL ="         ";
    private static finalintDEFAULT_TIMEOUT =10;
    private Retrofit retrofit;
    private RequestService requestService;
    /**
    *         ,        
    */
    private HttpRequestUtils() {
        //      OkHttpClient       
        OkHttpClient.Builder builder =newOkHttpClient.Builder();        
        builder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);        
        retrofit =newRetrofit.Builder().client(builder.build())
                                .addConverterFactory(GsonConverterFactory.create())
                                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .baseUrl(BASE_URL)
                .build();        
        requestService = retrofit.create(RequestService.class);//    API
    }
    /**
     *    HttpRequestUtils       
     */
    private static classSingletonHolder{
        private static finalHttpRequestUtils INSTANCE =newHttpRequestUtils();    
    }
    /**    
     *           
     *@return
     */
    public static HttpRequestUtils getInstance() {
        return SingletonHolder.INSTANCE;    
    }
    /**    *           *@return*/
    public static RequestService getRequestService(){
        return getInstance().requestService;    
    }
    /**    *          *@paramo         *@params        *@param         */
    public void toSubscribe(Observable o, Subscriber s) {        
        o.subscribeOn(Schedulers.io()).unsubscribeOn(Schedulers.io())// io         
         .observeOn(AndroidSchedulers.mainThread()).subscribe(s);//         
    }
}

3. 처리 요청 결과
public class HttpResultFunctionimplementsFunc1 {
    @Override
    public T call(HttpResult tHttpResult) {
        if(tHttpResult.getCode() ==0) {
            thrownewApiException(ApiException.EXCEPTION_CODE1);//
        }
        returntHttpResult.getResult();    
    }
}

4, 이상 정의
public class ApiException extends RuntimeException{
    public  static final int EXCEPTION_CODE1=100;
    public  static final int EXCEPTION_CODE2=101;
    public ApiException(int resultCode) {
        this(getApiExceptionMessage(resultCode));    
    }
    public ApiException(String detailMessage) {
        super(detailMessage);    
    }
    private static String getApiExceptionMessage(intcode){
        String message ="";
        switch(code) {
            case EXCEPTION_CODE1:                
                message ="  1";
                break;
            case EXCEPTION_CODE2:                
                message ="  2";
                break;
                default:                
                message ="      ";        
        }
        return message;    
    }
}

5. 요청 API 정의
public  interface RequestService {
    @POST("user/loginApi")    
    Observable loginApi(@Field("username") String username,@Field("password") String password,@Field("pushid") String pushid);
}

6、이 로그인 방법을 호출합니다
public void login( String username, String password,String pushid) {        
    Observable observable = HttpRequestUtils.getRequestService().loginApi(username, password,pushid).map(new HttpResultFunction());        
    HttpRequestUtils.getInstance().toSubscribe(observable,newSubscriber() {
        @Override
        public void onCompleted() {                
            Toast.makeText(OtherActivity.this,"  ",Toast.LENGTH_SHORT).show();            
        }
        @Override
        public void onError(Throwable throwable) {                
            Toast.makeText(OtherActivity.this,throwable.getMessage(),Toast.LENGTH_SHORT).show();            
        }
        @Override
        public void onNext(String s) {                
            Toast.makeText(OtherActivity.this,s,Toast.LENGTH_SHORT).show();            
        }        
    });    
}

좋은 웹페이지 즐겨찾기