网络请求所需要的依赖
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
compile "io.reactivex.rxjava2:rxjava:2.1.10"
compile 'io.reactivex.rxjava2:rxandroid:2.0.2'
compile 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
Model接口包括可以实现的两个方法
public interface BaseModel<T> {
void getDataFromNet(String url, Map<String,String> map, IBaseRequest<T> iBaseRequest);
void onUnsubscribe();
}
Model开始处理数据的类
public class HomeModel implements BaseModel<HomeBean> {
private CompositeDisposable compositeDisposable;
public HomeModel() {
compositeDisposable = new CompositeDisposable();
}
@Override
public void getDataFromNet(String url, Map<String, String> map, final IBaseRequest<HomeBean> iBaseRequest) {
RetrofitUtil.getInstance(IntegratedUrl.HOBASE_Url).createService(ApiService.class).doGet(url,map)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<ResponseBody>() {
@Override
public void onSubscribe(Disposable d) {
compositeDisposable.add(d);
}
@Override
public void onNext(ResponseBody responseBody) {
try {
String json = responseBody.string();
HomeBean homeBean = new Gson().fromJson(json, HomeBean.class);
iBaseRequest.requestSuccess(homeBean);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onError(Throwable e) {
iBaseRequest.requestError(e);
}
@Override
public void onComplete() {
iBaseRequest.requestComplete();
}
});
}
@Override
public void onUnsubscribe() {
compositeDisposable.clear();
}
}
Presenter的一个实体类可以被继承
public class BasePresenter<V extends IBaseResponse,T> implements IBaseRequest<T> {
private IBaseResponse iBaseResponse;
public BasePresenter(V view) {
this.iBaseResponse = view;
}
@Override
public void requestError(Throwable throwable) {
iBaseResponse.loadDataError(throwable);
}
@Override
public void requestComplete() {
}
@Override
public void requestSuccess(T callBack) {
iBaseResponse.loadDataSuccess(callBack);
}
}
Presenter中负责处理接收model传递的数据
public class HomePresenter extends BasePresenter<HomeView,HomeBean> implements Ipresenter {
private HomeModel homeModel;
public HomePresenter(HomeView view) {
super(view);
homeModel = new HomeModel();
}
@Override
public void getDataFromNet(String url, Map<String, String> map) {
homeModel.getDataFromNet(url,map,this);
}
@Override
public void onUnsubscribe() {
homeModel.onUnsubscribe();
}
}
请求的最大的接口
public interface IBaseRequest<T> {
/**
* @descriptoin 请求异常
* @author dc
* @param throwable 异常类型
* @date 2017/2/16 11:34
*/
void requestError(Throwable throwable);
/**
* @descriptoin 请求完成
* @author dc
* @date 2017/2/16 11:35
*/
void requestComplete();
/**
* @descriptoin 请求成功
* @author dc
* @param callBack 根据业务返回相应的数据
* @date 2017/2/16 11:35
*/
void requestSuccess(T callBack);
}
响应的最大接口
public interface IBaseResponse<T> {
/**
* @descriptoin 请求数据成功
* @author dc
* @param tData 数据类型
* @date 2017/2/16 11:01
*/
void loadDataSuccess(T tData);
/**
* @descriptoin 请求数据错误
* @author dc
* @param throwable 异常类型
* @date 2017/2/16 11:01
*/
void loadDataError(Throwable throwable);
}
Presenter的接口包括两个方法
public interface Ipresenter {
void getDataFromNet(String url, Map<String,String> map);
void onUnsubscribe();
}
需要被Presenter类继承的View接口
public interface HomeView extends IBaseResponse<HomeBean> {
}
ApiService请求方法
public interface ApiService {
/**
* 坑点:--------------路径的字符被转义
*
*/
@GET("{url}")
Observable<ResponseBody> doGet(@Path(value = "url",encoded = true) String url, @QueryMap Map<String,String> map);
@FormUrlEncoded
@POST("{url}")
Observable<ResponseBody> doPost(@Path(value = "url",encoded = true) String url, @FieldMap Map<String,String> map);
}
RetrofitUtil请求工具
public class RetrofitUtil {
private static RetrofitUtil retrofitUtil = null;
private Retrofit retrofit;
private RetrofitUtil(){
}
private RetrofitUtil(String baseUrl){
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addInterceptor(new CommonParamsInterceptor())
.build();
retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
}
/**
* 单例模式
* @return
*/
public static RetrofitUtil getInstance(String baseUrl){
if (retrofitUtil == null){
synchronized (RetrofitUtil.class){
if (retrofitUtil == null){
retrofitUtil = new RetrofitUtil(baseUrl);
}
}
}
return retrofitUtil;
}
public <T> T createService(Class<T> service){
return retrofit.create(service);
}
/**
* 公共参数的拦截器
*/
private static class CommonParamsInterceptor implements Interceptor{
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
String method = request.method();
String oldUrl = request.url().toString();
Log.e("----oldUrl",oldUrl);
Map<String,String> map = new HashMap<>();
map.put("source","android");
if ("GET".equals(method)){
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(oldUrl);
if (oldUrl.contains("?")){
if (oldUrl.indexOf("?") == oldUrl.length()-1){
}else {
stringBuilder.append("&");
}
}else {
stringBuilder.append("?");
}
for (Map.Entry<String,String> entry: map.entrySet()) {
stringBuilder.append(entry.getKey())
.append("=")
.append(entry.getValue())
.append("&");
}
if (stringBuilder.indexOf("&") != -1){
stringBuilder.deleteCharAt(stringBuilder.lastIndexOf("&"));
}
String newUrl = stringBuilder.toString();
Log.e("----newUrl",newUrl);
request = request.newBuilder().url(newUrl).build();
}else if ("POST".equals(method)){
RequestBody requestBody = request.body();
if (requestBody instanceof FormBody){
FormBody oldBody = (FormBody) requestBody;
FormBody.Builder builder = new FormBody.Builder();
for (int i = 0;i<oldBody.size();i++){
builder.add(oldBody.name(i),oldBody.value(i));
}
for (Map.Entry<String,String> entry: map.entrySet()) {
builder.add(entry.getKey(),entry.getValue());
}
request = request.newBuilder().url(oldUrl).post(builder.build()).build();
}
}
Response response = chain.proceed(request);
return response;
}
}
}
Application
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
}
public static ApiService getApiService() {
return RetrofitUtil.getInstance(IntegratedUrl.SHBASE_URL).createService(ApiService.class);
}
}
网址的特殊写法
public class IntegratedUrl {
public static final String SHBASE_URL = "http://120.27.23.105/";
public static final String HOBASE_Url = "https://www.zhaoapi.cn/";
public static final String HOME_URL = "ad/getAd";
public static final String QUERY_URL = "product/getCarts";
public static final String ADD_URL = "product/addCart";
public static final String DELETE_URL = "product/deleteCart";
}