From c9668c4d292e7735c0e27f9270efe349a04680c1 Mon Sep 17 00:00:00 2001 From: liaoziyao Date: Mon, 29 Aug 2016 00:50:50 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BB=A3=E7=A0=81=E6=95=B4=E4=BD=93=E7=BB=93?= =?UTF-8?q?=E6=9E=84=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../lzy/okhttpdemo/activity/BaseActivity.java | 17 +-- .../activity/BitmapRequestActivity.java | 11 +- .../okhttpdemo/activity/CacheActivity.java | 27 +++- .../activity/CustomRequestActivity.java | 10 +- .../activity/FileDownloadActivity.java | 11 +- .../activity/FormUploadActivity.java | 10 +- .../okhttpdemo/activity/HttpsActivity.java | 10 +- .../okhttpdemo/activity/MethodActivity.java | 10 +- .../okhttpdemo/activity/PostTextActivity.java | 16 +-- .../okhttpdemo/activity/RedirectActivity.java | 10 +- .../callback/BitmapDialogCallback.java | 2 +- .../okhttpdemo/callback/DialogCallback.java | 4 +- .../lzy/okhttpdemo/callback/JsonCallback.java | 11 +- .../callback/StringDialogCallback.java | 4 +- .../okhttpdemo/fragment/OkhttpFragment.java | 4 +- build.gradle | 2 +- gradle/wrapper/gradle-wrapper.properties | 4 +- .../lzy/okhttpserver/upload/UploadTask.java | 2 +- .../lzy/okhttputils/cache/CacheManager.java | 13 +- .../lzy/okhttputils/callback/AbsCallback.java | 44 +++++- .../exception/OkHttpException.java | 33 +++++ .../com/lzy/okhttputils/model/HttpParams.java | 5 + .../okhttputils/request/BaseBodyRequest.java | 37 ++++- .../lzy/okhttputils/request/BaseRequest.java | 134 +++++++++++++----- .../okhttputils/request/DeleteRequest.java | 3 +- .../com/lzy/okhttputils/request/HasBody.java | 6 + .../okhttputils/request/OptionsRequest.java | 3 +- .../lzy/okhttputils/request/PostRequest.java | 48 +------ .../lzy/okhttputils/request/PutRequest.java | 3 +- .../lzy/okhttputils/utils/HeaderParser.java | 10 +- 30 files changed, 320 insertions(+), 184 deletions(-) create mode 100644 okhttputils/src/main/java/com/lzy/okhttputils/exception/OkHttpException.java diff --git a/app/src/main/java/com/lzy/okhttpdemo/activity/BaseActivity.java b/app/src/main/java/com/lzy/okhttpdemo/activity/BaseActivity.java index edfaafbb..7ed1e101 100644 --- a/app/src/main/java/com/lzy/okhttpdemo/activity/BaseActivity.java +++ b/app/src/main/java/com/lzy/okhttpdemo/activity/BaseActivity.java @@ -106,10 +106,7 @@ public boolean onOptionsItemSelected(MenuItem item) { } } - protected void handleResponse(boolean isFromCache, T data, Request request, @Nullable Response response) { - requestState.setText("请求成功 是否来自缓存:" + isFromCache + " 请求方式:" + request.method() + "\n" + - "url:" + request.url()); - + protected void handleResponse(T data, Request request, @Nullable Response response) { Headers requestHeadersString = request.headers(); Set requestNames = requestHeadersString.names(); StringBuilder sb = new StringBuilder(); @@ -164,18 +161,12 @@ protected void handleResponse(boolean isFromCache, T data, Request request, for (String name : names) { sb.append(name).append(" : ").append(responseHeadersString.get(name)).append("\n"); } - } else if (isFromCache) { - sb = new StringBuilder("响应头可以根据 cacheKey 获取到,在此不演示!"); } responseHeader.setText(sb.toString()); } - protected void handleError(boolean isFromCache, Call call, @Nullable Response response) { - Request request = call.request(); - requestState.setText("请求失败 是否来自缓存:" + isFromCache + " 请求方式:" + request.method() + "\n" + - "url:" + request.url()); - - Headers requestHeadersString = request.headers(); + protected void handleError(Call call, @Nullable Response response) { + Headers requestHeadersString = call.request().headers(); Set requestNames = requestHeadersString.names(); StringBuilder sb = new StringBuilder(); for (String name : requestNames) { @@ -197,4 +188,4 @@ protected void handleError(boolean isFromCache, Call call, @Nullable Response re responseHeader.setText("--"); } } -} +} \ No newline at end of file diff --git a/app/src/main/java/com/lzy/okhttpdemo/activity/BitmapRequestActivity.java b/app/src/main/java/com/lzy/okhttpdemo/activity/BitmapRequestActivity.java index e0691d3b..ea254620 100644 --- a/app/src/main/java/com/lzy/okhttpdemo/activity/BitmapRequestActivity.java +++ b/app/src/main/java/com/lzy/okhttpdemo/activity/BitmapRequestActivity.java @@ -11,7 +11,6 @@ import com.lzy.okhttpdemo.utils.Constant; import com.lzy.okhttpdemo.utils.Urls; import com.lzy.okhttputils.OkHttpUtils; -import com.lzy.okhttputils.callback.BitmapCallback; import butterknife.Bind; import butterknife.ButterKnife; @@ -46,15 +45,15 @@ public void requestJson(View view) { .params("param1", "paramValue1")// .execute(new BitmapDialogCallback(this) { @Override - public void onResponse(boolean isFromCache, Bitmap bitmap, Request request, Response response) { - handleResponse(isFromCache, bitmap, request, response); + public void onSuccess(Bitmap bitmap, Request request, Response response) { + handleResponse(bitmap, request, response); imageView.setImageBitmap(bitmap); } @Override - public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) { - super.onError(isFromCache, call, response, e); - handleError(isFromCache, call, response); + public void onError(Call call, @Nullable Response response, @Nullable Exception e) { + super.onError(call, response, e); + handleError(call, response); } }); } diff --git a/app/src/main/java/com/lzy/okhttpdemo/activity/CacheActivity.java b/app/src/main/java/com/lzy/okhttpdemo/activity/CacheActivity.java index 91361c50..6f772bfb 100644 --- a/app/src/main/java/com/lzy/okhttpdemo/activity/CacheActivity.java +++ b/app/src/main/java/com/lzy/okhttpdemo/activity/CacheActivity.java @@ -127,14 +127,29 @@ public CacheCallBack(Activity activity) { } @Override - public void onResponse(boolean isFromCache, RequestInfo requestInfo, Request request, Response response) { - handleResponse(isFromCache, requestInfo, request, response); + public void onSuccess(RequestInfo requestInfo, Request request, Response response) { + requestState.setText("请求成功 是否来自缓存:false 请求方式:" + request.method() + "\n" + "url:" + request.url()); + handleResponse(requestInfo, request, response); } @Override - public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) { - super.onError(isFromCache, call, response, e); - handleError(isFromCache, call, response); + public void onCacheSuccess(RequestInfo requestInfo, Request request, @Nullable Response response) { + requestState.setText("请求成功 是否来自缓存:true 请求方式:" + request.method() + "\n" + "url:" + request.url()); + handleResponse(requestInfo, request, response); + responseHeader.setText("响应头可以根据 cacheKey 获取到,在此不演示!"); + } + + @Override + public void onError(Call call, @Nullable Response response, @Nullable Exception e) { + super.onError(call, response, e); + requestState.setText("请求失败 是否来自缓存:false 请求方式:" + call.request().method() + "\n" + "url:" + call.request().url()); + handleError(call, response); + } + + @Override + public void onCacheError(Call call, @Nullable Response response, @Nullable Exception e) { + requestState.setText("请求失败 是否来自缓存:true 请求方式:" + call.request().method() + "\n" + "url:" + call.request().url()); + handleError(call, response); } } -} +} \ No newline at end of file diff --git a/app/src/main/java/com/lzy/okhttpdemo/activity/CustomRequestActivity.java b/app/src/main/java/com/lzy/okhttpdemo/activity/CustomRequestActivity.java index 6698b9e1..e46d2aed 100644 --- a/app/src/main/java/com/lzy/okhttpdemo/activity/CustomRequestActivity.java +++ b/app/src/main/java/com/lzy/okhttpdemo/activity/CustomRequestActivity.java @@ -66,14 +66,14 @@ public CustomCallBack(Activity activity, Type type) { } @Override - public void onResponse(boolean isFromCache, T data, Request request, Response response) { - handleResponse(isFromCache, data, request, response); + public void onSuccess(T data, Request request, Response response) { + handleResponse(data, request, response); } @Override - public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) { - super.onError(isFromCache, call, response, e); - handleError(isFromCache, call, response); + public void onError(Call call, @Nullable Response response, @Nullable Exception e) { + super.onError(call, response, e); + handleError(call, response); } } } diff --git a/app/src/main/java/com/lzy/okhttpdemo/activity/FileDownloadActivity.java b/app/src/main/java/com/lzy/okhttpdemo/activity/FileDownloadActivity.java index 492c5b2a..4bdd9598 100644 --- a/app/src/main/java/com/lzy/okhttpdemo/activity/FileDownloadActivity.java +++ b/app/src/main/java/com/lzy/okhttpdemo/activity/FileDownloadActivity.java @@ -17,7 +17,6 @@ import com.lzy.okhttputils.request.BaseRequest; import java.io.File; -import java.nio.ByteBuffer; import butterknife.Bind; import butterknife.ButterKnife; @@ -69,8 +68,8 @@ public void onBefore(BaseRequest request) { } @Override - public void onResponse(boolean isFromCache, File file, Request request, Response response) { - handleResponse(isFromCache, file, request, response); + public void onSuccess(File file, Request request, Response response) { + handleResponse(file, request, response); btnFileDownload.setText("下载完成"); } @@ -89,9 +88,9 @@ public void downloadProgress(long currentSize, long totalSize, float progress, l } @Override - public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) { - super.onError(isFromCache, call, response, e); - handleError(isFromCache, call, response); + public void onError(Call call, @Nullable Response response, @Nullable Exception e) { + super.onError(call, response, e); + handleError(call, response); btnFileDownload.setText("下载出错"); } } diff --git a/app/src/main/java/com/lzy/okhttpdemo/activity/FormUploadActivity.java b/app/src/main/java/com/lzy/okhttpdemo/activity/FormUploadActivity.java index 25b58f9b..8f6598bb 100644 --- a/app/src/main/java/com/lzy/okhttpdemo/activity/FormUploadActivity.java +++ b/app/src/main/java/com/lzy/okhttpdemo/activity/FormUploadActivity.java @@ -128,15 +128,15 @@ public void onBefore(BaseRequest request) { } @Override - public void onResponse(boolean isFromCache, T s, Request request, Response response) { - handleResponse(isFromCache, s, request, response); + public void onSuccess(T s, Request request, Response response) { + handleResponse(s, request, response); btnFormUpload.setText("上传完成"); } @Override - public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) { - super.onError(isFromCache, call, response, e); - handleError(isFromCache, call, response); + public void onError(Call call, @Nullable Response response, @Nullable Exception e) { + super.onError(call, response, e); + handleError(call, response); btnFormUpload.setText("上传出错"); } diff --git a/app/src/main/java/com/lzy/okhttpdemo/activity/HttpsActivity.java b/app/src/main/java/com/lzy/okhttpdemo/activity/HttpsActivity.java index 1b3a4206..1dc209b5 100644 --- a/app/src/main/java/com/lzy/okhttpdemo/activity/HttpsActivity.java +++ b/app/src/main/java/com/lzy/okhttpdemo/activity/HttpsActivity.java @@ -85,14 +85,14 @@ public HttpsCallBack(Activity activity) { } @Override - public void onResponse(boolean isFromCache, String data, Request request, Response response) { - handleResponse(isFromCache, data, request, response); + public void onSuccess(String data, Request request, Response response) { + handleResponse(data, request, response); } @Override - public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) { - super.onError(isFromCache, call, response, e); - handleError(isFromCache, call, response); + public void onError(Call call, @Nullable Response response, @Nullable Exception e) { + super.onError(call, response, e); + handleError(call, response); } } } diff --git a/app/src/main/java/com/lzy/okhttpdemo/activity/MethodActivity.java b/app/src/main/java/com/lzy/okhttpdemo/activity/MethodActivity.java index 18a54790..d95ebf3d 100644 --- a/app/src/main/java/com/lzy/okhttpdemo/activity/MethodActivity.java +++ b/app/src/main/java/com/lzy/okhttpdemo/activity/MethodActivity.java @@ -108,14 +108,14 @@ public MethodCallBack(Activity activity, Class clazz) { } @Override - public void onResponse(boolean isFromCache, T data, Request request, Response response) { - handleResponse(isFromCache, data, request, response); + public void onSuccess(T data, Request request, Response response) { + handleResponse(data, request, response); } @Override - public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) { - super.onError(isFromCache, call, response, e); - handleError(isFromCache, call, response); + public void onError(Call call, @Nullable Response response, @Nullable Exception e) { + super.onError(call, response, e); + handleError(call, response); } } diff --git a/app/src/main/java/com/lzy/okhttpdemo/activity/PostTextActivity.java b/app/src/main/java/com/lzy/okhttpdemo/activity/PostTextActivity.java index d315e34d..281fd685 100644 --- a/app/src/main/java/com/lzy/okhttpdemo/activity/PostTextActivity.java +++ b/app/src/main/java/com/lzy/okhttpdemo/activity/PostTextActivity.java @@ -52,7 +52,7 @@ public void postJson(View view) { .tag(this)// .headers("header1", "headerValue1")// .params("param1", "paramValue1")// - .postJson(jsonObject.toString())// + .upJson(jsonObject.toString())// .execute(new TextCallBack<>(this, RequestInfo.class)); } @@ -62,7 +62,7 @@ public void postString(View view) { .tag(this)// .headers("header1", "headerValue1")// .params("param1", "paramValue1")// - .postString("这是要上传的长文本数据!")// + .upString("这是要上传的长文本数据!")// .execute(new TextCallBack<>(this, RequestInfo.class)); } @@ -72,7 +72,7 @@ public void postBytes(View view) { .tag(this)// .headers("header1", "headerValue1")// .params("param1", "paramValue1")// - .postBytes("这是字节数据".getBytes())// + .upBytes("这是字节数据".getBytes())// .execute(new TextCallBack<>(this, RequestInfo.class)); } @@ -83,14 +83,14 @@ public TextCallBack(Activity activity, Class clazz) { } @Override - public void onResponse(boolean isFromCache, T data, Request request, Response response) { - handleResponse(isFromCache, data, request, response); + public void onSuccess(T data, Request request, Response response) { + handleResponse(data, request, response); } @Override - public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) { - super.onError(isFromCache, call, response, e); - handleError(isFromCache, call, response); + public void onError(Call call, @Nullable Response response, @Nullable Exception e) { + super.onError(call, response, e); + handleError(call, response); } } } diff --git a/app/src/main/java/com/lzy/okhttpdemo/activity/RedirectActivity.java b/app/src/main/java/com/lzy/okhttpdemo/activity/RedirectActivity.java index 9d28edbe..6d782216 100644 --- a/app/src/main/java/com/lzy/okhttpdemo/activity/RedirectActivity.java +++ b/app/src/main/java/com/lzy/okhttpdemo/activity/RedirectActivity.java @@ -48,8 +48,8 @@ public RedirectCallBack(Activity activity) { } @Override - public void onResponse(boolean isFromCache, String data, Request request, Response response) { - handleResponse(isFromCache, data, request, response); + public void onSuccess(String data, Request request, Response response) { + handleResponse(data, request, response); responseData.setText("注意看请求头的url和响应头的url是不一样的!\n这代表了在请求过程中发生了重定向," + "okhttp默认将重定向封装在了请求内部,只有最后一次请求的数据会被真正的请求下来触发回调,中间过程" + @@ -57,9 +57,9 @@ public void onResponse(boolean isFromCache, String data, Request request, Respon } @Override - public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) { - super.onError(isFromCache, call, response, e); - handleError(isFromCache, call, response); + public void onError(Call call, @Nullable Response response, @Nullable Exception e) { + super.onError(call, response, e); + handleError(call, response); } } } \ No newline at end of file diff --git a/app/src/main/java/com/lzy/okhttpdemo/callback/BitmapDialogCallback.java b/app/src/main/java/com/lzy/okhttpdemo/callback/BitmapDialogCallback.java index 88db6f65..b3c9b982 100644 --- a/app/src/main/java/com/lzy/okhttpdemo/callback/BitmapDialogCallback.java +++ b/app/src/main/java/com/lzy/okhttpdemo/callback/BitmapDialogCallback.java @@ -41,7 +41,7 @@ public void onBefore(BaseRequest request) { } @Override - public void onAfter(boolean isFromCache, @Nullable Bitmap bitmap, Call call, @Nullable Response response, @Nullable Exception e) { + public void onAfter(@Nullable Bitmap bitmap, Call call, @Nullable Response response, @Nullable Exception e) { if (dialog != null && dialog.isShowing()) { dialog.dismiss(); } diff --git a/app/src/main/java/com/lzy/okhttpdemo/callback/DialogCallback.java b/app/src/main/java/com/lzy/okhttpdemo/callback/DialogCallback.java index 056409c8..41994aac 100644 --- a/app/src/main/java/com/lzy/okhttpdemo/callback/DialogCallback.java +++ b/app/src/main/java/com/lzy/okhttpdemo/callback/DialogCallback.java @@ -53,8 +53,8 @@ public void onBefore(BaseRequest request) { } @Override - public void onAfter(boolean isFromCache, @Nullable T t, Call call, @Nullable Response response, @Nullable Exception e) { - super.onAfter(isFromCache, t, call, response, e); + public void onAfter(@Nullable T t, Call call, @Nullable Response response, @Nullable Exception e) { + super.onAfter(t, call, response, e); //网络请求结束后关闭对话框 if (dialog != null && dialog.isShowing()) { dialog.dismiss(); diff --git a/app/src/main/java/com/lzy/okhttpdemo/callback/JsonCallback.java b/app/src/main/java/com/lzy/okhttpdemo/callback/JsonCallback.java index 8528ff7b..639d3c13 100644 --- a/app/src/main/java/com/lzy/okhttpdemo/callback/JsonCallback.java +++ b/app/src/main/java/com/lzy/okhttpdemo/callback/JsonCallback.java @@ -1,10 +1,8 @@ package com.lzy.okhttpdemo.callback; import android.text.TextUtils; -import android.widget.Toast; import com.google.gson.Gson; -import com.lzy.okhttputils.OkHttpUtils; import org.json.JSONObject; @@ -73,13 +71,6 @@ public T parseNetworkResponse(Response response) throws Exception { default: throw new IllegalStateException("错误代码:" + code + ",错误信息:" + msg); } - //如果要更新UI,需要使用handler,可以如下方式实现,也可以自己写handler - OkHttpUtils.getInstance().getDelivery().post(new Runnable() { - @Override - public void run() { - Toast.makeText(OkHttpUtils.getContext(), "错误代码:" + code + ",错误信息:" + msg, Toast.LENGTH_SHORT).show(); - } - }); - return null; + throw new IllegalStateException("数据解析错误"); } } \ No newline at end of file diff --git a/app/src/main/java/com/lzy/okhttpdemo/callback/StringDialogCallback.java b/app/src/main/java/com/lzy/okhttpdemo/callback/StringDialogCallback.java index a4062ee2..4139fe98 100644 --- a/app/src/main/java/com/lzy/okhttpdemo/callback/StringDialogCallback.java +++ b/app/src/main/java/com/lzy/okhttpdemo/callback/StringDialogCallback.java @@ -46,8 +46,8 @@ public void onBefore(BaseRequest request) { } @Override - public void onAfter(boolean isFromCache, @Nullable String s, Call call, Response response, @Nullable Exception e) { - super.onAfter(isFromCache, s, call, response, e); + public void onAfter(@Nullable String s, Call call, Response response, @Nullable Exception e) { + super.onAfter(s, call, response, e); //网络请求结束后关闭对话框 if (dialog != null && dialog.isShowing()) { dialog.dismiss(); diff --git a/app/src/main/java/com/lzy/okhttpdemo/fragment/OkhttpFragment.java b/app/src/main/java/com/lzy/okhttpdemo/fragment/OkhttpFragment.java index 8cc1b15b..d3fe686a 100644 --- a/app/src/main/java/com/lzy/okhttpdemo/fragment/OkhttpFragment.java +++ b/app/src/main/java/com/lzy/okhttpdemo/fragment/OkhttpFragment.java @@ -153,7 +153,7 @@ public ViewHolder(View convertView) { // } // // @Override -// public void onResponse(Call call, Response response) throws IOException { +// public void onSuccess(Call call, Response response) throws IOException { // System.out.println("-----" + response.body().string()); // } // }); @@ -171,7 +171,7 @@ public ViewHolder(View convertView) { // } // // @Override -// public void onResponse(Call call, Response response) throws IOException { +// public void onSuccess(Call call, Response response) throws IOException { // System.out.println("-----" + response.body().string()); // } // }); diff --git a/build.gradle b/build.gradle index cd8e87f8..88ea6546 100644 --- a/build.gradle +++ b/build.gradle @@ -5,7 +5,7 @@ buildscript { jcenter() } dependencies { - classpath 'com.android.tools.build:gradle:2.1.2' + classpath 'com.android.tools.build:gradle:2.1.3' classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.0' classpath 'com.github.dcendents:android-maven-gradle-plugin:1.3' diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 66135aa2..2e45b72f 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ -#Wed Apr 13 18:38:37 CST 2016 +#Sun Aug 28 17:42:10 CST 2016 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-2.10-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip diff --git a/okhttpserver/src/main/java/com/lzy/okhttpserver/upload/UploadTask.java b/okhttpserver/src/main/java/com/lzy/okhttpserver/upload/UploadTask.java index 480da14b..762f6328 100644 --- a/okhttpserver/src/main/java/com/lzy/okhttpserver/upload/UploadTask.java +++ b/okhttpserver/src/main/java/com/lzy/okhttpserver/upload/UploadTask.java @@ -118,7 +118,7 @@ public T parseNetworkResponse(Response response) throws Exception { } @Override - public void onResponse(boolean isFromCache, T t, Request request, Response response) { + public void onSuccess(T t, Request request, Response response) { } } diff --git a/okhttputils/src/main/java/com/lzy/okhttputils/cache/CacheManager.java b/okhttputils/src/main/java/com/lzy/okhttputils/cache/CacheManager.java index 4fa21f87..7624eb2e 100644 --- a/okhttputils/src/main/java/com/lzy/okhttputils/cache/CacheManager.java +++ b/okhttputils/src/main/java/com/lzy/okhttputils/cache/CacheManager.java @@ -31,6 +31,12 @@ public CacheEntity get(String key) { } } + /** 返回带泛型的对象,注意必须确保泛型和对象对应才不会发生类型转换异常 */ + @SuppressWarnings("unchecked") + public CacheEntity get(String key, Class clazz) { + return (CacheEntity) get(key); + } + /** * 获取所有缓存 * @@ -52,11 +58,12 @@ public List> getAll() { * @param entity 需要替换的的缓存 * @return 被替换的缓存 */ - public CacheEntity replace(String key, CacheEntity entity) { + @SuppressWarnings("unchecked") + public CacheEntity replace(String key, CacheEntity entity) { mLock.lock(); try { entity.setKey(key); - cacheDao.replace(entity); + cacheDao.replace((CacheEntity) entity); return entity; } finally { mLock.unlock(); @@ -92,4 +99,4 @@ public boolean clear() { mLock.unlock(); } } -} +} \ No newline at end of file diff --git a/okhttputils/src/main/java/com/lzy/okhttputils/callback/AbsCallback.java b/okhttputils/src/main/java/com/lzy/okhttputils/callback/AbsCallback.java index f13675d5..8c0eccda 100644 --- a/okhttputils/src/main/java/com/lzy/okhttputils/callback/AbsCallback.java +++ b/okhttputils/src/main/java/com/lzy/okhttputils/callback/AbsCallback.java @@ -2,8 +2,11 @@ import android.support.annotation.Nullable; +import com.lzy.okhttputils.cache.CacheMode; import com.lzy.okhttputils.request.BaseRequest; +import java.io.IOException; + import okhttp3.Call; import okhttp3.Request; import okhttp3.Response; @@ -16,6 +19,27 @@ * 描 述:抽象的回调接口 * 修订历史: * ================================================ + *

该类的回调具有如下顺序,虽然顺序写的很复杂,但是理解后,是很简单,并且合情合理的 + *

1.无缓存模式{@link CacheMode#NO_CACHE}
+ * ---网络请求成功 onBefore -> parseNetworkResponse -> onSuccess -> onAfter
+ * ---网络请求失败 onBefore -> parseNetworkFail -> onError -> onAfter
+ *

2.默认缓存模式,遵循304头{@link CacheMode#DEFAULT}
+ * ---网络请求成功,服务端返回非304 onBefore -> parseNetworkResponse -> onSuccess -> onAfter
+ * ---网络请求成功服务端返回304 onBefore -> onCacheSuccess -> onAfter
+ * ---网络请求失败 onBefore -> parseNetworkFail -> onError -> onAfter
+ *

3.请求网络失败后读取缓存{@link CacheMode#REQUEST_FAILED_READ_CACHE}
+ * ---网络请求成功,不读取缓存 onBefore -> parseNetworkResponse -> onSuccess -> onAfter
+ * ---网络请求失败,读取缓存成功 onBefore -> parseNetworkFail -> onError -> onCacheSuccess -> onAfter
+ * ---网络请求失败,读取缓存失败 onBefore -> parseNetworkFail -> onError -> onCacheError -> onAfter
+ *

4.如果缓存不存在才请求网络,否则使用缓存{@link CacheMode#IF_NONE_CACHE_REQUEST}
+ * ---已经有缓存,不请求网络 onBefore -> onCacheSuccess -> onAfter
+ * ---没有缓存请求网络成功 onBefore -> onCacheError -> parseNetworkResponse -> onSuccess -> onAfter
+ * ---没有缓存请求网络失败 onBefore -> onCacheError -> parseNetworkFail -> onError -> onAfter
+ *

5.先使用缓存,不管是否存在,仍然请求网络{@link CacheMode#FIRST_CACHE_THEN_REQUEST}
+ * ---无缓存时,网络请求成功 onBefore -> onCacheError -> parseNetworkResponse -> onSuccess -> onAfter
+ * ---无缓存时,网络请求失败 onBefore -> onCacheError -> parseNetworkFail -> onError -> onAfter
+ * ---有缓存时,网络请求成功 onBefore -> onCacheSuccess -> parseNetworkResponse -> onSuccess -> onAfter
+ * ---有缓存时,网络请求失败 onBefore -> onCacheSuccess -> parseNetworkFail -> onError -> onAfter
*/ public abstract class AbsCallback { @@ -26,16 +50,28 @@ public void onBefore(BaseRequest request) { /** 拿到响应后,将数据转换成需要的格式,子线程中执行,可以是耗时操作 */ public abstract T parseNetworkResponse(Response response) throws Exception; + /** 用于网络错误时在子线程中执行数据耗时操作,子类可以根据自己的需要重写此方法 */ + public void parseNetworkFail(Call call, IOException e) { + } + /** 对返回数据进行操作的回调, UI线程 */ - public abstract void onResponse(boolean isFromCache, T t, Request request, @Nullable Response response); + public abstract void onSuccess(T t, Request request, @Nullable Response response); + + /** 缓存成功的回调,UI线程 */ + public void onCacheSuccess(T t, Request request, @Nullable Response response) { + } /** 请求失败,响应错误,数据解析错误等,都会回调该方法, UI线程 */ - public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) { + public void onError(Call call, @Nullable Response response, @Nullable Exception e) { if (e != null) e.printStackTrace(); } + /** 缓存失败的回调,UI线程 */ + public void onCacheError(Call call, @Nullable Response response, @Nullable Exception e) { + } + /** 请求网络结束后,UI线程 */ - public void onAfter(boolean isFromCache, @Nullable T t, Call call, @Nullable Response response, @Nullable Exception e) { + public void onAfter(@Nullable T t, Call call, @Nullable Response response, @Nullable Exception e) { } /** @@ -68,7 +104,7 @@ public Response parseNetworkResponse(Response response) throws Exception { } @Override - public void onResponse(boolean isFromCache, Object data, Request request, Response response) { + public void onSuccess(Object data, Request request, Response response) { } }; } \ No newline at end of file diff --git a/okhttputils/src/main/java/com/lzy/okhttputils/exception/OkHttpException.java b/okhttputils/src/main/java/com/lzy/okhttputils/exception/OkHttpException.java new file mode 100644 index 00000000..ed9f5343 --- /dev/null +++ b/okhttputils/src/main/java/com/lzy/okhttputils/exception/OkHttpException.java @@ -0,0 +1,33 @@ +package com.lzy.okhttputils.exception; + +/** + * ================================================ + * 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy0216 + * 版 本:1.0 + * 创建日期:16/8/28 + * 描 述: + * 修订历史: + * ================================================ + */ +public class OkHttpException extends Exception { + + public static OkHttpException INSTANCE(String msg) { + return new OkHttpException(msg); + } + + public OkHttpException() { + super(); + } + + public OkHttpException(String detailMessage) { + super(detailMessage); + } + + public OkHttpException(String detailMessage, Throwable throwable) { + super(detailMessage, throwable); + } + + public OkHttpException(Throwable throwable) { + super(throwable); + } +} \ No newline at end of file diff --git a/okhttputils/src/main/java/com/lzy/okhttputils/model/HttpParams.java b/okhttputils/src/main/java/com/lzy/okhttputils/model/HttpParams.java index b033b8af..8ce3105c 100644 --- a/okhttputils/src/main/java/com/lzy/okhttputils/model/HttpParams.java +++ b/okhttputils/src/main/java/com/lzy/okhttputils/model/HttpParams.java @@ -25,6 +25,10 @@ public class HttpParams implements Serializable { private static final long serialVersionUID = 7369819159227055048L; + public static final MediaType MEDIA_TYPE_PLAIN = MediaType.parse("text/plain;charset=utf-8"); + public static final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json;charset=utf-8"); + public static final MediaType MEDIA_TYPE_STREAM = MediaType.parse("application/octet-stream"); + /** 普通的键值对参数 */ public LinkedHashMap> urlParamsMap; @@ -144,6 +148,7 @@ public void clear() { private MediaType guessMimeType(String path) { FileNameMap fileNameMap = URLConnection.getFileNameMap(); + path = path.replace("#", ""); //解决文件名中含有#号异常的问题 String contentType = fileNameMap.getContentTypeFor(path); if (contentType == null) { contentType = "application/octet-stream"; diff --git a/okhttputils/src/main/java/com/lzy/okhttputils/request/BaseBodyRequest.java b/okhttputils/src/main/java/com/lzy/okhttputils/request/BaseBodyRequest.java index 86b71f92..a9b3ee16 100644 --- a/okhttputils/src/main/java/com/lzy/okhttputils/request/BaseBodyRequest.java +++ b/okhttputils/src/main/java/com/lzy/okhttputils/request/BaseBodyRequest.java @@ -22,6 +22,11 @@ */ public abstract class BaseBodyRequest extends BaseRequest implements HasBody { + protected MediaType mediaType; //上传的MIME类型 + protected String string; //上传的文本内容 + protected String json; //上传的Json + protected byte[] bs; //上传的字节数据 + protected RequestBody requestBody; public BaseBodyRequest(String url) { @@ -70,9 +75,39 @@ public R params(String key, File file, String fileName, MediaType contentType) { return (R) this; } + /** 注意使用该方法上传字符串会清空实体中其他所有的参数,头信息不清除 */ + @SuppressWarnings("unchecked") + @Override + public R upString(String string) { + this.string = string; + this.mediaType = HttpParams.MEDIA_TYPE_PLAIN; + return (R) this; + } + + /** 注意使用该方法上传字符串会清空实体中其他所有的参数,头信息不清除 */ + @SuppressWarnings("unchecked") + @Override + public R upJson(String json) { + this.json = json; + this.mediaType = HttpParams.MEDIA_TYPE_JSON; + return (R) this; + } + + /** 注意使用该方法上传字符串会清空实体中其他所有的参数,头信息不清除 */ + @SuppressWarnings("unchecked") + @Override + public R upBytes(byte[] bs) { + this.bs = bs; + this.mediaType = HttpParams.MEDIA_TYPE_STREAM; + return (R) this; + } + @Override protected RequestBody generateRequestBody() { - if (requestBody != null) return requestBody; + if (requestBody != null) return requestBody; //自定义的请求体 + if (string != null && mediaType != null) return RequestBody.create(mediaType, string); //post上传字符串数据 + if (json != null && mediaType != null) return RequestBody.create(mediaType, json); //post上传json数据 + if (bs != null && mediaType != null) return RequestBody.create(mediaType, bs); //post上传字节数组 return HttpUtils.generateMultipartRequestBody(params); } } \ No newline at end of file diff --git a/okhttputils/src/main/java/com/lzy/okhttputils/request/BaseRequest.java b/okhttputils/src/main/java/com/lzy/okhttputils/request/BaseRequest.java index 50a0d6d6..5806e00b 100644 --- a/okhttputils/src/main/java/com/lzy/okhttputils/request/BaseRequest.java +++ b/okhttputils/src/main/java/com/lzy/okhttputils/request/BaseRequest.java @@ -2,12 +2,14 @@ import android.graphics.Bitmap; import android.support.annotation.NonNull; +import android.text.TextUtils; import com.lzy.okhttputils.OkHttpUtils; import com.lzy.okhttputils.cache.CacheEntity; import com.lzy.okhttputils.cache.CacheManager; import com.lzy.okhttputils.cache.CacheMode; import com.lzy.okhttputils.callback.AbsCallback; +import com.lzy.okhttputils.exception.OkHttpException; import com.lzy.okhttputils.https.HttpsUtils; import com.lzy.okhttputils.model.HttpHeaders; import com.lzy.okhttputils.model.HttpParams; @@ -64,6 +66,7 @@ public abstract class BaseRequest { private AbsCallback mCallback; private CacheManager cacheManager; private HttpUrl httpUrl; + private Request mRequest; public BaseRequest(String url) { this.url = url; @@ -71,6 +74,12 @@ public BaseRequest(String url) { httpUrl = HttpUrl.parse(url); OkHttpUtils okHttpUtils = OkHttpUtils.getInstance(); cacheManager = CacheManager.INSTANCE; + //默认添加 Accept-Language + String acceptLanguage = HttpHeaders.getAcceptLanguage(); + if (!TextUtils.isEmpty(acceptLanguage)) headers(HttpHeaders.HEAD_KEY_ACCEPT_LANGUAGE, acceptLanguage); + //默认添加 User-Agent + String userAgent = HttpHeaders.getUserAgent(); + if (!TextUtils.isEmpty(userAgent)) headers(HttpHeaders.HEAD_KEY_USER_AGENT, userAgent); //添加公共请求参数 if (okHttpUtils.getCommonParams() != null) params.put(okHttpUtils.getCommonParams()); if (okHttpUtils.getCommonHeaders() != null) headers.put(okHttpUtils.getCommonHeaders()); @@ -285,6 +294,18 @@ public long getCacheTime() { return cacheTime; } + public Request getRequest() { + return mRequest; + } + + /** + * 返回当前的请求方法 + * GET,POST,HEAD,PUT,DELETE,OPTIONS + */ + public String getMethod() { + return mRequest.method(); + } + /** 根据不同的请求方式和参数,生成不同的RequestBody */ protected abstract RequestBody generateRequestBody(); @@ -310,6 +331,7 @@ public void run() { /** 根据当前的请求参数,生成对应的 Call 任务 */ protected Call generateCall(Request request) { + mRequest = request; if (readTimeOut <= 0 && writeTimeOut <= 0 && connectTimeout <= 0 && sslParams == null && userCookies.size() == 0) { return OkHttpUtils.getInstance().getOkHttpClient().newCall(request); } else { @@ -332,11 +354,11 @@ protected Call generateCall(Request request) { /** 获取同步call对象 */ public Call getCall() { //添加缓存头和其他的公共头,同步请求不做缓存,缓存为空 - HeaderParser.addDefaultHeaders(this, null, null); + HeaderParser.addCacheHeaders(this, null, null); //构建请求体,返回call对象 RequestBody requestBody = generateRequestBody(); - Request request = generateRequest(wrapRequestBody(requestBody)); - return generateCall(request); + mRequest = generateRequest(wrapRequestBody(requestBody)); + return generateCall(mRequest); } /** 阻塞方法,同步请求执行 */ @@ -356,12 +378,16 @@ public void execute(AbsCallback callback) { //请求之前获取缓存信息,添加缓存头和其他的公共头 if (cacheKey == null) cacheKey = HttpUtils.createUrlFromParams(baseUrl, params.urlParamsMap); if (cacheMode == null) cacheMode = CacheMode.DEFAULT; - final CacheEntity cacheEntity = (CacheEntity) cacheManager.get(cacheKey); - //检查缓存的有效时间,判断缓存是否已经过期 - if (cacheEntity != null && cacheEntity.checkExpire(cacheMode, cacheTime, System.currentTimeMillis())) { - cacheEntity.setExpire(true); + //无缓存模式,不需要进入缓存逻辑 + CacheEntity cacheEntity = null; + if (cacheMode != CacheMode.NO_CACHE) { + cacheEntity = (CacheEntity) cacheManager.get(cacheKey); + //检查缓存的有效时间,判断缓存是否已经过期 + if (cacheEntity != null && cacheEntity.checkExpire(cacheMode, cacheTime, System.currentTimeMillis())) { + cacheEntity.setExpire(true); + } + HeaderParser.addCacheHeaders(this, cacheEntity, cacheMode); } - HeaderParser.addDefaultHeaders(this, cacheEntity, cacheMode); //构建请求 RequestBody requestBody = generateRequestBody(); Request request = generateRequest(wrapRequestBody(requestBody)); @@ -371,26 +397,42 @@ public void execute(AbsCallback callback) { //如果没有缓存,或者缓存过期,就请求网络,否者直接使用缓存 if (cacheEntity != null && !cacheEntity.isExpire()) { T data = cacheEntity.getData(); - sendSuccessResultCallback(true, data, call, null, mCallback); - return;//返回即不请求网络 + HttpHeaders headers = cacheEntity.getResponseHeaders(); + if (data == null || headers == null) { + //由于没有序列化等原因,可能导致数据为空 + sendFailResultCallback(true, call, null, OkHttpException.INSTANCE("没有获取到缓存,或者缓存已经过期!"), mCallback); + } else { + sendSuccessResultCallback(true, data, call, null, mCallback); + return;//获取缓存成功,不请求网络 + } } else { - sendFailResultCallback(true, call, null, new IllegalStateException("没有获取到缓存,或者缓存已经过期!"), mCallback); + sendFailResultCallback(true, call, null, OkHttpException.INSTANCE("没有获取到缓存,或者缓存已经过期!"), mCallback); } } else if (cacheMode == CacheMode.FIRST_CACHE_THEN_REQUEST) { //先使用缓存,不管是否存在,仍然请求网络 if (cacheEntity != null && !cacheEntity.isExpire()) { T data = cacheEntity.getData(); - sendSuccessResultCallback(true, data, call, null, mCallback); + HttpHeaders headers = cacheEntity.getResponseHeaders(); + if (data == null || headers == null) { + //由于没有序列化等原因,可能导致数据为空 + sendFailResultCallback(true, call, null, OkHttpException.INSTANCE("没有获取到缓存,或者缓存已经过期!"), mCallback); + } else { + sendSuccessResultCallback(true, data, call, null, mCallback); + } } else { - sendFailResultCallback(true, call, null, new IllegalStateException("没有获取到缓存,或者缓存已经过期!"), mCallback); + sendFailResultCallback(true, call, null, OkHttpException.INSTANCE("没有获取到缓存,或者缓存已经过期!"), mCallback); } } + final CacheEntity finalCacheEntity = cacheEntity; call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { - //请求失败,一般为url地址错误,网络错误等 - sendFailResultCallback(false, call, null, e, mCallback); + mCallback.parseNetworkFail(call, e); + //请求失败,一般为url地址错误,网络错误等,并且过滤用户主动取消的网络请求 + if (!"Canceled".equals(e.getMessage())) { + sendFailResultCallback(false, call, null, e, mCallback); + } } @Override @@ -398,17 +440,23 @@ public void onResponse(Call call, Response response) throws IOException { int responseCode = response.code(); //304缓存数据 if (responseCode == 304 && cacheMode == CacheMode.DEFAULT) { - if (cacheEntity == null) { - sendFailResultCallback(true, call, response, new IllegalStateException("服务器响应码304,但是客户端没有缓存!"), mCallback); + if (finalCacheEntity == null) { + sendFailResultCallback(true, call, response, OkHttpException.INSTANCE("服务器响应码304,但是客户端没有缓存!"), mCallback); } else { - T data = cacheEntity.getData(); - sendSuccessResultCallback(true, data, call, response, mCallback); + T data = finalCacheEntity.getData(); + HttpHeaders headers = finalCacheEntity.getResponseHeaders(); + if (data == null || headers == null) { + //由于没有序列化等原因,可能导致数据为空 + sendFailResultCallback(true, call, response, OkHttpException.INSTANCE("没有获取到缓存,或者缓存已经过期!"), mCallback); + } else { + sendSuccessResultCallback(true, data, call, response, mCallback); + } } return; } //响应失败,一般为服务器内部错误,或者找不到页面等 - if (responseCode >= 400 && responseCode <= 599) { - sendFailResultCallback(false, call, response, null, mCallback); + if (responseCode == 404 || responseCode >= 500) { + sendFailResultCallback(false, call, response, OkHttpException.INSTANCE("服务器数据异常!"), mCallback); return; } @@ -448,37 +496,57 @@ private void handleCache(Headers headers, T data) { /** 失败回调,发送到主线程 */ @SuppressWarnings("unchecked") - private void sendFailResultCallback(final boolean isFromCache, final Call call,// - final Response response, final Exception e, final AbsCallback callback) { - + private void sendFailResultCallback(final boolean isFromCache, final Call call, final Response response, final Exception e, final AbsCallback callback) { OkHttpUtils.getInstance().getDelivery().post(new Runnable() { @Override public void run() { - callback.onError(isFromCache, call, response, e); //请求失败回调 (UI线程) - callback.onAfter(isFromCache, null, call, response, e); //请求结束回调 (UI线程) + if (isFromCache) { + callback.onCacheError(call, response, e); //缓存失败回调 (UI线程) + if (cacheMode == CacheMode.DEFAULT || cacheMode == CacheMode.REQUEST_FAILED_READ_CACHE) { + callback.onAfter(null, call, response, e); //请求结束回调 (UI线程) + } + } else { + callback.onError(call, response, e); //请求失败回调 (UI线程) + if (cacheMode != CacheMode.REQUEST_FAILED_READ_CACHE) { + callback.onAfter(null, call, response, e); //请求结束回调 (UI线程) + } + } + } }); //不同的缓存模式,可能会导致该失败进入两次,一次缓存失败,一次网络请求失败 if (!isFromCache && cacheMode == CacheMode.REQUEST_FAILED_READ_CACHE) { CacheEntity cacheEntity = (CacheEntity) cacheManager.get(cacheKey); - if (cacheEntity != null) { + if (cacheEntity != null && !cacheEntity.isExpire()) { T data = cacheEntity.getData(); - sendSuccessResultCallback(true, data, call, response, callback); + HttpHeaders headers = cacheEntity.getResponseHeaders(); + if (data == null || headers == null) { + //由于没有序列化等原因,可能导致数据为空 + sendFailResultCallback(true, call, response, OkHttpException.INSTANCE("没有获取到缓存,或者缓存已经过期!"), callback); + } else { + sendSuccessResultCallback(true, data, call, response, callback); + } } else { - sendFailResultCallback(true, call, response, new IllegalStateException("请求网络失败后,无法读取缓存或者缓存不存在!"), callback); + sendFailResultCallback(true, call, response, OkHttpException.INSTANCE("没有获取到缓存,或者缓存已经过期!"), callback); } } } /** 成功回调,发送到主线程 */ - private void sendSuccessResultCallback(final boolean isFromCache, final T t, // - final Call call, final Response response, final AbsCallback callback) { + private void sendSuccessResultCallback(final boolean isFromCache, final T t, final Call call, final Response response, final AbsCallback callback) { OkHttpUtils.getInstance().getDelivery().post(new Runnable() { @Override public void run() { - callback.onResponse(isFromCache, t, call.request(), response); //请求成功回调 (UI线程) - callback.onAfter(isFromCache, t, call, response, null); //请求结束回调 (UI线程) + if (isFromCache) { + callback.onCacheSuccess(t, call.request(), response); //缓存成功回调 (UI线程) + if (cacheMode == CacheMode.DEFAULT || cacheMode == CacheMode.REQUEST_FAILED_READ_CACHE || cacheMode == CacheMode.IF_NONE_CACHE_REQUEST) { + callback.onAfter(t, call, response, null); //请求结束回调 (UI线程) + } + } else { + callback.onSuccess(t, call.request(), response); //请求成功回调 (UI线程) + callback.onAfter(t, call, response, null); //请求结束回调 (UI线程) + } } }); } diff --git a/okhttputils/src/main/java/com/lzy/okhttputils/request/DeleteRequest.java b/okhttputils/src/main/java/com/lzy/okhttputils/request/DeleteRequest.java index 2c72b1c2..7eb2176a 100644 --- a/okhttputils/src/main/java/com/lzy/okhttputils/request/DeleteRequest.java +++ b/okhttputils/src/main/java/com/lzy/okhttputils/request/DeleteRequest.java @@ -1,5 +1,6 @@ package com.lzy.okhttputils.request; +import com.lzy.okhttputils.model.HttpHeaders; import com.lzy.okhttputils.utils.HttpUtils; import com.lzy.okhttputils.utils.OkLogger; @@ -26,7 +27,7 @@ public DeleteRequest(String url) { @Override protected Request generateRequest(RequestBody requestBody) { try { - headers.put("Content-Length", String.valueOf(requestBody.contentLength())); + headers.put(HttpHeaders.HEAD_KEY_CONTENT_LENGTH, String.valueOf(requestBody.contentLength())); } catch (IOException e) { OkLogger.e(e); } diff --git a/okhttputils/src/main/java/com/lzy/okhttputils/request/HasBody.java b/okhttputils/src/main/java/com/lzy/okhttputils/request/HasBody.java index 6fa61404..e1a6b3cb 100644 --- a/okhttputils/src/main/java/com/lzy/okhttputils/request/HasBody.java +++ b/okhttputils/src/main/java/com/lzy/okhttputils/request/HasBody.java @@ -31,4 +31,10 @@ public interface HasBody { R params(String key, File file, String fileName); R params(String key, File file, String fileName, MediaType contentType); + + R upString(String string); + + R upJson(String json); + + R upBytes(byte[] bs); } \ No newline at end of file diff --git a/okhttputils/src/main/java/com/lzy/okhttputils/request/OptionsRequest.java b/okhttputils/src/main/java/com/lzy/okhttputils/request/OptionsRequest.java index d5b91ef6..12f1f432 100644 --- a/okhttputils/src/main/java/com/lzy/okhttputils/request/OptionsRequest.java +++ b/okhttputils/src/main/java/com/lzy/okhttputils/request/OptionsRequest.java @@ -1,5 +1,6 @@ package com.lzy.okhttputils.request; +import com.lzy.okhttputils.model.HttpHeaders; import com.lzy.okhttputils.utils.HttpUtils; import com.lzy.okhttputils.utils.OkLogger; @@ -26,7 +27,7 @@ public OptionsRequest(String url) { @Override protected Request generateRequest(RequestBody requestBody) { try { - headers.put("Content-Length", String.valueOf(requestBody.contentLength())); + headers.put(HttpHeaders.HEAD_KEY_CONTENT_LENGTH, String.valueOf(requestBody.contentLength())); } catch (IOException e) { OkLogger.e(e); } diff --git a/okhttputils/src/main/java/com/lzy/okhttputils/request/PostRequest.java b/okhttputils/src/main/java/com/lzy/okhttputils/request/PostRequest.java index d42e8560..bb953540 100644 --- a/okhttputils/src/main/java/com/lzy/okhttputils/request/PostRequest.java +++ b/okhttputils/src/main/java/com/lzy/okhttputils/request/PostRequest.java @@ -1,11 +1,11 @@ package com.lzy.okhttputils.request; +import com.lzy.okhttputils.model.HttpHeaders; import com.lzy.okhttputils.utils.HttpUtils; import com.lzy.okhttputils.utils.OkLogger; import java.io.IOException; -import okhttp3.MediaType; import okhttp3.Request; import okhttp3.RequestBody; @@ -20,58 +20,14 @@ */ public class PostRequest extends BaseBodyRequest { - public static final MediaType MEDIA_TYPE_PLAIN = MediaType.parse("text/plain;charset=utf-8"); - public static final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json;charset=utf-8"); - public static final MediaType MEDIA_TYPE_STREAM = MediaType.parse("application/octet-stream"); - - protected MediaType mediaType; //上传的MIME类型 - protected String string; //上传的文本内容 - protected String json; //上传的Json - protected byte[] bs; //上传的字节数据 - public PostRequest(String url) { super(url); } - /** 注意使用该方法上传字符串会清空实体中其他所有的参数,头信息不清除 */ - public PostRequest postString(String string) { - this.string = string; - this.mediaType = MEDIA_TYPE_PLAIN; - return this; - } - - /** 注意使用该方法上传字符串会清空实体中其他所有的参数,头信息不清除 */ - public PostRequest postJson(String json) { - this.json = json; - this.mediaType = MEDIA_TYPE_JSON; - return this; - } - - /** 注意使用该方法上传字符串会清空实体中其他所有的参数,头信息不清除 */ - public PostRequest postBytes(byte[] bs) { - this.bs = bs; - this.mediaType = MEDIA_TYPE_STREAM; - return this; - } - - public PostRequest mediaType(MediaType mediaType) { - this.mediaType = mediaType; - return this; - } - - @Override - protected RequestBody generateRequestBody() { - if (requestBody != null) return requestBody; //自定义的请求体 - if (string != null && mediaType != null) return RequestBody.create(mediaType, string); //post上传字符串数据 - if (json != null && mediaType != null) return RequestBody.create(mediaType, json); //post上传json数据 - if (bs != null && mediaType != null) return RequestBody.create(mediaType, bs); //post上传字节数组 - return HttpUtils.generateMultipartRequestBody(params); - } - @Override protected Request generateRequest(RequestBody requestBody) { try { - headers.put("Content-Length", String.valueOf(requestBody.contentLength())); + headers.put(HttpHeaders.HEAD_KEY_CONTENT_LENGTH, String.valueOf(requestBody.contentLength())); } catch (IOException e) { OkLogger.e(e); } diff --git a/okhttputils/src/main/java/com/lzy/okhttputils/request/PutRequest.java b/okhttputils/src/main/java/com/lzy/okhttputils/request/PutRequest.java index cfd0b6a7..043e0415 100644 --- a/okhttputils/src/main/java/com/lzy/okhttputils/request/PutRequest.java +++ b/okhttputils/src/main/java/com/lzy/okhttputils/request/PutRequest.java @@ -1,5 +1,6 @@ package com.lzy.okhttputils.request; +import com.lzy.okhttputils.model.HttpHeaders; import com.lzy.okhttputils.utils.HttpUtils; import com.lzy.okhttputils.utils.OkLogger; @@ -26,7 +27,7 @@ public PutRequest(String url) { @Override protected Request generateRequest(RequestBody requestBody) { try { - headers.put("Content-Length", String.valueOf(requestBody.contentLength())); + headers.put(HttpHeaders.HEAD_KEY_CONTENT_LENGTH, String.valueOf(requestBody.contentLength())); } catch (IOException e) { OkLogger.e(e); } diff --git a/okhttputils/src/main/java/com/lzy/okhttputils/utils/HeaderParser.java b/okhttputils/src/main/java/com/lzy/okhttputils/utils/HeaderParser.java index c24f4a3d..8409b645 100644 --- a/okhttputils/src/main/java/com/lzy/okhttputils/utils/HeaderParser.java +++ b/okhttputils/src/main/java/com/lzy/okhttputils/utils/HeaderParser.java @@ -119,7 +119,7 @@ public static CacheEntity createCacheEntity(Headers responseHeaders, T da * @param cacheEntity 缓存实体类 * @param cacheMode 缓存模式 */ - public static void addDefaultHeaders(BaseRequest request, CacheEntity cacheEntity, CacheMode cacheMode) { + public static void addCacheHeaders(BaseRequest request, CacheEntity cacheEntity, CacheMode cacheMode) { //1. 按照标准的 http 协议,添加304相关请求头 if (cacheEntity != null && cacheMode == CacheMode.DEFAULT) { HttpHeaders responseHeaders = cacheEntity.getResponseHeaders(); @@ -130,13 +130,5 @@ public static void addDefaultHeaders(BaseRequest request, CacheEntity cac if (lastModified > 0) request.headers(HttpHeaders.HEAD_KEY_IF_MODIFIED_SINCE, HttpHeaders.formatMillisToGMT(lastModified)); } } - - // 2. 添加 Accept-Language - String acceptLanguage = HttpHeaders.getAcceptLanguage(); - if (!TextUtils.isEmpty(acceptLanguage)) request.headers(HttpHeaders.HEAD_KEY_ACCEPT_LANGUAGE, acceptLanguage); - - // 3. 添加 UserAgent - String userAgent = HttpHeaders.getUserAgent(); - if (!TextUtils.isEmpty(userAgent)) request.headers(HttpHeaders.HEAD_KEY_USER_AGENT, userAgent); } }