赞
踩
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'
/** * 请求回调接口 * 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(); }
/**
* 返回对象
* @param <T>
*/
public class BaseOneResp<T> {
public boolean success;
public String code;
public String message;
public T module;
}
/**
* 返回多个对象
*/
public class BaseListResp<T> {
public boolean success;
public String code;
public String message;
public List<T> module;
}
/** * 用户 */ 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 + '\'' + '}'; } }
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(); }
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; }
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(); } } }
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); } }
/** * 登录页 */ 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 就不写了 //....... } }
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。