Retrofit 的使用
Retrofit GitHub 官方地址
Retrofit 是square公司出的一个框架,是基于OkHttp进行封装。
第一步:导入Retrofit 依赖:
//rxjava依赖
implementation 'io.reactivex.rxjava2:rxjava:2.1.9'
implementation 'io.reactivex.rxjava2:rxandroid:2.0.2'
//retrofit依赖
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
implementation 'com.squareup.okhttp3:okhttp:3.10.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.9.1'
第二步 创建实体类
现在这样一个api接口
http://service.picasso.adesk.com/v1/vertical/vertical?limit=30&skip=180&adult=false&first=0&order=hot
根据返回json数据创建实体类
第三步 我们新创建一个用于网络请求的接口叫RetrofitService他长这样 ↓
public interface RetrofitService {
// get请求无参数这样
@GET("v1/vertical/vertical?limit=30&skip=180&adult=false&first=0&order=hot")
//要调用的方法和要解析的实体类
Call getData();
//使用path
@GET("v1/{vertical}/vertical?limit=30&skip=180&adult=false&first=0&order=hot")
Call getPath(@Path("vertical") String vertical);
//使用Query
@GET("v1/vertical/vertical?limit=30&skip=180&adult=false")
Call getQuery(@Query("first") int fist,@Query("order") String hot);
//使用url 需要传递整个url,如传递v1/vertical/vertical?limit=30&skip=180&adult=false&first=0&order=hot
@GET()
Call getUrl(@Url String url);
}
在需要请求的地方调用
String baseUrl="http://service.picasso.adesk.com/"; //要以/结尾
//创建Retrofit 并添加baseurl,gson解析
Retrofit retrofit = new Retrofit.Builder().baseUrl(baseUrl).addConverterFactory(GsonConverterFactory.create()).build();
//获取服务接口并创建
RetrofitService service=retrofit.create(RetrofitService.class);
service.getData().enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response){
Log.e("response--getData:",response.toString()+"");
}
@Override
public void onFailure(Call call, Throwable t) {
}
});
service.getPath("vertical").enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
Log.e("response--getPath:",response.response.toString()+"");
}
@Override
public void onFailure(Call call, Throwable t) {
}
});
service.getQuery(0,"hot").enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
Log.e("response--getQuery:",response.response.toString()+"");
}
@Override
public void onFailure(Call call, Throwable t) {
}
});
service.getUrl("v1/vertical/vertical?limit=30&skip=180&adult=false&first=0&order=hot").enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
Log.e("response--getUrl:",response.response.toString()+"");
}
@Override
public void onFailure(Call call, Throwable t) {
}
});
查看log打印:
这样我们就成功请求到了,只不过使用了不同的url拼接方式去请求
Rxjava
Rxjava简单使用
//被观察者
Observable.create(new ObservableOnSubscribe() {
@Override
public void subscribe(ObservableEmitter emitter) throws Exception {
//ObservableEmitter是用来发送事件 onNext、onError、onComplete
emitter.onNext(1);
emitter.onNext(2);
//onComplete 阻止onNext事件继续接收事件,发送没有影响
emitter.onComplete();
emitter.onNext(3);
emitter.onNext(4);
}
}) //观察者
.subscribe(new Observer() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(Integer integer) {
Log.e("onNext", integer + "");
buffer.append("onNext:" + integer + constans.mNewline);
textView.setText(buffer);
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
});
log日志如下:
Rxjava线程切换:
Observable.create(new ObservableOnSubscribe() {
@Override
public void subscribe(ObservableEmitter emitter) throws Exception {
Log.e("Observable_Thread",Thread.currentThread().getName()+"");
emitter.onNext(1);
emitter.onNext(2);
emitter.onNext(3);
emitter.onNext(4);
}
}).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Observer() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(Integer integer) {
Log.e("Observer_onNext",Thread.currentThread().getName()+"");
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
});
log日志如下:
我们看到跟上一段代码只是添加了
观察者所在线程
observeOn(AndroidSchedulers.mainThread())
被观察者所在线程
subscribeOn(Schedulers.io())
Retrofit+Rxjava简单封装
获取okhttp拦截,这里只是拦截了url连接
public class OkHttpClientHelper {
//写入超时
private static final int WRITE_TIME_OUT = 30;
//建立连接的超时时间
private static final int CONNECT_TIME_OUT = 30;
//读取超时
private static final int READ_TIME_OUT = 30;
private static OkHttpClientHelper client;
private OkHttpClient mOkHttpClient;
public static OkHttpClientHelper getmOkHttpClient() {
if (client == null) return new OkHttpClientHelper();
return client;
}
public OkHttpClient getClient() {
mOkHttpClient = new OkHttpClient.Builder().writeTimeout(WRITE_TIME_OUT, TimeUnit.SECONDS).connectTimeout(CONNECT_TIME_OUT, TimeUnit.SECONDS).readTimeout(READ_TIME_OUT, TimeUnit.SECONDS).addNetworkInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Response response = chain.proceed(request);
Log.e("URL-----",response.toString());
return response;
}
}).build();
return mOkHttpClient;
}
创建服务获取Retrofit
public class RetrofitApi {
public static T getApiService(Class tClass, String BaseUrl) {
//client添加自己的okhttp addCallAdapterFactory添加rxjava适配器 addConverterFactory 添加gson适配器
Retrofit retrofit = new Retrofit.Builder().client(OkHttpClientHelper.getmOkHttpClient().getClient()).addCallAdapterFactory(RxJava2CallAdapterFactory.create()).addConverterFactory(GsonConverterFactory.create()).baseUrl(BaseUrl).build();
return retrofit.create(tClass);
}
}
public class RetrofitHelper {
private static RetrofitHelper mHelper;
private String BASE_URL = "";
private RetrofitHelper() {
BASE_URL = constans.baseUrl;
}
public static RetrofitHelper getService() {
if (mHelper == null) mHelper = new RetrofitHelper();
return mHelper;
}
public RetrofitService getApi() {
return RetrofitApi.getApiService(RetrofitService.class, BASE_URL);
}
}
设置默认观察者请求回调
public abstract class DefaultObserver implements Observer {
private String ERROR_TOAST ="";
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(T t) {
onSuccess(t);
onFinish();
}
@Override
public void onError(Throwable e) {
if (e instanceof ConnectException){
ERROR_TOAST="连接超时,请稍后重试!";
onError(ERROR_TOAST);
onFinish();
}else {
onError(e.getMessage());
onFinish();
}
}
@Override
public void onComplete() {
}
public abstract void onSuccess(T data);
public abstract void onError(String error);
public abstract void onFinish();
}
MVP 模式
什么是MVP ,是有MVC演化而来。
M→Model(对数据的操作)
V→View(负责显示)
P→presenter(负责逻辑处理)
先创建一个BaseView
和BasePresenter
接口 里面放着通用操作
public interface BaseView {
void lodingShow();
void lodingDissmis();
void setPresenter(T presenter);
}
public interface BasePresenter {
void start();
}
创建一个Model接口回调
public interface BaseHttpEntity {
void onSuccess(T data);
void onError(String error);
void onFinish();
}
创建Controller类
public interface Presenter extends BasePresenter {
void getData();
}
public interface View extends BaseView {
void setData(RetrofitBean RetrofitBean);
}
public interface Model {
void getModel(BaseHttpEntity entity);
}
}
创建Model类实现Controller.Model
public class Mode implements Controller.Model {
@Override
public void getModel(final BaseHttpEntity entity) {
RetrofitHelper.getService().getApi().getData().subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new DefaultObserver() {
@Override
public void onSuccess(RetrofitBean data) {
entity.onSuccess(data);
}
@Override
public void onError(String error) {
entity.onError(error);
}
@Override
public void onFinish() {
}
});
}
}
创建Presenter类实现Controller.presenter
public class Presenter implements Controller.presenter {
private Controller.Model model;
private Controller.View view;
public Presenter(Controller.View view) {
this.view = view;
model = new Mode();
view.setPresenter(this);
}
@Override
public void getData() {
model.getModel(new BaseHttpEntity() {
@Override
public void onSuccess(RetrofitBean data) {
view.setData(data);
}
@Override
public void onError(String error) {
}
@Override
public void onFinish() {
}
});
}
@Override
public void start() {
getData();
}
}
在activity中
public class MvpActivity extends AppCompatActivity implements Controller.View {
private Controller.presenter presenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mvp);
new Presenter(this);
presenter.start();
}
@Override
public void setData(RetrofitBean mRetrofitBean) {
Log.e("mRetrofitBean.getCode()",mRetrofitBean.getCode()+"");
}
@Override
public void lodingShow() {
}
@Override
public void lodingDissmis() {
}
@Override
public void setPresenter(Controller.presenter presenter) {
this.presenter = presenter;
}
}
要把RetrofitService中Call改成Observable!!!
项目地址GitHub