其他代码都是一样的,就这些不一样
ApiService:代码
public interface ApiService {
@GET
Observable<String> get(@Url String url, @QueryMap Map<String, String> map);
@FormUrlEncoded
@POST
Observable<String> post(@Url String url, @FieldMap Map<String, String> map);
}
BaseObserver代码
public abstract class BaseObserver<T> implements Observer<String> {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(String s) {
try {
Type genType = getClass().getGenericSuperclass();
Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
Class entityClass = (Class) params[0];
Gson gson = new Gson();
T t = (T)gson.fromJson(s,entityClass);
success(t);
} catch (Exception e) {
failure(1001);
e.printStackTrace();
}
}
@Override
public void onError(Throwable e) {
try {
if(e != null){
if(e instanceof HttpException){
failure(HTTP_ERROR);
} else if(e instanceof SocketException){
failure(NET_WORK_ERROR);
}else {
failure(UNKNOW_ERROR);
}
}else {
failure(UNKNOW_ERROR);
}
e.printStackTrace() ;
} catch (Exception e1) {
failure(UNKNOW_ERROR);
e1.printStackTrace();
}
}
@Override
public void onComplete() {
}
//
/**
* code
* 1000 UNKNOW_ERROR 未知错误
* 1001 json 转化异常 parse error
* 1002 当前网络不可用 java.net.SocketException: Network is unreachable 超时
* 1003 服务器不可用 401 402 403 500 502 503 504
* @param code
*/
public static final int UNKNOW_ERROR = 1000;
public static final int JSON_FORMAT_ERROR = 1001;
public static final int NET_WORK_ERROR = 1002;
public static final int HTTP_ERROR = 1003;
public abstract void success(T t);
public abstract void failure(int code);
}
RetrofitManager:代码
public class RetrofitManager {
public static OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new LoggingInterceptor())
.build();
public static ApiService apiService = new Retrofit.Builder()
.baseUrl("http://120.27.23.105/product/")
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(ScalarsConverterFactory.create())
.client(client)
.build()
.create(ApiService.class);
public static void get(String url, Map<String, String> map, Observer observer) {
apiService.get(url, map)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(observer);
}
public static void post(String url, Map<String, String> map, Observer observer) {
apiService.post(url, map)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(observer);
}
}
molder代码:
public class MyBeanMolder {
public void get(String pscid, String page, final MyBeanCallBack callBack) {
HashMap<String, String> map = new HashMap<>();
map.put("pscid", pscid);
map.put("page", page);
RetrofitManager.get("product/getProducts", map, new BaseObserver<Bean>() {
@Override
public void success(Bean bean) {
callBack.success(bean);
}
@Override
public void failure(int code) {
callBack.failuer(code);
}
});
}
}