结合当前比较火的mvp开发模式,在AndroidStudio上使用rxJava与retrofit。
rxJava(异步),retrofit(网络请求)
1.gradle添加依赖
compile 'com.google.code.gson:gson:2.4'
compile 'io.reactivex:rxandroid:1.2.1'
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.2.0'
2.http部分 RetrofitUtils
public class RetrofitUtils {
private static Retrofit mRetrofit;
private static APIService mApiService;
public static Retrofit newInstence() {
if(mRetrofit == null) {
OkHttpClient client = new OkHttpClient.Builder().connectTimeout(Ini._HTTP_CONNECT_TIMEOUT, TimeUnit.MILLISECONDS)
.readTimeout(Ini._HTTP_READ_TIMEOUT, TimeUnit.MILLISECONDS).build();
mRetrofit = new Retrofit.Builder()
.client(client)//添加一个client,不然retrofit会自己默认添加一个
.baseUrl("http://www.blog.com/pages/")
.addConverterFactory(new StringConverterFactory())
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
}
return mRetrofit;
}
public static APIService getApiService(){
newInstence();
if(mApiService == null) {
mApiService = mRetrofit.create(APIService.class);
}
return mApiService;
}
static class FileRequestBodyConverterFactory extends Converter.Factory {
@Override
public Converter<File, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
return new FileRequestBodyConverter();
}
}
static class FileRequestBodyConverter implements Converter<File, RequestBody> {
@Override
public RequestBody convert(File file) throws IOException {
return RequestBody.create(MediaType.parse("image/*"), file);
}
}
public static class StringConverterFactory extends Converter.Factory {
public static StringConverterFactory create() {
return new StringConverterFactory();
}
private StringConverterFactory() {
}
@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations,
Retrofit retrofit) {
if(String.class.equals(type))
return new StringResponseBodyConverter();
else
return null;
}
@Override
public Converter<?, RequestBody> requestBodyConverter(Type type,
Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
if(String.class.equals(type))
return new StringRequestBodyConverter();
else
return null;
}
}
public static class StringResponseBodyConverter implements Converter<ResponseBody, String> {
@Override
public String convert(ResponseBody value) throws IOException {
try {
return value.string();
} finally {
value.close();
}
}
}
public static class StringRequestBodyConverter implements Converter<String, RequestBody> {
private static final MediaType MEDIA_TYPE = MediaType.parse("application/json; charset=UTF-8");
private static final Charset UTF_8 = Charset.forName("UTF-8");
StringRequestBodyConverter() {
}
@Override public RequestBody convert(String value) throws IOException {
Buffer buffer = new Buffer();
Writer writer = new OutputStreamWriter(buffer.outputStream(), UTF_8);
writer.write(value);
writer.close();
return RequestBody.create(MEDIA_TYPE, buffer.readByteString());
}
}
}
3.APIService
public interface APIService {
@GET
Observable<String> loginData(@Url String url);
}
4.这里用一个登录接口作为例子
(1)model
public class UserLoginModel {
public void startLoginData(String url, Subscriber subscriber){
APIService apiService = RetrofitUtils.getApiService();
apiService.loginData(url).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
.subscribe(subscriber);
}
}
(2)presenter
public class UserLoginPresenter {
private static final String TAG="UserLoginPresenter";
private WeakReference<IMainView> iMainView;
private UserLoginModel userLoginModel;
private Context context;
public UserLoginPresenter(Context context,IMainView iMainView) {
this.iMainView =new WeakReference<> (iMainView);
this.context=context;
userLoginModel=new UserLoginModel();
}
public void startLogin(final String userName, String userPaw){
/** 云端验证 **/
// 请求命令 登录
String act = "loginByEmployee";
// 生成sign
Map<String, Object> map = new HashMap<>();
map.put("user",userName);
map.put("password", MD5.md5(userPaw));
map.put("merchantid", userName); // 第一次登录用手机号做企业ID,不是第一次用真正的企业ID
map.put("storeid", "");
map.put("flag", 1);
map.put("appversion", "57_v2.7");
map.put("appos", Ini._APP_OS);
map.put("platform", Ini._VERSION_BUSINESS);
map.put("oper", userName);
map.put("deviceid", "");
map.put("devicetoken", "");
LogUtils.logE(TAG,"map--"+map.toString());
String strSign = getSign(act, map);
String strUrl = getHttpGetUrl(act,
Ini._API_SERVER_CHAIN, getP(map), strSign);
LogUtils.logE(TAG, "strUrl--" + strUrl);
userLoginModel.startLoginData(strUrl, new Subscriber<String>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
iMainView.get().onGetInfoError(e.getMessage());
}
@Override
public void onNext(String mesg) {
Gson gson = new Gson();
Type type = new TypeToken<LoginDataBean>() {}.getType();
LoginDataBean jsonBean = gson.fromJson(mesg, type);
LogUtils.logE(TAG, "jsonBean--" + jsonBean.getState());
if (jsonBean.getState()== Ini.STATE_SUCCESS){
Gson gsons = new Gson();
Type types = new TypeToken<LoginDataResult>() {}.getType();
LoginDataResult jsonBeans = gsons.fromJson(jsonBean.getMesg(), types);
savePerson(userName,jsonBeans);
iMainView.get().onGetInfoSuccess("登录成功");
}else {
iMainView.get().onGetInfoFail(jsonBean.getMesg());
}
}
});
}
public static String getSign(String act, Map<String, Object> map) {
String p = getSignP(map);
String urlQuery = "act=" + act + "&p=" + p + "&key=" + Ini._KEY_SIGN;
return MD5.md5(urlQuery);
}
public static String getHttpGetUrl(String act, String url, String p,
String sign) {
return url + "?act=" + act + "&p=" + p + "&sign=" + sign + "&r="
+ Math.random();
}
public static String getP(Map<String, Object> map) {
return Uri.encode(getSignP(map), "utf-8");
}
public static String getSignP(Map<String, Object> map) {
String p = "";
Set<String> set = map.keySet();
for (String i : set) {
if (p.length() > 0)
p += ",";
p += "\"" + i + "\":";
if (map.get(i) instanceof Integer) {
p += Integer.valueOf("" + map.get(i));
} else {
p += ("\"" + String.valueOf(map.get(i)) + "\"");
}
}
p = "{" + p + "}";
return p;
}
private void savePerson(String userName,LoginDataResult loginDataResult){
DataBaseHelper dataBaseHelper=DataBaseManager.getInstance(context);
SQLiteDatabase db=dataBaseHelper.getWritableDatabase();
ContentValues person =new ContentValues();
person.put("username",userName);
person.put("password",loginDataResult.getPassword());
db.insert(DataBaseHelper.TABLE_NAME,null,person);
db.close();
}
}
(3)IMainView
public interface IMainView {
void onGetInfoSuccess(String mesg);
void onGetInfoFail(String mesg);
void onGetInfoError(String errorMesg);
}
4.在登录处初始化
userLoginPresenter = new UserLoginPresenter(context,this);
userLoginPresenter.startLogin(userName.getText().toString(), userPaw.getText().toString());