1.強強聯合
RxJava + Retrofit + okhttp
2.build.gradle檔案中添加如下内容
compile 'com.android.support:appcompat-v7:23.4.0'
compile 'io.reactivex:rxjava:1.0.10'
compile 'io.reactivex:rxandroid:1.2.0'
compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0-beta4'
compile 'com.google.code.gson:gson:2.6.2'
3. 建立各種幫助類
3.1 建立緩存幫助類 主要是友善緩存 需要選擇好緩存路徑和緩存檔案大小
public class CacheHelper {
private Cache mCache;
//設定緩存目錄
private static File cacheFile;
private static long maxSize = **;
private CacheHelper(){
cacheFile = new File(MyApplication.getContext().getCacheDir().getAbsolutePath(), "mycache");
}
private static CacheHelper helper;
public static CacheHelper getInstance(){
if(helper==null){
synchronized (CacheHelper.class){
if(helper==null){
helper = new CacheHelper();
}
}
}
return helper;
}
//傳回緩存對象
public Cache getCache(){
if(mCache ==null)
mCache = new Cache(cacheFile, maxSize);
return mCache;
}
}
3.2 建立OkHttp幫助類 主要是結合OkHttp 提高請求效率
public class OkHttpClientHelper {
private final Cache cache;
private OkHttpClient mClient;
private final static long TIMEOUT = ; //逾時時間
private OkHttpClientHelper(){
cache = CacheHelper.getInstance().getCache();
}
private static OkHttpClientHelper clientHelper;
public static OkHttpClientHelper getInstance(){
if(clientHelper==null){
synchronized (OkHttpClientHelper.class){
if(clientHelper==null){
clientHelper = new OkHttpClientHelper();
}
}
}
return clientHelper;
}
//擷取OKHttpClicent對象
public OkHttpClient getOkHttpClient(){
if(mClient ==null) {
mClient = new OkHttpClient.Builder()
.connectTimeout(TIMEOUT, TimeUnit.SECONDS)
.readTimeout(TIMEOUT, TimeUnit.SECONDS)
.writeTimeout(TIMEOUT, TimeUnit.SECONDS)
.cache(cache) //設定緩存
.build();
}
return mClient;
}
}
3.3 建立Retrofit幫助類
public class RetrofitHelper {
private final OkHttpClient mClient;
private Retrofit mRetrofit;
private RetrofitHelper(){
mClient = OkHttpClientHelper.getInstance().getOkHttpClient();
}
private static RetrofitHelper helper;
//單例 保證對象唯一
public static RetrofitHelper getInstance(){
if(helper==null){
synchronized (RetrofitHelper.class){
if(helper==null){
helper = new RetrofitHelper();
}
}
}
return helper;
}
//擷取Retrofit對象
public Retrofit getRetrofit(String url){
if(mRetrofit==null) {
mRetrofit = new Retrofit.Builder()
.baseUrl(url + "/")
.addConverterFactory(GsonConverterFactory.create()) //添加Gson支援
.addCallAdapterFactory(RxJavaCallAdapterFactory.create()) //添加RxJava支援
.client(mClient) //關聯okhttp
.build();
}
return mRetrofit;
}
}
3.4 建立Http工具類 封裝各種網絡請求方式
public class HttpUtils {
private static MavinService mService;
//Post方式請求網絡
public static void requestNetByPost(String url, String uid,Subscriber subscriber){
setSubscriber(getService(url).getInfoByPost(uid),subscriber);
}
//Get方式請求網絡
public static void requestNetByGet(String url,String uid,Subscriber subscriber){
setSubscriber(getService(url).getInfoByGet(uid),subscriber);
}
//Post map 方式請求網絡
public static void requestNetByPostMap(String url, Map<Integer,String> map,Subscriber subscriber){
setSubscriber(getService(url).getInfoByPostMap(map),subscriber);
}
//Get map方式請求網絡
public static void requestNetByGetMap(String url, Map<Integer,String> map,Subscriber subscriber){
setSubscriber(getService(url).getInfoByGetMap(map),subscriber);
}
//設定緩存
public static void getCache(String url,String uid,Subscriber subscriber){
setSubscriber(getService(url).getCache(uid),subscriber);
}
//訂閱事件
public static<T> void setSubscriber(Observable<T> observable, Subscriber<T> subscriber){
observable.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(subscriber);
}
//擷取服務對象
private static MavinService getService(String url){
if(mService==null) {
mService = RetrofitHelper.getInstance()
.getRetrofit(url)
.create(MavinService.class);
}
return mService;
}
}
4 建立實體類和服務類
4.1 建立實體類 不解釋 用于Gson解析
public class MavinInfo {
public String ANDROID_VERSION;
public String ANDROID_VERSION_CODE;
public String IOS_VERSION;
public String IOS_VERSION_CODE;
public String msg;
public String status;
public List<BodyBean> body;
public static class BodyBean {
public String body_img;
public String title;
public String trueName;
public int uid;
@Override
public String toString() {
return "BodyBean{" +
"body_img='" + body_img + '\'' +
", title='" + title + '\'' +
", trueName='" + trueName + '\'' +
", uid=" + uid +
'}';
}
}
}
4.2 建立服務類接口 Retrofit請求必須的
public interface MavinService{
String MAVIN = "json/tjMavin.htm";
String FIELD = "uid";
//設緩存有效期為1天
long CACHE_STALE_SEC = * * * ;
//查詢緩存的Cache-Control設定,使用緩存
String CACHE_CONTROL_CACHE = "only-if-cached, max-stale=" + CACHE_STALE_SEC;
//查詢網絡的Cache-Control設定。不使用緩存
String CACHE_CONTROL_NETWORK = "max-age=0";
//Post請求
@FormUrlEncoded
@POST(MAVIN)
Observable<MavinInfo> getInfoByPost(@Field(FIELD) String uid);
//GET請求
@GET(MAVIN)
Observable<MavinInfo> getInfoByGet(@Query(FIELD) String uid);
//POST map
@FormUrlEncoded
@POST(MAVIN)
Observable<MavinInfo> getInfoByPostMap(@FieldMap Map<Integer,String> map);
//GET請求 map
@GET(MAVIN)
Observable<MavinInfo> getInfoByGetMap(@QueryMap Map<Integer,String> map);
//GET請求,設定緩存
@Headers("Cache-Control: public," + CACHE_CONTROL_CACHE)
@GET(MAVIN)
Observable<MavinInfo> getCache(@Query(FIELD) String uid);
}
5 Activity中實作
//Get請求
mBtn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getInfo("GET");
}
});
//Post請求
mBtn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getInfo("POST");
}
});
private void getInfo(String type) {
if(type.equals("GET")){
HttpUtils.requestNetByGet(url, "33201", new Subscriber<MavinInfo>() {
@Override
public void onCompleted() {
Log.e("get onCompleted","讀取完成");
}
@Override
public void onError(Throwable e) {
Log.e("get onError",e.getMessage());
}
@Override
public void onNext(MavinInfo info) {
if(info.body==null || info.body.size()<=)
return;
for (MavinInfo.BodyBean bean : info.body) {
Log.e("get onNext ",bean.toString());
}
}
});
}else{
HttpUtils.requestNetByPost(url, "33201", new Subscriber<MavinInfo>() {
@Override
public void onCompleted() {
Log.e("post onCompleted","讀取完成");
}
@Override
public void onError(Throwable e) {
Log.e("post onError",e.getMessage());
}
@Override
public void onNext(MavinInfo info) {
if(info.body==null || info.body.size()<=)
return;
for (MavinInfo.BodyBean bean : info.body) {
Log.e("post onNext ",bean.toString());
}
}
});
}
}
6 聯系方式
QQ:1509815887
郵箱:[email protected]