当前位置:   article > 正文

Android请求后台接口,Retrofit+RxJava网络请求封装

Android请求后台接口,Retrofit+RxJava网络请求封装
想了解Retrofit+RxJava网络请求框架的可以看看这个:
不了解Retrofit+RxJava的下面的代码可能有点看不懂。不过不想懂的,也可以直接用,废话不多说,直接上代码
  • 在build.gradle添加依赖(Module)
implementation 'com.squareup.retrofit2:retrofit:2.1.0'
implementation 'com.squareup.retrofit2:converter-gson:2.1.0'
implementation 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
implementation 'io.reactivex:rxandroid:1.2.0'
  • 1
  • 2
  • 3
  • 4
  • 请求回调接口
/**
 * 请求回调接口
 * Created by Administrator on 2018/11/12.
 */

public interface ApiCallBack<T> {
    /**
     * 成功
     * @param resp
     */
    public void onSuccess(T resp);

    /**
     * 请求失败
     * @param code
     * @param msg
     */
    public void onFailure(int code, String msg);

    /**
     * 请求结束
     */
    public void onCompoleted();
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 返回对象
/**
 * 返回对象
 * @param <T>
 */
public class BaseOneResp<T> {
    public boolean success;
    public String code;
    public String message;
    public T module;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 返回多个对象
/**
 * 返回多个对象
 */
public class BaseListResp<T> {
    public boolean success;
    public String code;
    public String message;
    public List<T> module;
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 创建一个实体类用于接收数据
/**
 * 用户
 */
public class LoginResp implements Serializable {
    public String id;
    public String username;
    public String password;
    public String status;
    public String name;
    public String sex;
    public String age;
    public String token;

