想了解Retrofit+RxJava网络请求框架的可以看看这个:
https://blog.csdn.net/u010194538/article/details/107332562
不了解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'
请求回调接口
public interface ApiCallBack<T> {
public void onSuccess(T resp
);
public void onFailure(int code
, String msg
);
public void onCompoleted();
}
返回对象
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 {
@POST("login")
Observable
<BaseOneResp
<LoginResp>> login(@Body LoginResp LoginResp
);
@POST("login_list")
Observable
<BaseListResp
<LoginResp>> login_list();
}
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
;
public class RetrofitHelper {
private HttpApi mApiService
;
public static Map
<String, RetrofitHelper> managers
= new HashMap<>();
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
) {
Retrofit retrofit
= new Retrofit.Builder()
.baseUrl(url
)
.addConverterFactory(GsonConverterFactory
.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory
.create())
.client(new OkHttpClient())
.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 {
private CompositeSubscription mCompositeSubscription
;
protected HttpApi httpApi
= RetrofitHelper
.getAPIService();
public void addSubscription(Observable observable
, Subscriber subscriber
) {
if (mCompositeSubscription
== null
) {
mCompositeSubscription
= new CompositeSubscription();
}
mCompositeSubscription
.add(observable
.subscribeOn(Schedulers
.io())
.observeOn(AndroidSchedulers
.mainThread())
.subscribe(subscriber
));
}
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
= "网络不给力";
}
apiCallBack
.onFailure(code
, msg
);
}else{
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() {
}
}));
}
}