implementation ‘com.lzy.net:okgo:2.1.4’//OKGO库
比较简单的调用如下:
public static void doRequestGetGiftCabinetList(String id, StringCallback callback) {
OkGo.get(AppConfig.API_DOMAIN + "/user_api/request_get_gift_cabinet")
.params("to_user_id", id)
.tag("doRequestGetGiftCabinetList")
.cacheMode(CacheMode.DEFAULT)
.execute(callback);
}
以下是Retrofit的的用法,搭配rxjava使用:
@POST(“api/sso/login”)
@FormUrlEncoded
Observable phoneregister(@Field(“appid”) String appid);
以下是直接使用:
@GET("/reverse_geocoding/v3")
Call findLocation(@Query(“location”) String location, @Query(“ak”) String ak);
以下是RetrofitClient封装单例类, 实现网络请求,可以复制直接使用,在下面有配合rxjava使用的示例代码:
import android.content.Context;
import android.text.TextUtils;
import com.sim.chongwukongjing.BuildConfig;
import java.io.File;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.goldze.mvvmhabit.http.cookie.CookieJarImpl;
import me.goldze.mvvmhabit.http.cookie.store.PersistentCookieStore;
import me.goldze.mvvmhabit.http.interceptor.BaseInterceptor;
import me.goldze.mvvmhabit.http.interceptor.CacheInterceptor;
import me.goldze.mvvmhabit.http.interceptor.logging.Level;
import me.goldze.mvvmhabit.http.interceptor.logging.LoggingInterceptor;
import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.Utils;
import okhttp3.Cache;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import okhttp3.internal.platform.Platform;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
/**
*
* @author goldze
* @date 2017/5/10
* RetrofitClient封装单例类, 实现网络请求
*/
public class RetrofitClient {
//超时时间
private static final int DEFAULT_TIMEOUT = 20;
//缓存时间
private static final int CACHE_TIMEOUT = 10 * 1024 * 1024;
//服务端根路径
public static String baseUrl = "http://smart.airmedic.cn:9088/arm/";
private static Context mContext = Utils.getContext();
private static OkHttpClient okHttpClient;
private static Retrofit retrofit;
private Cache cache = null;
private File httpCacheDirectory;
private static class SingletonHolder {
private static RetrofitClient INSTANCE = new RetrofitClient();
}
public static RetrofitClient getInstance() {
return SingletonHolder.INSTANCE;
}
private RetrofitClient() {
this(baseUrl, null);
}
private RetrofitClient(String url, Map<String, String> headers) {
if (TextUtils.isEmpty(url)) {
url = baseUrl;
}
if (httpCacheDirectory == null) {
httpCacheDirectory = new File(mContext.getCacheDir(), "goldze_cache");
}
try {
if (cache == null) {
cache = new Cache(httpCacheDirectory, CACHE_TIMEOUT);
}
} catch (Exception e) {
KLog.e("Could not create http cache", e);
}
HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory();
okHttpClient = new OkHttpClient.Builder()
.cookieJar(new CookieJarImpl(new PersistentCookieStore(mContext)))
// .cache(cache)
.addInterceptor(new BaseInterceptor(headers))
.addInterceptor(new CacheInterceptor(mContext))
.sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager)
.addInterceptor(new LoggingInterceptor
.Builder()//构建者模式
.loggable(BuildConfig.DEBUG) //是否开启日志打印
.setLevel(Level.BASIC) //打印的等级
.log(Platform.INFO) // 打印类型
.request("Request") // request的Tag
.response("Response")// Response的Tag
.addHeader("log-header", "I am the log request header.") // 添加打印头, 注意 key 和 value 都不能是中文
.build()
)
.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
.writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
.connectionPool(new ConnectionPool(8, 15, TimeUnit.SECONDS))
// 这里你可以根据自己的机型设置同时连接的个数和时间,我这里8个,和每个保持时间为10s
.build();
retrofit = new Retrofit.Builder()
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.baseUrl(url)
.build();
}
/**
* create you ApiService
* Create an implementation of the API endpoints defined by the {@code service} interface.
*/
public static <T> T create(final Class<T> service) {
if (service == null) {
throw new RuntimeException("Api service is null!");
}
if(retrofit == null){
synchronized (RetrofitClient.class){
if(retrofit == null){
new RetrofitClient();
}
}
}
return retrofit.create(service);
}
/**
* /**
* execute your customer API
* For example:
* MyApiService service =
* RetrofitClient.getInstance(MainActivity.this).create(MyApiService.class);
* <p>
* RetrofitClient.getInstance(MainActivity.this)
* .execute(service.lgon("name", "password"), subscriber)
* * @param subscriber
*/
public static <T> T execute(Observable<T> observable, Observer<T> subscriber) {
observable.subscribeOn(Schedulers.io())
.unsubscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(subscriber);
return null;
}
}
以下是可以在present层使用的Retrofit和rxjava的示例代码:
private void login() {
HttpApi mloginApi;
mloginApi = RetrofitClient.create(HttpApi.class);//对上面封装的使用
String motime = String.valueOf(System.currentTimeMillis());
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("motime",motime);
hashMap.put("smstype","REG");
hashMap.put("phone",phone.getText().toString());
String androidID = Settings.System.getString(this.getContentResolver(), Settings.System.ANDROID_ID);
//关于安卓设备唯一序列号的使用可以看我之前的博文
String sign = signMD5("",hashMap);//加密签名
FormBody body = new FormBody.Builder()
.add("appid", "")
.add("motime", motime)
.add("sign", "")
.add("phone", phone.getText().toString())
.add("mac", androidID)
.add("passwd",editText3.getText().toString())
.build();
Observable<LoginResult> observable = mloginApi.login(body);
observable.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<LoginResult>() {
@Override
public void accept(LoginResult baseInfo) throws Exception {
if ("10000".equals(baseInfo.getCode())){
ToastUtils.showShort(baseInfo.getMsg());
if (checkBox2.isChecked()){
SharedPreferencesUtil.saveLoginInfo(getApplicationContext(),phone.getText().toString(),editText3.getText().toString());
}else {
SharedPreferencesUtil.deleteUser(getApplicationContext());
}
MyApplication.getInstance().setLoginResult(baseInfo);
if (baseInfo.getData().getDcvcnt()==0){
startActivity(AddMachineActivity.class);
}else {
startActivity(MyEquipmentAcitivity.class);
}
finish();
}else {
ToastUtils.showShort(baseInfo.getMsg());
}
}
}, new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Exception {
ToastUtils.showShort("登录失败,请稍后重试");
}
});
}