	@Override
    public String toString() {
        return "LoginResp{" +
                "id='" + id + '\'' +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", status='" + status + '\'' +
                ", name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                ", age='" + age + '\'' +
                ", token='" + token + '\'' +
                '}';
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 请求接口,定义网络请求方式/参数
package com.example.myfirstapp.http;

import com.example.myfirstapp.model.resp.BaseListResp;
import com.example.myfirstapp.model.resp.BaseOneResp;
import com.example.myfirstapp.model.resp.LoginResp;

import retrofit2.http.Body;
import retrofit2.http.Header;
import retrofit2.http.POST;
import rx.Observable;

/**
 * 请求接口
 */
public interface HttpApi {
	/**
     * 登录
     * @param loginReq
     * @return
     */
    @POST("login")
    Observable<BaseOneResp<LoginResp>> login(@Body LoginResp LoginResp);
    
    /**
    * 获取所有用户集合
    */
    @POST("login_list")
    Observable<BaseListResp<LoginResp>> login_list();
 
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • Retrofit初始化
package com.example.myfirstapp.http;

import com.example.myfirstapp.common.Globals;

import java.util.HashMap;
import java.util.Map;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/***
 * 用于Retrofit的初始化
 * 静态方法getInstance用于获取自身RetrofitHelper的实例化,并且只会实例化一次
 */
public class RetrofitHelper {
    private HttpApi mApiService;
//    private static volatile OkHttpClient mOkHttpClient;
    //保证多个地址的
    public static Map<String, RetrofitHelper> managers = new HashMap<>();

	/**
	* 1.可以把地址这个常量写在一个实体类里调用
	* 2.服务器地址例如:https://appsrv.tuanpu.cn/
	* 3.本地项目请求的话,需要查看本地电脑的ip地址+后台项目端口
	*/
    private static String testUrl = "http://192.168.1.6:8080/";

    public static RetrofitHelper getInstance(String url) {
        RetrofitHelper instance = managers.get(url);
        if (instance == null) {
            instance = new RetrofitHelper(url);
            managers.put(url, instance);
        }
        return instance;
    }

    public static RetrofitHelper getInstance() {
        return getInstance(testUrl);
    }

    private RetrofitHelper(String url) {
//        initOkHttpClient();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .addConverterFactory(GsonConverterFactory.create())   //gson转换
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(new OkHttpClient())
//                .addConverterFactory(new NullOnEmptyConverterFactory())   //空数据的处理
                //.addConverterFactory(StringConverterFactory.create())       //数据获取
                .build();
        mApiService = retrofit.create(HttpApi.class);
    }

    public static HttpApi getAPIService() {
        return getInstance().mApiService;
    }

    public static HttpApi getAPIService(String url) {
        return getInstance(url).mApiService;
    }

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 添加订阅关系
public class BaseActivity extends AppCompatActivity {
	//存放RxJava中的订阅关系
    private CompositeSubscription mCompositeSubscription;
    //Retrofit初始化
    protected HttpApi httpApi = RetrofitHelper.getAPIService();
    
	/**
     * 添加订阅关系
     * @param observable
     * @param subscriber
     */
	public void addSubscription(Observable observable, Subscriber subscriber) {
        if (mCompositeSubscription == null) {
            mCompositeSubscription = new CompositeSubscription();
        }
        mCompositeSubscription.add(observable//被观察者
                .subscribeOn(Schedulers.io())//定义事件在主线程消费
                .observeOn(AndroidSchedulers.mainThread())//定义请求事件发生在io线程
                .subscribe(subscriber));//使观察者订阅它
    }

	/**
     * RXjava取消订阅关系,以避免内存泄露
     */
    public void onUnsubscribe() {
        if (mCompositeSubscription != null && mCompositeSubscription.hasSubscriptions()) 	{
            mCompositeSubscription.unsubscribe();
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 使观察者订阅被观察者
package com.example.myfirstapp.http;

import android.content.Context;

import retrofit2.adapter.rxjava.HttpException;
import rx.Subscriber;

/**
 * 使观察者订阅被观察者
 */
public class SubscriberCallBack<T> extends Subscriber<T> {
    private ApiCallBack<T> apiCallBack;
    private Context context;

    public SubscriberCallBack(ApiCallBack<T> apiCallBack) {
        this.apiCallBack = apiCallBack;
    }

    @Override
    public void onCompleted() {//所有事件都完成,可以做些操作(请求结束)
        apiCallBack.onCompoleted();
    }

    @Override
    public void onError(Throwable e) {//请求过程中发生错误
        e.printStackTrace();
        if(e instanceof HttpException){
            //服务器的问题
            HttpException httpException = (HttpException)e;
            int code = httpException.code();
            String msg = httpException.message();
            if (code == 504){
                msg = "网络不给力";
            }
//            ToastCommon.toast(context.getApplicationContext() , "服务器链接不上,请稍等");
            apiCallBack.onFailure(code , msg);
        }else{
            //自身网络原因
//            ToastCommon.toast(context.getApplicationContext() , "网络链接不上,请重新链接网络");
            apiCallBack.onFailure(0 , e.getMessage());
        }
        apiCallBack.onCompoleted();
    }

    @Override
    public void onNext(T t) {//请求接口返回的实体类
        apiCallBack.onSuccess(t);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 以上繁琐的操作后,终于终于可以使用了…
/**
 * 登录页
 */
public class LoginActivity extends BaseActivity{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_activity);
        
		login();
    }

    /**
     * 登录
     */
    private void login() {
        final LoginResp loginResp = new LoginResp();
        loginResp.username = "root";
        loginResp.password = "123456";

        addSubscription(httpApi.login(loginResp),new SubscriberCallBack(new ApiCallBack<BaseOneResp<LoginResp>>() {
            @Override
            public void onSuccess(BaseOneResp<LoginResp> resp) {
                if(!resp.success){
                    showMsg(resp.message);
                    return;
                }
                LoginResp module = resp.module;
                
                System.out.println(module);
        
                Log.d("data:",module.toString());
            }

            @Override
            public void onFailure(int code, String msg) {
            }

            @Override
            public void onCompoleted() {
            }
        }));
		//返回多个对象换成BaseListResp 就不写了
		//.......
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/264964
推荐阅读
相关标签
  

闽ICP备14008679号