/**
@详情 RXjava的被观察者
@创建日期 2018/12/29 15:00
*/
public interface ObservedApis {
//使用rxjava的时候,这里需要使用Observable
@GET
Observable get(@Url String url);
@FormUrlEncoded
@POST
Observable post(@Url String url, @FieldMap Map
@DELETE
Observable delete(@Url String url);
@PUT
Observable put(@Url String url, @QueryMap Map
@POST
@Multipart
Observable postImage(@Url String url, @Part MultipartBody.Part parts);
}
public class Apis {
public static final String URL_GET_SHOP_CAR_INFO = “http://172.17.8.100/ks/product/getCarts?uid=51”;
}
/**
@详情 Retrofit网络请求的工具类
@创建日期 2018/12/29 15:02
*/
public class RetrofitUtil {
private static RetrofitUtil instance;
private ObservedApis mObservedApis;
private final String BaseUrl = “http://mobile.bwstudent.com/movieApi/”;
public static synchronized RetrofitUtil getInstance() {
if (instance == null) {
instance = new RetrofitUtil();
}
return instance;
}
private RetrofitUtil() {
//拦截器
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient mClient = new OkHttpClient.Builder()
//读取超时
.readTimeout(10, TimeUnit.SECONDS)
//连接超时
.connectTimeout(10, TimeUnit.SECONDS)
//写超时
.writeTimeout(10, TimeUnit.SECONDS)
//添加自定义拦截器
//new Interceptor
.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
//获取请求
Request original = chain.request();
Log.i(“dj”, "original is " + original.url());
//取出保存的userID,sessionID
// SharedPreferences mSharedPreferences = MyApplication.getContext().getSharedPreferences(“User”, Context.MODE_PRIVATE);
// String userId = mSharedPreferences.getString(“userId”, “”);
// String sessionId = mSharedPreferences.getString(“sessionId”, “”);
//把旧请求的内容,全部复制给新的请求,保证在新的请求中依然有旧请求的所有数据
Request.Builder builder1 = original.newBuilder();
builder1.method(original.method(), original.body());
1
2
3
// builder1.addHeader(“ak”, “0110010010000”);
// builder1.addHeader(“Content-Type”, “application/x-www-form-urlencoded”);
// if (!TextUtils.isEmpty(userId) && !TextUtils.isEmpty(sessionId)) {
// builder1.addHeader(“userId”, userId);
// builder1.addHeader(“sessionId”, sessionId);
// }
//把新请求的builder,重新build成请求
Request request = builder1.build();
//发送请求,并且获得结果
Response response = chain.proceed(request);
return response;
}
})
.build();
//Retrofit的创建
Retrofit mRetrofit = new Retrofit.Builder()
//添加Rxjava工厂
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.baseUrl(BaseUrl)
.client(mClient)
.build();
mObservedApis = mRetrofit.create(ObservedApis.class);
}
//这里就是Rxjava的功能,切换数据运行的线程
//get请求,在外面讲url拼好,传入
public void get(String url, ICallBack callBack) {
mObservedApis.get(url)
//被观察者执行在哪个线程,这里面执行在io线程,io线程是一个子线程
.subscribeOn(Schedulers.io())
//最终完成后结果返回到哪个线程,mainThread代表主线
.observeOn(AndroidSchedulers.mainThread())
//结果
.subscribe(getObserver(callBack));
}
//post请求
//url:接口文档中除去Base_url剩余的部分
public void post(String url, Map
//一定要判空,如果是空,创建一个实例就可以了
if (params == null) {
params = new HashMap<>();
}
mObservedApis.post(url, params)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(getObserver(callBack));
}
//delete请求
public void delete(String url, ICallBack callBack) {
mObservedApis.delete(url)
//后执行在哪个线程
.subscribeOn(Schedulers.io())
//最终完成后执行在哪个线程
.observeOn(AndroidSchedulers.mainThread())
.subscribe(getObserver(callBack));
}
//put请求
public void put(String url, Map
if (params == null) {
params = new HashMap<>();
}
mObservedApis.put(url, params)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(getObserver(callBack));
}
//图片上传
public void postImage(String url, File file, ICallBack callBack) {
RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part filePart = MultipartBody.Part.createFormData("image", file.getName(), requestBody);
mObservedApis.postImage(url, filePart)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(getObserver(callBack));
}
/**
拿结果
*/
private Observer getObserver(final ICallBack callBack) {
//Rxjava
Observer observer = new Observer() {
@Override
public void onCompleted() {
//完成,所有事件全部完成才会执行
}
@Override
public void onError(Throwable e) {
//任何一个事件报错后执行
if (callBack != null) {
callBack.failureData(e.getMessage());
Log.i("Tag", e.getMessage());
}
}
@Override
public void onNext(ResponseBody responseBody) {
//单一事件完成后执行
//请求完成,会走onNext
//这里面的请求完成,不代表服务器告诉我们请求成功
//200 404 503这些都代表请求完成,有结果,中间没报错,但是结果不一定是200
try {
String result = responseBody.string();
if (callBack != null) {
callBack.successData(result);
}
} catch (Exception e) {
e.printStackTrace();
if (callBack != null) {
callBack.failureData(e.getMessage());
}
}
}
};
return observer;
}
public interface ICallBack {
void successData(String result);
void failureData(String error);
}