1.Retrofit网络封装:
private static Retrofit getRetrofit() {
return new Retrofit.Builder()
.baseUrl(Api.Host)
.client(NetConfig.getInstance().getClient())
.addConverterFactory(GsonConverterFactory.create(NetConfig.getInstance().getGson()))
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
}
baseUrl 是服务器主路径
client 网络封装
public class NetConfig implements Interceptor, CookieJar {
private static NetConfig instance;
private OkHttpClient client;
private PersistentCookieStore cookieStore;
private Gson gson;
private NetConfig() {
}
public static NetConfig getInstance() {
if (instance == null) {
synchronized (NetConfig.class) {
instance = new NetConfig();
}
}
return instance;
}
public OkHttpClient getClient() {
if (client == null)
client = new OkHttpClient.Builder()
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.connectTimeout(30, TimeUnit.SECONDS)
.addInterceptor(this)
.cookieJar(this)
.build();
return client;
}
public Gson getGson() {
if (gson == null)
gson = new GsonBuilder()
.registerTypeAdapter(String.class, new StringConverter())
.enableComplexMapKeySerialization() //支持Map的key为复杂对象的形式
.create();
return gson;
}
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Logger.d("URL = " + request.url().toString());
Request.Builder builder = request.newBuilder();
builder.addHeader("imei", PhoneInfo.getInstance().getImei())
.addHeader("model", PhoneInfo.getInstance().getModel())
.addHeader("brand", PhoneInfo.getInstance().getBrand())
.addHeader("version", PhoneInfo.getInstance().getVersion())
.addHeader("channel", PhoneInfo.getInstance().getChannel())
.addHeader("device", "android");
Map<String, String> headers = Utils.getHttpHeaders();
if (headers != null) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
builder.addHeader(entry.getKey(), entry.getValue());
}
}
Response response = chain.proceed(builder
.build());
ResponseBody responseBody = response.body();
if (null != responseBody) {
okhttp3.MediaType mediaType = responseBody.contentType();
if (null != mediaType && "text/html; charset=UTF-8".equals(mediaType.toString())) {
if (Constant.IS_DEVELOPER && "POST".equals(request.method())) {//打印请求参数
StringBuilder sb = new StringBuilder();
if (request.body() instanceof FormBody) {
FormBody body = (FormBody) request.body();
if (null != body) {
for (int i = 0; i < body.size(); i++) {
sb.append(body.encodedName(i)).append("=").append(body.encodedValue(i)).append(",");
}
if (sb.length() > 0) {
sb.delete(sb.length() - 1, sb.length());
Logger.d("Params ? " + sb.toString());
}
}
}
}
String content = responseBody.string();
Logger.json(content);
return response.newBuilder()
.body(okhttp3.ResponseBody.create(mediaType, content))
.build();
}
}
return response;
}
@Override
public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
if (cookies != null && cookies.size() > 0) {
for (Cookie item : cookies) {
getCookieStore().add(url, item);
}
}
}
@Override
public List<Cookie> loadForRequest(HttpUrl url) {
return getCookieStore().get(url);
}
private PersistentCookieStore getCookieStore() {
if (cookieStore == null)
cookieStore = new PersistentCookieStore(TopAppContext.context);
return cookieStore;
}
}
完整的封装
class Creator {
private static ApiService apiService;
public static ApiService get() {
if (apiService == null) {
create();
}
return apiService;
}
private static synchronized void create() {
if (apiService == null) {
apiService = getRetrofit().create(ApiService.class);
}
}
private static Retrofit getRetrofit() {
return new Retrofit.Builder()
.baseUrl(Api.Host)
.client(NetConfig.getInstance().getClient())
.addConverterFactory(GsonConverterFactory.create(NetConfig.getInstance().getGson()))
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
}
}
RxJava封装
1.先来看一个 登录案例
ApiService.Creator.get().login(account, MD5.getMD5(password), Push.getDeviceToken(), Push.getDeviceToken())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.flatMap(new FlatMapResponse<TopResponse<User>>())
.flatMap(new FlatMapTopRes<User>())
.doOnRequest(new Action1<Long>() {//发起请求
@Override
public void call(Long aLong) {
})
.doOnTerminate(new Action0() {
@Override
public void call() {
}
})
.subscribe(new Subscriber<User>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(User user) {
});
new FlatMapResponse<>封装样式
public class FlatMapResponse<Data> implements Func1<Response<Data>, Observable<Data>> {
@Override
public Observable<Data> call(Response<Data> response) {
if (response.isSuccessful()) {
return Observable.just(response.body());
} else {
try {
return Observable.error(new Error(response.code(), response.errorBody().string()));
} catch (IOException e) {
return Observable.error(new Error(response.code(), e.getMessage()));
}
}
}
}
new FlatMapTopRes封装样式
public class FlatMapTopRes<Data> implements Func1<TopResponse<Data>, Observable<Data>> {
@Override
public Observable<Data> call(TopResponse<Data> response) {
if (response.getCode() == 200) {
return Observable.just(response.getData());
} else {
return Observable.error(response.getError());
}
}
}
第一个flatmap 是Gson解析的bean类型
第二个是返回的bean,可以去掉公共数据 :如code info 这些公共返回码和返回信息
看完以上封装却没有发现 Observable被观察者
其实Observable 已经封装在 Rtrofit中
@FormUrlEncoded
@POST("MobileAppv2/login")
Observable<Response<TopResponse<User>>> login(@Field("account") String account, @Field("password") String password, @Field("push") String deviceToken, @Field("device_id") String deviceId);
<完>