1,添加依赖
compile 'com.squareup.retrofit2:retrofit:2.1.0' compile 'com.squareup.okhttp3:okhttp:3.3.1' compile 'com.squareup.retrofit2:converter-gson:2.1.0' //适配器 compile 'com.squareup.okhttp3:logging-interceptor:3.8.1' compile "com.squareup.retrofit2:adapter-rxjava2:2.2.0" compile 'io.reactivex.rxjava2:rxjava:2.0.1' compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
2,配置okhttp和retrofit
package com.weijie.aiboy.base;
import android.util.Log;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.weijie.aiboy.api.ServiceAPI;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
public class BaseRetrofit {
private static final String BASE_URL = "http://101.37.34.109:8080/lol/";
private static final long TIMEOUT = 30;
// Retrofit是基于OkHttpClient的,可以创建一个OkHttpClient进行一些配置
private static OkHttpClient httpClient = new OkHttpClient.Builder()
// 添加通用的Header
.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request.Builder builder = chain.request().newBuilder();
return chain.proceed(builder.build());
}
})
/*
这里可以添加一个HttpLoggingInterceptor,因为Retrofit封装好了从Http请求到解析,
出了bug很难找出来问题,添加HttpLoggingInterceptor拦截器方便调试接口
*/
.addInterceptor(new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
@Override
public void log(String message) {
Log.i("----->",message);
}
}).setLevel(HttpLoggingInterceptor.Level.BASIC))
.connectTimeout(TIMEOUT, TimeUnit.SECONDS)
.readTimeout(TIMEOUT, TimeUnit.SECONDS)
.build();
private static ServiceAPI retrofitService = new Retrofit.Builder()
.baseUrl(BASE_URL)
// 添加Gson转换器
.addConverterFactory(GsonConverterFactory.create(buildGson()))
// 添加Retrofit到RxJava的转换器
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(httpClient)
.build()
.create(ServiceAPI.class);
public static ServiceAPI getInstance() {
return retrofitService;
}
private static Gson buildGson() {
return new GsonBuilder()
.serializeNulls()
.setFieldNamingPolicy(FieldNamingPolicy.IDENTITY)
.create();
}
}
3,定义接口文件
package com.weijie.aiboy.api;
import com.weijie.aiboy.bean.ShouyeBeen;
import java.util.Map;
import io.reactivex.Observable;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Response;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;
import retrofit2.http.QueryMap;
/**
* Created by Administrator on 2017/8/12.
*/
public interface ServiceAPI {
/*post上传*/
@POST("game/getHome")
Observable<Response<ShouyeBeen>>getShouyeInfo(@QueryMap Map<String, String> map);
/*图文上传*/
@Multipart
@POST("user/updateUserImg")
Observable<Response<Object>>upDateHeadImg(@Part("userId")RequestBody body, @Part MultipartBody.Part file);
}
4,定义baseObsever
package com.weijie.aiboy.base;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import retrofit2.Response;
public abstract class BaseObserver<T> implements Observer<Response<T>> {
private static final String TAG = "BaseObserver";
private Context mContext;
protected BaseObserver(Context context) {
this.mContext = context.getApplicationContext();
}
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(Response<T> value) {
if (value != null) {
if (value.isSuccessful()) {
T t = value.body();
onHandleSuccess(t);
} else {
onHandleError(value.message());
}
}
}
@Override
public void onError(Throwable e) {
Log.e(TAG, "error:" + e.toString());
}
@Override
public void onComplete() {
Log.d(TAG, "onComplete");
}
protected abstract void onHandleSuccess(T t);
protected void onHandleError(String msg) {
Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
}
}
5,定义BaseEntity
package com.weijie.aiboy.entity;
import com.google.gson.annotations.SerializedName;
public class BaseEntity<E> {
@SerializedName("state")
private int state;
@SerializedName("msg")
private String msg;
@SerializedName("data")
private E AdsList;
public boolean isSuccess() {
return state == 0;
}
public int getState() {
return state;
}
public void setState(int code) {
this.state = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public E getAdsList() {
return AdsList;
}
public void setAdsList(E AdsList) {
this.AdsList = AdsList;
}
}
6,封装线程切换
package com.weijie.aiboy.base;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
public class MyRxSchedulers {
public static <T> ObservableTransformer<T, T> compose() {
return new ObservableTransformer<T, T>() {
@Override
public ObservableSource<T> apply(Observable<T> observable) {
return observable
.subscribeOn(Schedulers.io())
.doOnSubscribe(new Consumer<Disposable>() {
@Override
public void accept(Disposable disposable) throws Exception {
// if (!Utils.isNetworkConnected()) {
// Toast.makeText(context, R.string.toast_network_error, Toast.LENGTH_SHORT).show();
// }
}
})
.observeOn(AndroidSchedulers.mainThread());
}
};
}
}
其他
package com.weijie.aiboy.base; import okhttp3.MediaType; import okhttp3.RequestBody; /** * Created by Administrator on 2017/8/15. */ public class RetrofitUtils { /*图文上传转默认文本格式*/ public static RequestBody exchangeTextType(String s){ RequestBody body= RequestBody.create(MediaType.parse("text/plain"),s); return body; } }
*示例final File file=new File(Environment.getExternalStorageDirectory() + "/head.jpg"); Log.d("ppppppp",file.length()+""); MediaType MEDIATYPE = MediaType.parse(judgeType(Environment.getExternalStorageDirectory() + "/head.jpg")); RequestBody requestFile = RequestBody.create(MEDIATYPE, file); HashMap<String,RequestBody>map=new HashMap<>(); MultipartBody.Part body = MultipartBody.Part.createFormData("image", file.getName(), requestFile); map.put("userId",RequestBody.create(MediaType.parse("text/plain"),"33")); BaseRetrofit.getInstance().upDateHeadImg(RetrofitUtils.exchangeTextType("33"),body).compose(MyRxSchedulers.<Response<Object>>compose()).subscribe(new Consumer<Response<Object>>() { @Override public void accept(Response<Object> objectResponse) throws Exception { Log.d("--------->",objectResponse.body()+""); } });