OkCall.java 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. package com.mylove.okhttp;
  2. import android.annotation.SuppressLint;
  3. import android.content.Context;
  4. import android.support.annotation.NonNull;
  5. import java.io.IOException;
  6. import java.util.concurrent.TimeUnit;
  7. import okhttp3.Cache;
  8. import okhttp3.Call;
  9. import okhttp3.Callback;
  10. import okhttp3.OkHttpClient;
  11. import okhttp3.Request;
  12. import okhttp3.Response;
  13. import rx.Subscriber;
  14. /**
  15. * @author myLove
  16. * @time 2017/11/15 13:52
  17. * @e-mail mylove.520.y@gmail.com
  18. * @overview
  19. */
  20. class OkCall {
  21. @SuppressLint("StaticFieldLeak")
  22. private static Context mContext;
  23. private String mCacheUrl;
  24. private Subscriber<? super ResultMsg> subscriber;
  25. private Call call;
  26. @SuppressLint("StaticFieldLeak")
  27. private static OkCall instance;
  28. private CallType callType;
  29. private static OkHttpClient okHttpClient;
  30. private OkCall(String mCacheUrl, Request request, Subscriber<? super ResultMsg> subscriber, CallType callType) {
  31. this.mCacheUrl = mCacheUrl;
  32. this.subscriber = subscriber;
  33. this.call = okHttpClient.newCall(request);
  34. this.callType = callType;
  35. }
  36. /**
  37. * okHttpClient初始化,并添加拦截及缓存
  38. *
  39. * @param context 上下文
  40. * @param mCacheUrl 缓存地址
  41. * @param request 请求
  42. * @param subscriber 返回
  43. * @param callType 请求类型
  44. * @return
  45. */
  46. public static OkCall getInstance(Context context, String mCacheUrl, Request request, Subscriber<? super ResultMsg> subscriber, CallType callType) {
  47. // if (instance == null) {
  48. // synchronized (OkCall.class) {
  49. // if (instance == null) {
  50. mContext = context;
  51. OkHttpClient httpClient = new OkHttpClient();
  52. okHttpClient = httpClient.newBuilder()
  53. .addNetworkInterceptor(new CacheInterceptor())
  54. .cache(privateCache())
  55. .connectTimeout(30, TimeUnit.SECONDS)
  56. .readTimeout(30, TimeUnit.SECONDS)
  57. .build();
  58. instance = new OkCall(mCacheUrl, request, subscriber, callType);
  59. // }
  60. // }
  61. // }
  62. return instance;
  63. }
  64. /**
  65. * 请求
  66. */
  67. void sendCall() {
  68. if (callType == CallType.SYNC) {
  69. sync();
  70. } else if (callType == CallType.ASYNC) {
  71. async();
  72. }
  73. }
  74. /**
  75. * 同步请求
  76. */
  77. private void sync() {
  78. try {
  79. Response execute = call.execute();
  80. ResultMsg msg = new ResultMsg();
  81. int code = execute.code();
  82. msg.setCode(code + "");
  83. msg.setResult("");
  84. if (execute.isSuccessful()) {
  85. String str = execute.body().string();
  86. msg.setResult(str);
  87. if (!str.contains("<!DOCTYPE html>")) {
  88. if (FormatUtil.isNotEmpty(mCacheUrl)) {
  89. CacheUtils.getInstance(mContext).setCacheToLocalJson(mCacheUrl, str);
  90. }
  91. }
  92. subscriber.onNext(msg);
  93. subscriber.onCompleted();
  94. } else {
  95. String json = CacheUtils.getInstance(mContext).getCacheToLocalJson(mCacheUrl);
  96. if (FormatUtil.isNotEmpty(json)) {
  97. msg.setResult(json);
  98. subscriber.onNext(msg);
  99. } else {
  100. subscriber.onError(new Exception("请求失败"));
  101. }
  102. subscriber.onCompleted();
  103. }
  104. } catch (IOException e) {
  105. String json = CacheUtils.getInstance(mContext).getCacheToLocalJson(mCacheUrl);
  106. ResultMsg msg = new ResultMsg();
  107. msg.setCode("404");
  108. if (FormatUtil.isNotEmpty(json)) {
  109. msg.setResult(json);
  110. subscriber.onNext(msg);
  111. } else {
  112. subscriber.onError(e);
  113. }
  114. e.printStackTrace();
  115. subscriber.onCompleted();
  116. }
  117. }
  118. /**
  119. * 异步请求
  120. */
  121. private void async() {
  122. call.enqueue(new Callback() {
  123. @Override
  124. public void onFailure(@NonNull Call call, @NonNull IOException e) {
  125. String json = CacheUtils.getInstance(mContext).getCacheToLocalJson(mCacheUrl);
  126. ResultMsg msg = new ResultMsg();
  127. msg.setCode("404");
  128. if (FormatUtil.isNotEmpty(json)) {
  129. msg.setResult(json);
  130. subscriber.onNext(msg);
  131. } else {
  132. subscriber.onError(e);
  133. }
  134. e.printStackTrace();
  135. subscriber.onCompleted();
  136. }
  137. @Override
  138. public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
  139. String str = response.body().string();
  140. ResultMsg msg = new ResultMsg();
  141. int code = response.code();
  142. msg.setCode(code + "");
  143. msg.setResult(str);
  144. if (!str.contains("<!DOCTYPE html>")) {
  145. if (FormatUtil.isNotEmpty(mCacheUrl)) {
  146. CacheUtils.getInstance(mContext).setCacheToLocalJson(mCacheUrl, str);
  147. }
  148. }
  149. subscriber.onNext(msg);
  150. subscriber.onCompleted();
  151. }
  152. });
  153. }
  154. /**
  155. * 设置缓存路径,以及缓存文件大小
  156. */
  157. private static Cache privateCache() {
  158. return new Cache(mContext.getCacheDir(), 1024 * 1024);
  159. }
  160. }