package com.driverdispatch.www.webtool;
import android.util.Log;
import com.driverdispatch.www.util.Property;
import com.google.gson.GsonBuilder;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;
import java.util.List;
import java.util.concurrent.TimeUnit;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
/**
-
Created by wenleitao on 2016/8/23.
*/
public class RetrofitManager {private static final long CACHE_STALE_SEC = 60 * 60 * 24 * 2;
//查询缓存的Cache-Control设置,为if-only-cache时只查询缓存而不会请求服务器,max-stale可以配合设置缓存失效时间
private static final String CACHE_CONTROL_CACHE = “only-if-cached, max-stale=” + CACHE_STALE_SEC;
//查询网络的Cache-Control设置,头部Cache-Control设为max-age=0
//(假如请求了服务器并在a时刻返回响应结果,则在max-age规定的秒数内,浏览器将不会发送对应的请求到服务器,数据由缓存直接返回)时则不会使用缓存而请求服务器
private static final String CACHE_CONTROL_NETWORK = “max-age=0”;private Retrofit retrofit;
private static String serviceCode;private static RetrofitManager instance;
private static final String TAG = RetrofitManager.class.getSimpleName();private static volatile OkHttpClient sOkHttpClient;
private String baseUrl;
public void setServiceCode(String serviceCode) {
this.serviceCode = serviceCode;
}public String getServiceCode() {
return serviceCode;
}**
public void updateServiceCode(String ServiceCode){ this.serviceCode = ServiceCode; }//retorfit 给个update servicecode 方法
**
public enum RetrofitManagerBuild{
INSTANCE;
private RetrofitManager instance;
RetrofitManagerBuild() {
instance = new RetrofitManager();
}
public RetrofitManager getInstance(String serviceCode) {
instance.setServiceCode(serviceCode);
return instance;
}
}
public RetrofitManager() {
retrofitCreate();
}
public RetrofitManager(String serviceCode) {
this.serviceCode=serviceCode;
retrofitCreate();
}
private void retrofitCreate() {
try {
retrofit = new Retrofit.Builder()
.baseUrl(Property.baseUrl)
.client(getOkHttpClient())
.addConverterFactory(IGsonFactory.create(new GsonBuilder().registerTypeAdapterFactory(new NullStringToEmptyAdapterFactory()).create()))
// .addConverterFactory(GsonConverterFactory.create(new GsonBuilder().registerTypeAdapterFactory(new NullStringToEmptyAdapterFactory()).create()))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
} catch (Exception e) {
e.printStackTrace();
}
}
private OkHttpClient getOkHttpClient() {
if (sOkHttpClient == null) {
synchronized (RetrofitManager.class) {
if (sOkHttpClient == null) {
// OkHttpClient配置是一样的,静态创建一次即可
// 指定缓存路径,缓存大小100Mb
// Cache cache = new Cache(new File(MyApplication.GetAppContext().getCacheDir(), “HttpCache”),
// 1024 * 1024 * 100);
sOkHttpClient = new OkHttpClient
.Builder()
.connectTimeout(10000L, TimeUnit.MILLISECONDS)
.readTimeout(10000L, TimeUnit.MILLISECONDS)
.addInterceptor(mLoggingInterceptor)
// .addInterceptor(new AddCookiesInterceptor(MyApplication.getInstance().getApplicationContext()))
// .addInterceptor(new SaveCookiesInterceptor(MyApplication.getInstance().getApplicationContext()))
.addInterceptor(chain -> {
Request original = chain.request();
HttpUrl originalHttpUrl = original.url();
Request.Builder builder = original.newBuilder();
List headerValues = original.headers(“api_server”);
HttpUrl url = null;
HttpUrl newFullUrl=null;
String headerValue = “”;
try {
//如果有这个header,先将配置的header删除,因此header仅用作app和okhttp之间使用
if (headerValues != null && headerValues.size() > 0) {
builder.removeHeader(“api_server”);
//匹配获得新的BaseUrl
headerValue = headerValues.get(0);
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if (“companyfist”.equals(headerValue)) {
url = HttpUrl.parse(Property.REQ_API_SERVERFIST);
builder.addHeader(“Content-Type”, " application/json");
newFullUrl = originalHttpUrl
.newBuilder()
.scheme(url.scheme())
.host(url.host())
.port(url.port())
.build();
} else {
url = HttpUrl.parse(Property.baseUrl);
newFullUrl = originalHttpUrl
.newBuilder()
.addQueryParameter(“appkey”, Property.APPKEY)
.addQueryParameter(“serviceCode”, serviceCode)
.scheme(url.scheme())
.host(url.host())
.port(url.port())
.build();
}
} catch (Exception e) {
e.printStackTrace();
}
Request.Builder requestBuilder = original.newBuilder()
.url(newFullUrl);
Request request = requestBuilder.build();
return chain.proceed(request);
})
.build();
}
}
}
return sOkHttpClient;
}
public <T> T creat(Class<?> clazz) {
return (T) retrofit.create(clazz);
}
// 打印返回的json数据拦截器
private Interceptor mLoggingInterceptor = chain -> {
final Request request = chain.request();
final Response response = chain.proceed(request);
final ResponseBody responseBody = response.body();
final long contentLength = responseBody.contentLength();
BufferedSource source = responseBody.source();
Log.e(TAG, "发送请求\n" + "method:" + request.method() + "\nurl:" + request.url() + "\nheaders:" + request.headers());
source.request(Long.MAX_VALUE); // Buffer the entire body.
Buffer buffer = source.buffer();
Charset charset = Charset.forName("UTF-8");
MediaType contentType = responseBody.contentType();
if (contentType != null) {
try {
charset = contentType.charset(charset);
} catch (UnsupportedCharsetException e) {
Log.e(TAG, "Couldn't decode the response body; charset is likely malformed.");
return response;
}
}
if (contentLength != 0) {
Log.e(TAG, "返回信息:" + buffer.clone().readString(charset));
}
return response;
};
Interceptor mTokenInterceptor = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request originalRequest = chain.request();
String value = "";
// String value = “Token token=”+ SharedData.getInstance().getString(SharedData._token)+",phone="+SharedData.getInstance().getString(SharedData._phone);
if (value == null) {
return chain.proceed(originalRequest);
}
Request authorised = originalRequest.newBuilder()
.header(“Authorization”, value)
.build();
return chain.proceed(authorised);
}
};
}
package com.driverdispatch.www.model;
import android.arch.lifecycle.MutableLiveData;
import android.arch.lifecycle.ViewModel;
import com.driverdispatch.www.base.HttpService;
import com.driverdispatch.www.entity.Resource;
import com.driverdispatch.www.pojo.DriverOilInfoPojo;
import com.driverdispatch.www.request.DriverOilAllocateSource;
import com.driverdispatch.www.util.Property;
import com.driverdispatch.www.util.SharedData;
import com.driverdispatch.www.util.TimeDateFormat;
import com.driverdispatch.www.webtool.RetrofitManager;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
public class DriverOilAllocateListModel extends ViewModel {
private DriverOilAllocateSource doas = null;
/*
private DriverOilAllocateSource doas = new DriverOilAllocateSource(RetrofitManager.RetrofitManagerBuild.INSTANCE.
getInstance(Property.SERVICECODE[41]).creat(HttpService.class));
private DriverOilAllocateSource doasYue = new DriverOilAllocateSource(RetrofitManager.RetrofitManagerBuild.INSTANCE.
getInstance(Property.SERVICECODE[42]).creat(HttpService.class));
*/
private Disposable mDisposable1,mDisposable2,mDisposable3;
public MutableLiveData<Resource<List<DriverOilInfoPojo>>> mOilAllocateLiveData = new MutableLiveData<>();
public MutableLiveData<Resource<List<DriverOilInfoPojo>>> mCheckOilAllocateLiveData = new MutableLiveData<>();
public MutableLiveData<Resource<Object>> companyYueLiveData = new MutableLiveData<>();
public void getDriverOilAllocateData(String imei,String i,Map<String ,String> driveroilAccount){
RetrofitManager rm = RetrofitManager.RetrofitManagerBuild.INSTANCE.getInstance(Property.SERVICECODE[41]);
doas = new DriverOilAllocateSource(rm.creat(HttpService.class));
**
rm.updateServiceCode(Property.SERVICECODE[41]);//servicecode修改在model中调用update 修改servicecode
**
/* doas = new DriverOilAllocateSource(RetrofitManager.RetrofitManagerBuild.INSTANCE.
getInstance(Property.SERVICECODE[41]).creat(HttpService.class));/
Map<String, String> map = new HashMap<>();
map.put(“phone”, SharedData.getInstance().getString(SharedData.PHONE_NUMBER));
map.put(“IMEI”, imei);
map.put(“token”, SharedData.getInstance().getTokenCode());
map.put(“pageNumber”, i);
map.put(“setupTime”, TimeDateFormat.formatYMDByDate(new Date()));
map.put(“processType”, Property.PROCESSALOILDRIVERLIST_TYPE[0][1]);
/
万金司机账号
*/
if (driveroilAccount != null && driveroilAccount.size()>0){
String name = driveroilAccount.get(“oilAccountDriverName”);
String phone = driveroilAccount.get(“PhoneNo”);
if (name !=null && !"".equals(name.trim())){
map.put(“oilAccountDriverName”, name);
}
if (phone !=null && !"".equals(phone.trim())){
map.put(“PhoneNo”, phone);
}
}
mDisposable1 = doas.getDriverOilAllocateList(map).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe(subscription -> mOilAllocateLiveData.setValue(Resource.loading(null)))
.subscribe(resources -> {
if (resources.code .equals(Property.SUCCESSCODE)){
mOilAllocateLiveData.setValue(Resource.success(resources.data, resources.encrypt));
}else {
mOilAllocateLiveData.setValue(Resource.error(resources.code, resources.msg));
}
},throwable -> {
mOilAllocateLiveData.setValue(Resource.error("error", "网络连接失败"));
}
);
}
public void updDriverOilAllocateInfo(String imei,String driveroilAccount){
doas = new DriverOilAllocateSource(RetrofitManager.RetrofitManagerBuild.INSTANCE.
getInstance(Property.SERVICECODE[41]).creat(HttpService.class));
Map<String, String> map = new HashMap<>();
map.put("phone", SharedData.getInstance().getString(SharedData.PHONE_NUMBER));
map.put("IMEI", imei);
map.put("token", SharedData.getInstance().getTokenCode());
map.put("setupTime", TimeDateFormat.formatYMDByDate(new Date()));
map.put("processType", Property.PROCESSALOILDRIVERLIST_TYPE[1][1]);
map.put("driveroilAccount", driveroilAccount);
mDisposable2 = doas.updDriverOilAllocateInfo(map).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe(subscription -> mCheckOilAllocateLiveData.setValue(Resource.loading(null)))
.subscribe(resources -> {
if (resources.code .equals(Property.SUCCESSCODE)){
mCheckOilAllocateLiveData.setValue(Resource.success(resources.data, resources.encrypt));
}else {
mCheckOilAllocateLiveData.setValue(Resource.error(resources.code, resources.msg));
}
},throwable -> {
mCheckOilAllocateLiveData.setValue(Resource.error("error", "网络连接失败"));
}
);
}
}