Browse Source

集成公共框架

316044749 7 years ago
parent
commit
cfe207aff5
53 changed files with 2899 additions and 1 deletions
  1. 0 0
      app/src/main/java/com/ynstkz/shitu/android/activity/HomeActivity.java
  2. 1 0
      library/.gitignore
  3. 34 0
      library/build.gradle
  4. 21 0
      library/proguard-rules.pro
  5. 26 0
      library/src/androidTest/java/test/kotlin/com/library/ExampleInstrumentedTest.java
  6. 2 0
      library/src/main/AndroidManifest.xml
  7. 218 0
      library/src/main/java/okhttp/OkHttpUtils.java
  8. 66 0
      library/src/main/java/okhttp/builder/GetBuilder.java
  9. 12 0
      library/src/main/java/okhttp/builder/HasParamsable.java
  10. 17 0
      library/src/main/java/okhttp/builder/HeadBuilder.java
  11. 55 0
      library/src/main/java/okhttp/builder/OkHttpRequestBuilder.java
  12. 41 0
      library/src/main/java/okhttp/builder/OtherRequestBuilder.java
  13. 38 0
      library/src/main/java/okhttp/builder/PostFileBuilder.java
  14. 87 0
      library/src/main/java/okhttp/builder/PostFormBuilder.java
  15. 36 0
      library/src/main/java/okhttp/builder/PostStringBuilder.java
  16. 19 0
      library/src/main/java/okhttp/callback/BitmapCallback.java
  17. 82 0
      library/src/main/java/okhttp/callback/Callback.java
  18. 100 0
      library/src/main/java/okhttp/callback/FileCallBack.java
  19. 30 0
      library/src/main/java/okhttp/callback/GenericsCallback.java
  20. 8 0
      library/src/main/java/okhttp/callback/IGenericsSerializator.java
  21. 17 0
      library/src/main/java/okhttp/callback/StringCallback.java
  22. 41 0
      library/src/main/java/okhttp/cookie/CookieJarImpl.java
  23. 21 0
      library/src/main/java/okhttp/cookie/store/CookieStore.java
  24. 9 0
      library/src/main/java/okhttp/cookie/store/HasCookieStore.java
  25. 94 0
      library/src/main/java/okhttp/cookie/store/MemoryCookieStore.java
  26. 281 0
      library/src/main/java/okhttp/cookie/store/PersistentCookieStore.java
  27. 74 0
      library/src/main/java/okhttp/cookie/store/SerializableHttpCookie.java
  28. 232 0
      library/src/main/java/okhttp/https/HttpsUtils.java
  29. 165 0
      library/src/main/java/okhttp/log/LoggerInterceptor.java
  30. 92 0
      library/src/main/java/okhttp/request/CountingRequestBody.java
  31. 31 0
      library/src/main/java/okhttp/request/GetRequest.java
  32. 94 0
      library/src/main/java/okhttp/request/OkHttpRequest.java
  33. 74 0
      library/src/main/java/okhttp/request/OtherRequest.java
  34. 78 0
      library/src/main/java/okhttp/request/PostFileRequest.java
  35. 130 0
      library/src/main/java/okhttp/request/PostFormRequest.java
  36. 52 0
      library/src/main/java/okhttp/request/PostStringRequest.java
  37. 124 0
      library/src/main/java/okhttp/request/RequestCall.java
  38. 14 0
      library/src/main/java/okhttp/utils/Exceptions.java
  39. 196 0
      library/src/main/java/okhttp/utils/ImageUtils.java
  40. 21 0
      library/src/main/java/okhttp/utils/L.java
  41. 82 0
      library/src/main/java/okhttp/utils/Platform.java
  42. 8 0
      library/src/main/java/utils/AppVersionUtil.java
  43. 8 0
      library/src/main/java/utils/ArithUtil.java
  44. 8 0
      library/src/main/java/utils/DateUtils.java
  45. 8 0
      library/src/main/java/utils/FileUtils.java
  46. 8 0
      library/src/main/java/utils/JsonAssetsReaderUtil.java
  47. 8 0
      library/src/main/java/utils/LogUtil.java
  48. 8 0
      library/src/main/java/utils/MD5Utils.java
  49. 8 0
      library/src/main/java/utils/NetWorkUtil.java
  50. 8 0
      library/src/main/java/utils/PixelUtil.java
  51. 8 0
      library/src/main/java/utils/RegularUtils.java
  52. 3 0
      library/src/main/res/values/strings.xml
  53. 1 1
      app/src/test/java/com/ynstkz/shitu/android/ExampleUnitTest.java

app/src/main/java/com/ynstkz/shitu/android/HomeActivity.java → app/src/main/java/com/ynstkz/shitu/android/activity/HomeActivity.java


+ 1 - 0
library/.gitignore

@@ -0,0 +1 @@
+/build

+ 34 - 0
library/build.gradle

@@ -0,0 +1,34 @@
+apply plugin: 'com.android.library'
+
+android {
+    compileSdkVersion 26
+
+
+
+    defaultConfig {
+        minSdkVersion 16
+        targetSdkVersion 26
+        versionCode 1
+        versionName "1.0"
+
+        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
+
+    }
+
+    buildTypes {
+        release {
+            minifyEnabled false
+            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
+        }
+    }
+
+}
+
+dependencies {
+    implementation fileTree(dir: 'libs', include: ['*.jar'])
+
+    implementation 'com.android.support:appcompat-v7:26.1.0'
+    testImplementation 'junit:junit:4.12'
+    androidTestImplementation 'com.android.support.test:runner:1.0.1'
+    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
+}

+ 21 - 0
library/proguard-rules.pro

@@ -0,0 +1,21 @@
+# Add project specific ProGuard rules here.
+# You can control the set of applied configuration files using the
+# proguardFiles setting in build.gradle.
+#
+# For more details, see
+#   http://developer.android.com/guide/developing/tools/proguard.html
+
+# If your project uses WebView with JS, uncomment the following
+# and specify the fully qualified class name to the JavaScript interface
+# class:
+#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
+#   public *;
+#}
+
+# Uncomment this to preserve the line number information for
+# debugging stack traces.
+#-keepattributes SourceFile,LineNumberTable
+
+# If you keep the line number information, uncomment this to
+# hide the original source file name.
+#-renamesourcefileattribute SourceFile

+ 26 - 0
library/src/androidTest/java/test/kotlin/com/library/ExampleInstrumentedTest.java

@@ -0,0 +1,26 @@
+package test.kotlin.com.library;
+
+import android.content.Context;
+import android.support.test.InstrumentationRegistry;
+import android.support.test.runner.AndroidJUnit4;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import static org.junit.Assert.*;
+
+/**
+ * Instrumented test, which will execute on an Android device.
+ *
+ * @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
+ */
+@RunWith(AndroidJUnit4.class)
+public class ExampleInstrumentedTest {
+    @Test
+    public void useAppContext() throws Exception {
+        // Context of the app under test.
+        Context appContext = InstrumentationRegistry.getTargetContext();
+
+        assertEquals("test.kotlin.com.library.test", appContext.getPackageName());
+    }
+}

+ 2 - 0
library/src/main/AndroidManifest.xml

@@ -0,0 +1,2 @@
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="test.kotlin.com.library" />

+ 218 - 0
library/src/main/java/okhttp/OkHttpUtils.java

@@ -0,0 +1,218 @@
+package com.zhy.http.okhttp;
+
+import com.zhy.http.okhttp.builder.GetBuilder;
+import com.zhy.http.okhttp.builder.HeadBuilder;
+import com.zhy.http.okhttp.builder.OtherRequestBuilder;
+import com.zhy.http.okhttp.builder.PostFileBuilder;
+import com.zhy.http.okhttp.builder.PostFormBuilder;
+import com.zhy.http.okhttp.builder.PostStringBuilder;
+import com.zhy.http.okhttp.callback.Callback;
+import com.zhy.http.okhttp.request.RequestCall;
+import com.zhy.http.okhttp.utils.Platform;
+
+import java.io.IOException;
+import java.util.concurrent.Executor;
+
+import okhttp3.Call;
+import okhttp3.OkHttpClient;
+import okhttp3.Response;
+
+/**
+ * Created by zhy on 15/8/17.
+ */
+public class OkHttpUtils
+{
+    public static final long DEFAULT_MILLISECONDS = 10_000L;
+    private volatile static OkHttpUtils mInstance;
+    private OkHttpClient mOkHttpClient;
+    private Platform mPlatform;
+
+    public OkHttpUtils(OkHttpClient okHttpClient)
+    {
+        if (okHttpClient == null)
+        {
+            mOkHttpClient = new OkHttpClient();
+        } else
+        {
+            mOkHttpClient = okHttpClient;
+        }
+
+        mPlatform = Platform.get();
+    }
+
+
+    public static OkHttpUtils initClient(OkHttpClient okHttpClient)
+    {
+        if (mInstance == null)
+        {
+            synchronized (OkHttpUtils.class)
+            {
+                if (mInstance == null)
+                {
+                    mInstance = new OkHttpUtils(okHttpClient);
+                }
+            }
+        }
+        return mInstance;
+    }
+
+    public static OkHttpUtils getInstance()
+    {
+        return initClient(null);
+    }
+
+
+    public Executor getDelivery()
+    {
+        return mPlatform.defaultCallbackExecutor();
+    }
+
+    public OkHttpClient getOkHttpClient()
+    {
+        return mOkHttpClient;
+    }
+
+    public static GetBuilder get()
+    {
+        return new GetBuilder();
+    }
+
+    public static PostStringBuilder postString()
+    {
+        return new PostStringBuilder();
+    }
+
+    public static PostFileBuilder postFile()
+    {
+        return new PostFileBuilder();
+    }
+
+    public static PostFormBuilder post()
+    {
+        return new PostFormBuilder();
+    }
+
+    public static OtherRequestBuilder put()
+    {
+        return new OtherRequestBuilder(METHOD.PUT);
+    }
+
+    public static HeadBuilder head()
+    {
+        return new HeadBuilder();
+    }
+
+    public static OtherRequestBuilder delete()
+    {
+        return new OtherRequestBuilder(METHOD.DELETE);
+    }
+
+    public static OtherRequestBuilder patch()
+    {
+        return new OtherRequestBuilder(METHOD.PATCH);
+    }
+
+    public void execute(final RequestCall requestCall, Callback callback)
+    {
+        if (callback == null)
+            callback = Callback.CALLBACK_DEFAULT;
+        final Callback finalCallback = callback;
+        final int id = requestCall.getOkHttpRequest().getId();
+
+        requestCall.getCall().enqueue(new okhttp3.Callback()
+        {
+            @Override
+            public void onFailure(Call call, final IOException e)
+            {
+                sendFailResultCallback(call, e, finalCallback, id);
+            }
+
+            @Override
+            public void onResponse(final Call call, final Response response)
+            {
+                try
+                {
+                    if (call.isCanceled())
+                    {
+                        sendFailResultCallback(call, new IOException("Canceled!"), finalCallback, id);
+                        return;
+                    }
+
+                    if (!finalCallback.validateReponse(response, id))
+                    {
+                        sendFailResultCallback(call, new IOException("request failed , reponse's code is : " + response.code()), finalCallback, id);
+                        return;
+                    }
+
+                    Object o = finalCallback.parseNetworkResponse(response, id);
+                    sendSuccessResultCallback(o, finalCallback, id);
+                } catch (Exception e)
+                {
+                    sendFailResultCallback(call, e, finalCallback, id);
+                } finally
+                {
+                    if (response.body() != null)
+                        response.body().close();
+                }
+
+            }
+        });
+    }
+
+
+    public void sendFailResultCallback(final Call call, final Exception e, final Callback callback, final int id)
+    {
+        if (callback == null) return;
+
+        mPlatform.execute(new Runnable()
+        {
+            @Override
+            public void run()
+            {
+                callback.onError(call, e, id);
+                callback.onAfter(id);
+            }
+        });
+    }
+
+    public void sendSuccessResultCallback(final Object object, final Callback callback, final int id)
+    {
+        if (callback == null) return;
+        mPlatform.execute(new Runnable()
+        {
+            @Override
+            public void run()
+            {
+                callback.onResponse(object, id);
+                callback.onAfter(id);
+            }
+        });
+    }
+
+    public void cancelTag(Object tag)
+    {
+        for (Call call : mOkHttpClient.dispatcher().queuedCalls())
+        {
+            if (tag.equals(call.request().tag()))
+            {
+                call.cancel();
+            }
+        }
+        for (Call call : mOkHttpClient.dispatcher().runningCalls())
+        {
+            if (tag.equals(call.request().tag()))
+            {
+                call.cancel();
+            }
+        }
+    }
+
+    public static class METHOD
+    {
+        public static final String HEAD = "HEAD";
+        public static final String DELETE = "DELETE";
+        public static final String PUT = "PUT";
+        public static final String PATCH = "PATCH";
+    }
+}
+

+ 66 - 0
library/src/main/java/okhttp/builder/GetBuilder.java

@@ -0,0 +1,66 @@
+package com.zhy.http.okhttp.builder;
+
+import android.net.Uri;
+
+import com.zhy.http.okhttp.request.GetRequest;
+import com.zhy.http.okhttp.request.RequestCall;
+
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * Created by zhy on 15/12/14.
+ */
+public class GetBuilder extends OkHttpRequestBuilder<GetBuilder> implements HasParamsable
+{
+    @Override
+    public RequestCall build()
+    {
+        if (params != null)
+        {
+            url = appendParams(url, params);
+        }
+
+        return new GetRequest(url, tag, params, headers,id).build();
+    }
+
+    protected String appendParams(String url, Map<String, String> params)
+    {
+        if (url == null || params == null || params.isEmpty())
+        {
+            return url;
+        }
+        Uri.Builder builder = Uri.parse(url).buildUpon();
+        Set<String> keys = params.keySet();
+        Iterator<String> iterator = keys.iterator();
+        while (iterator.hasNext())
+        {
+            String key = iterator.next();
+            builder.appendQueryParameter(key, params.get(key));
+        }
+        return builder.build().toString();
+    }
+
+
+    @Override
+    public GetBuilder params(Map<String, String> params)
+    {
+        this.params = params;
+        return this;
+    }
+
+    @Override
+    public GetBuilder addParams(String key, String val)
+    {
+        if (this.params == null)
+        {
+            params = new LinkedHashMap<>();
+        }
+        params.put(key, val);
+        return this;
+    }
+
+
+}

+ 12 - 0
library/src/main/java/okhttp/builder/HasParamsable.java

@@ -0,0 +1,12 @@
+package com.zhy.http.okhttp.builder;
+
+import java.util.Map;
+
+/**
+ * Created by zhy on 16/3/1.
+ */
+public interface HasParamsable
+{
+    OkHttpRequestBuilder params(Map<String, String> params);
+    OkHttpRequestBuilder addParams(String key, String val);
+}

+ 17 - 0
library/src/main/java/okhttp/builder/HeadBuilder.java

@@ -0,0 +1,17 @@
+package com.zhy.http.okhttp.builder;
+
+import com.zhy.http.okhttp.OkHttpUtils;
+import com.zhy.http.okhttp.request.OtherRequest;
+import com.zhy.http.okhttp.request.RequestCall;
+
+/**
+ * Created by zhy on 16/3/2.
+ */
+public class HeadBuilder extends GetBuilder
+{
+    @Override
+    public RequestCall build()
+    {
+        return new OtherRequest(null, null, OkHttpUtils.METHOD.HEAD, url, tag, params, headers,id).build();
+    }
+}

+ 55 - 0
library/src/main/java/okhttp/builder/OkHttpRequestBuilder.java

@@ -0,0 +1,55 @@
+package com.zhy.http.okhttp.builder;
+
+import com.zhy.http.okhttp.request.RequestCall;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+/**
+ * Created by zhy on 15/12/14.
+ */
+public abstract class OkHttpRequestBuilder<T extends OkHttpRequestBuilder>
+{
+    protected String url;
+    protected Object tag;
+    protected Map<String, String> headers;
+    protected Map<String, String> params;
+    protected int id;
+
+    public T id(int id)
+    {
+        this.id = id;
+        return (T) this;
+    }
+
+    public T url(String url)
+    {
+        this.url = url;
+        return (T) this;
+    }
+
+
+    public T tag(Object tag)
+    {
+        this.tag = tag;
+        return (T) this;
+    }
+
+    public T headers(Map<String, String> headers)
+    {
+        this.headers = headers;
+        return (T) this;
+    }
+
+    public T addHeader(String key, String val)
+    {
+        if (this.headers == null)
+        {
+            headers = new LinkedHashMap<>();
+        }
+        headers.put(key, val);
+        return (T) this;
+    }
+
+    public abstract RequestCall build();
+}

+ 41 - 0
library/src/main/java/okhttp/builder/OtherRequestBuilder.java

@@ -0,0 +1,41 @@
+package com.zhy.http.okhttp.builder;
+
+import com.zhy.http.okhttp.request.OtherRequest;
+import com.zhy.http.okhttp.request.RequestCall;
+
+import okhttp3.RequestBody;
+
+/**
+ * DELETE、PUT、PATCH等其他方法
+ */
+public class OtherRequestBuilder extends OkHttpRequestBuilder<OtherRequestBuilder>
+{
+    private RequestBody requestBody;
+    private String method;
+    private String content;
+
+    public OtherRequestBuilder(String method)
+    {
+        this.method = method;
+    }
+
+    @Override
+    public RequestCall build()
+    {
+        return new OtherRequest(requestBody, content, method, url, tag, params, headers,id).build();
+    }
+
+    public OtherRequestBuilder requestBody(RequestBody requestBody)
+    {
+        this.requestBody = requestBody;
+        return this;
+    }
+
+    public OtherRequestBuilder requestBody(String content)
+    {
+        this.content = content;
+        return this;
+    }
+
+
+}

+ 38 - 0
library/src/main/java/okhttp/builder/PostFileBuilder.java

@@ -0,0 +1,38 @@
+package com.zhy.http.okhttp.builder;
+
+import com.zhy.http.okhttp.request.PostFileRequest;
+import com.zhy.http.okhttp.request.RequestCall;
+
+import java.io.File;
+
+import okhttp3.MediaType;
+
+/**
+ * Created by zhy on 15/12/14.
+ */
+public class PostFileBuilder extends OkHttpRequestBuilder<PostFileBuilder>
+{
+    private File file;
+    private MediaType mediaType;
+
+
+    public OkHttpRequestBuilder file(File file)
+    {
+        this.file = file;
+        return this;
+    }
+
+    public OkHttpRequestBuilder mediaType(MediaType mediaType)
+    {
+        this.mediaType = mediaType;
+        return this;
+    }
+
+    @Override
+    public RequestCall build()
+    {
+        return new PostFileRequest(url, tag, params, headers, file, mediaType,id).build();
+    }
+
+
+}

+ 87 - 0
library/src/main/java/okhttp/builder/PostFormBuilder.java

@@ -0,0 +1,87 @@
+package com.zhy.http.okhttp.builder;
+
+import com.zhy.http.okhttp.request.PostFormRequest;
+import com.zhy.http.okhttp.request.RequestCall;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Created by zhy on 15/12/14.
+ */
+public class PostFormBuilder extends OkHttpRequestBuilder<PostFormBuilder> implements HasParamsable
+{
+    private List<FileInput> files = new ArrayList<>();
+
+    @Override
+    public RequestCall build()
+    {
+        return new PostFormRequest(url, tag, params, headers, files,id).build();
+    }
+
+    public PostFormBuilder files(String key, Map<String, File> files)
+    {
+        for (String filename : files.keySet())
+        {
+            this.files.add(new FileInput(key, filename, files.get(filename)));
+        }
+        return this;
+    }
+
+    public PostFormBuilder addFile(String name, String filename, File file)
+    {
+        files.add(new FileInput(name, filename, file));
+        return this;
+    }
+
+    public static class FileInput
+    {
+        public String key;
+        public String filename;
+        public File file;
+
+        public FileInput(String name, String filename, File file)
+        {
+            this.key = name;
+            this.filename = filename;
+            this.file = file;
+        }
+
+        @Override
+        public String toString()
+        {
+            return "FileInput{" +
+                    "key='" + key + '\'' +
+                    ", filename='" + filename + '\'' +
+                    ", file=" + file +
+                    '}';
+        }
+    }
+
+
+
+    @Override
+    public PostFormBuilder params(Map<String, String> params)
+    {
+        this.params = params;
+        return this;
+    }
+
+    @Override
+    public PostFormBuilder addParams(String key, String val)
+    {
+        if (this.params == null)
+        {
+            params = new LinkedHashMap<>();
+        }
+        params.put(key, val);
+        return this;
+    }
+
+
+
+
+}

+ 36 - 0
library/src/main/java/okhttp/builder/PostStringBuilder.java

@@ -0,0 +1,36 @@
+package com.zhy.http.okhttp.builder;
+
+import com.zhy.http.okhttp.request.PostStringRequest;
+import com.zhy.http.okhttp.request.RequestCall;
+
+import okhttp3.MediaType;
+
+/**
+ * Created by zhy on 15/12/14.
+ */
+public class PostStringBuilder extends OkHttpRequestBuilder<PostStringBuilder>
+{
+    private String content;
+    private MediaType mediaType;
+
+
+    public PostStringBuilder content(String content)
+    {
+        this.content = content;
+        return this;
+    }
+
+    public PostStringBuilder mediaType(MediaType mediaType)
+    {
+        this.mediaType = mediaType;
+        return this;
+    }
+
+    @Override
+    public RequestCall build()
+    {
+        return new PostStringRequest(url, tag, params, headers, content, mediaType,id).build();
+    }
+
+
+}

+ 19 - 0
library/src/main/java/okhttp/callback/BitmapCallback.java

@@ -0,0 +1,19 @@
+package com.zhy.http.okhttp.callback;
+
+import android.graphics.Bitmap;
+import android.graphics.BitmapFactory;
+
+import okhttp3.Response;
+
+/**
+ * Created by zhy on 15/12/14.
+ */
+public abstract class BitmapCallback extends Callback<Bitmap>
+{
+    @Override
+    public Bitmap parseNetworkResponse(Response response , int id) throws Exception
+    {
+        return BitmapFactory.decodeStream(response.body().byteStream());
+    }
+
+}

+ 82 - 0
library/src/main/java/okhttp/callback/Callback.java

@@ -0,0 +1,82 @@
+package com.zhy.http.okhttp.callback;
+
+import okhttp3.Call;
+import okhttp3.Request;
+import okhttp3.Response;
+
+public abstract class Callback<T>
+{
+    /**
+     * UI Thread
+     *
+     * @param request
+     */
+    public void onBefore(Request request, int id)
+    {
+    }
+
+    /**
+     * UI Thread
+     *
+     * @param
+     */
+    public void onAfter(int id)
+    {
+    }
+
+    /**
+     * UI Thread
+     *
+     * @param progress
+     */
+    public void inProgress(float progress, long total , int id)
+    {
+
+    }
+
+    /**
+     * if you parse reponse code in parseNetworkResponse, you should make this method return true.
+     *
+     * @param response
+     * @return
+     */
+    public boolean validateReponse(Response response, int id)
+    {
+        return response.isSuccessful();
+    }
+
+    /**
+     * Thread Pool Thread
+     *
+     * @param response
+     */
+    public abstract T parseNetworkResponse(Response response, int id) throws Exception;
+
+    public abstract void onError(Call call, Exception e, int id);
+
+    public abstract void onResponse(T response, int id);
+
+
+    public static Callback CALLBACK_DEFAULT = new Callback()
+    {
+
+        @Override
+        public Object parseNetworkResponse(Response response, int id) throws Exception
+        {
+            return null;
+        }
+
+        @Override
+        public void onError(Call call, Exception e, int id)
+        {
+
+        }
+
+        @Override
+        public void onResponse(Object response, int id)
+        {
+
+        }
+    };
+
+}

+ 100 - 0
library/src/main/java/okhttp/callback/FileCallBack.java

@@ -0,0 +1,100 @@
+package com.zhy.http.okhttp.callback;
+
+import com.zhy.http.okhttp.OkHttpUtils;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+
+import okhttp3.Response;
+
+/**
+ * Created by zhy on 15/12/15.
+ */
+public abstract class FileCallBack extends Callback<File>
+{
+    /**
+     * 目标文件存储的文件夹路径
+     */
+    private String destFileDir;
+    /**
+     * 目标文件存储的文件名
+     */
+    private String destFileName;
+
+
+    public FileCallBack(String destFileDir, String destFileName)
+    {
+        this.destFileDir = destFileDir;
+        this.destFileName = destFileName;
+    }
+
+
+    @Override
+    public File parseNetworkResponse(Response response, int id) throws Exception
+    {
+        return saveFile(response,id);
+    }
+
+
+    public File saveFile(Response response,final int id) throws IOException
+    {
+        InputStream is = null;
+        byte[] buf = new byte[2048];
+        int len = 0;
+        FileOutputStream fos = null;
+        try
+        {
+            is = response.body().byteStream();
+            final long total = response.body().contentLength();
+
+            long sum = 0;
+
+            File dir = new File(destFileDir);
+            if (!dir.exists())
+            {
+                dir.mkdirs();
+            }
+            File file = new File(dir, destFileName);
+            fos = new FileOutputStream(file);
+            while ((len = is.read(buf)) != -1)
+            {
+                sum += len;
+                fos.write(buf, 0, len);
+                final long finalSum = sum;
+                OkHttpUtils.getInstance().getDelivery().execute(new Runnable()
+                {
+                    @Override
+                    public void run()
+                    {
+
+                        inProgress(finalSum * 1.0f / total,total,id);
+                    }
+                });
+            }
+            fos.flush();
+
+            return file;
+
+        } finally
+        {
+            try
+            {
+                response.body().close();
+                if (is != null) is.close();
+            } catch (IOException e)
+            {
+            }
+            try
+            {
+                if (fos != null) fos.close();
+            } catch (IOException e)
+            {
+            }
+
+        }
+    }
+
+
+}

+ 30 - 0
library/src/main/java/okhttp/callback/GenericsCallback.java

@@ -0,0 +1,30 @@
+package com.zhy.http.okhttp.callback;
+
+import java.io.IOException;
+import java.lang.reflect.ParameterizedType;
+
+import okhttp3.Response;
+
+/**
+ * Created by JimGong on 2016/6/23.
+ */
+
+public abstract class GenericsCallback<T> extends Callback<T> {
+    IGenericsSerializator mGenericsSerializator;
+
+    public GenericsCallback(IGenericsSerializator serializator) {
+        mGenericsSerializator = serializator;
+    }
+
+    @Override
+    public T parseNetworkResponse(Response response, int id) throws IOException {
+        String string = response.body().string();
+        Class<T> entityClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
+        if (entityClass == String.class) {
+            return (T) string;
+        }
+        T bean = mGenericsSerializator.transform(string, entityClass);
+        return bean;
+    }
+
+}

+ 8 - 0
library/src/main/java/okhttp/callback/IGenericsSerializator.java

@@ -0,0 +1,8 @@
+package com.zhy.http.okhttp.callback;
+
+/**
+ * Created by JimGong on 2016/6/23.
+ */
+public interface IGenericsSerializator {
+    <T> T transform(String response, Class<T> classOfT);
+}

+ 17 - 0
library/src/main/java/okhttp/callback/StringCallback.java

@@ -0,0 +1,17 @@
+package com.zhy.http.okhttp.callback;
+
+import java.io.IOException;
+
+import okhttp3.Response;
+
+/**
+ * Created by zhy on 15/12/14.
+ */
+public abstract class StringCallback extends Callback<String>
+{
+    @Override
+    public String parseNetworkResponse(Response response, int id) throws IOException
+    {
+        return response.body().string();
+    }
+}

+ 41 - 0
library/src/main/java/okhttp/cookie/CookieJarImpl.java

@@ -0,0 +1,41 @@
+package com.zhy.http.okhttp.cookie;
+
+import com.zhy.http.okhttp.cookie.store.CookieStore;
+import com.zhy.http.okhttp.utils.Exceptions;
+
+import java.util.List;
+
+import okhttp3.Cookie;
+import okhttp3.CookieJar;
+import okhttp3.HttpUrl;
+
+/**
+ * Created by zhy on 16/3/10.
+ */
+public class CookieJarImpl implements CookieJar
+{
+    private CookieStore cookieStore;
+
+    public CookieJarImpl(CookieStore cookieStore)
+    {
+        if (cookieStore == null) Exceptions.illegalArgument("cookieStore can not be null.");
+        this.cookieStore = cookieStore;
+    }
+
+    @Override
+    public synchronized void saveFromResponse(HttpUrl url, List<Cookie> cookies)
+    {
+        cookieStore.add(url, cookies);
+    }
+
+    @Override
+    public synchronized List<Cookie> loadForRequest(HttpUrl url)
+    {
+        return cookieStore.get(url);
+    }
+
+    public CookieStore getCookieStore()
+    {
+        return cookieStore;
+    }
+}

+ 21 - 0
library/src/main/java/okhttp/cookie/store/CookieStore.java

@@ -0,0 +1,21 @@
+package com.zhy.http.okhttp.cookie.store;
+
+import java.util.List;
+
+import okhttp3.Cookie;
+import okhttp3.HttpUrl;
+
+public interface CookieStore
+{
+
+    void add(HttpUrl uri, List<Cookie> cookie);
+
+    List<Cookie> get(HttpUrl uri);
+
+    List<Cookie> getCookies();
+
+    boolean remove(HttpUrl uri, Cookie cookie);
+
+    boolean removeAll();
+
+}

+ 9 - 0
library/src/main/java/okhttp/cookie/store/HasCookieStore.java

@@ -0,0 +1,9 @@
+package com.zhy.http.okhttp.cookie.store;
+
+/**
+ * Created by zhy on 16/3/10.
+ */
+public interface HasCookieStore
+{
+    CookieStore getCookieStore();
+}

+ 94 - 0
library/src/main/java/okhttp/cookie/store/MemoryCookieStore.java

@@ -0,0 +1,94 @@
+package com.zhy.http.okhttp.cookie.store;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+
+import okhttp3.Cookie;
+import okhttp3.HttpUrl;
+
+/**
+ * Created by zhy on 16/3/10.
+ */
+public class MemoryCookieStore implements CookieStore
+{
+    private final HashMap<String, List<Cookie>> allCookies = new HashMap<>();
+
+    @Override
+    public void add(HttpUrl url, List<Cookie> cookies)
+    {
+        List<Cookie> oldCookies = allCookies.get(url.host());
+
+        if (oldCookies != null)
+        {
+            Iterator<Cookie> itNew = cookies.iterator();
+            Iterator<Cookie> itOld = oldCookies.iterator();
+            while (itNew.hasNext())
+            {
+                String va = itNew.next().name();
+                while (va != null && itOld.hasNext())
+                {
+                    String v = itOld.next().name();
+                    if (v != null && va.equals(v))
+                    {
+                        itOld.remove();
+                    }
+                }
+            }
+            oldCookies.addAll(cookies);
+        } else
+        {
+            allCookies.put(url.host(), cookies);
+        }
+
+
+    }
+
+    @Override
+    public List<Cookie> get(HttpUrl uri)
+    {
+        List<Cookie> cookies = allCookies.get(uri.host());
+        if (cookies == null)
+        {
+            cookies = new ArrayList<>();
+            allCookies.put(uri.host(), cookies);
+        }
+        return cookies;
+
+    }
+
+    @Override
+    public boolean removeAll()
+    {
+        allCookies.clear();
+        return true;
+    }
+
+    @Override
+    public List<Cookie> getCookies()
+    {
+        List<Cookie> cookies = new ArrayList<>();
+        Set<String> httpUrls = allCookies.keySet();
+        for (String url : httpUrls)
+        {
+            cookies.addAll(allCookies.get(url));
+        }
+        return cookies;
+    }
+
+
+    @Override
+    public boolean remove(HttpUrl uri, Cookie cookie)
+    {
+        List<Cookie> cookies = allCookies.get(uri.host());
+        if (cookie != null)
+        {
+            return cookies.remove(cookie);
+        }
+        return false;
+    }
+
+
+}

+ 281 - 0
library/src/main/java/okhttp/cookie/store/PersistentCookieStore.java

@@ -0,0 +1,281 @@
+package com.zhy.http.okhttp.cookie.store;
+
+import android.content.Context;
+import android.content.SharedPreferences;
+import android.text.TextUtils;
+import android.util.Log;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+import okhttp3.Cookie;
+import okhttp3.HttpUrl;
+
+/**
+ * <pre>
+ *     OkHttpClient client = new OkHttpClient.Builder()
+ *             .cookieJar(new JavaNetCookieJar(new CookieManager(
+ *                     new PersistentCookieStore(getApplicationContext()),
+ *                             CookiePolicy.ACCEPT_ALL))
+ *             .build();
+ *
+ * </pre>
+ * <p/>
+ * from http://stackoverflow.com/questions/25461792/persistent-cookie-store-using-okhttp-2-on-android
+ * <p/>
+ * <br/>
+ * A persistent cookie store which implements the Apache HttpClient CookieStore interface.
+ * Cookies are stored and will persist on the user's device between application sessions since they
+ * are serialized and stored in SharedPreferences. Instances of this class are
+ * designed to be used with AsyncHttpClient#setCookieStore, but can also be used with a
+ * regular old apache HttpClient/HttpContext if you prefer.
+ */
+public class PersistentCookieStore implements CookieStore
+{
+
+    private static final String LOG_TAG = "PersistentCookieStore";
+    private static final String COOKIE_PREFS = "CookiePrefsFile";
+    private static final String COOKIE_NAME_PREFIX = "cookie_";
+
+    private final HashMap<String, ConcurrentHashMap<String, Cookie>> cookies;
+    private final SharedPreferences cookiePrefs;
+
+    /**
+     * Construct a persistent cookie store.
+     *
+     * @param context Context to attach cookie store to
+     */
+    public PersistentCookieStore(Context context)
+    {
+        cookiePrefs = context.getSharedPreferences(COOKIE_PREFS, 0);
+        cookies = new HashMap<String, ConcurrentHashMap<String, Cookie>>();
+
+        // Load any previously stored cookies into the store
+        Map<String, ?> prefsMap = cookiePrefs.getAll();
+        for (Map.Entry<String, ?> entry : prefsMap.entrySet())
+        {
+            if (((String) entry.getValue()) != null && !((String) entry.getValue()).startsWith(COOKIE_NAME_PREFIX))
+            {
+                String[] cookieNames = TextUtils.split((String) entry.getValue(), ",");
+                for (String name : cookieNames)
+                {
+                    String encodedCookie = cookiePrefs.getString(COOKIE_NAME_PREFIX + name, null);
+                    if (encodedCookie != null)
+                    {
+                        Cookie decodedCookie = decodeCookie(encodedCookie);
+                        if (decodedCookie != null)
+                        {
+                            if (!cookies.containsKey(entry.getKey()))
+                                cookies.put(entry.getKey(), new ConcurrentHashMap<String, Cookie>());
+                            cookies.get(entry.getKey()).put(name, decodedCookie);
+                        }
+                    }
+                }
+
+            }
+        }
+    }
+
+    protected void add(HttpUrl uri, Cookie cookie)
+    {
+        String name = getCookieToken(cookie);
+
+        if (cookie.persistent())
+        {
+            if (!cookies.containsKey(uri.host()))
+            {
+                cookies.put(uri.host(), new ConcurrentHashMap<String, Cookie>());
+            }
+            cookies.get(uri.host()).put(name, cookie);
+        } else
+        {
+            if (cookies.containsKey(uri.host()))
+            {
+                cookies.get(uri.host()).remove(name);
+            }else
+            {
+                return ;
+            }
+        }
+
+        // Save cookie into persistent store
+        SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
+        prefsWriter.putString(uri.host(), TextUtils.join(",", cookies.get(uri.host()).keySet()));
+        prefsWriter.putString(COOKIE_NAME_PREFIX + name, encodeCookie(new SerializableHttpCookie(cookie)));
+        prefsWriter.apply();
+    }
+
+    protected String getCookieToken(Cookie cookie)
+    {
+        return cookie.name() + cookie.domain();
+    }
+
+    @Override
+    public void add(HttpUrl uri, List<Cookie> cookies)
+    {
+        for (Cookie cookie : cookies)
+        {
+            add(uri, cookie);
+        }
+    }
+
+    @Override
+    public List<Cookie> get(HttpUrl uri)
+    {
+        ArrayList<Cookie> ret = new ArrayList<Cookie>();
+        if (cookies.containsKey(uri.host()))
+        {
+            Collection<Cookie> cookies = this.cookies.get(uri.host()).values();
+            for (Cookie cookie : cookies)
+            {
+                if (isCookieExpired(cookie))
+                {
+                    remove(uri, cookie);
+                } else
+                {
+                    ret.add(cookie);
+                }
+            }
+        }
+
+        return ret;
+    }
+
+    private static boolean isCookieExpired(Cookie cookie)
+    {
+        return cookie.expiresAt() < System.currentTimeMillis();
+    }
+
+    @Override
+    public boolean removeAll()
+    {
+        SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
+        prefsWriter.clear();
+        prefsWriter.apply();
+        cookies.clear();
+        return true;
+    }
+
+
+    @Override
+    public boolean remove(HttpUrl uri, Cookie cookie)
+    {
+        String name = getCookieToken(cookie);
+
+        if (cookies.containsKey(uri.host()) && cookies.get(uri.host()).containsKey(name))
+        {
+            cookies.get(uri.host()).remove(name);
+
+            SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
+            if (cookiePrefs.contains(COOKIE_NAME_PREFIX + name))
+            {
+                prefsWriter.remove(COOKIE_NAME_PREFIX + name);
+            }
+            prefsWriter.putString(uri.host(), TextUtils.join(",", cookies.get(uri.host()).keySet()));
+            prefsWriter.apply();
+
+            return true;
+        } else
+        {
+            return false;
+        }
+    }
+
+    @Override
+    public List<Cookie> getCookies()
+    {
+        ArrayList<Cookie> ret = new ArrayList<Cookie>();
+        for (String key : cookies.keySet())
+            ret.addAll(cookies.get(key).values());
+
+        return ret;
+    }
+
+
+    protected String encodeCookie(SerializableHttpCookie cookie)
+    {
+        if (cookie == null)
+            return null;
+        ByteArrayOutputStream os = new ByteArrayOutputStream();
+        try
+        {
+            ObjectOutputStream outputStream = new ObjectOutputStream(os);
+            outputStream.writeObject(cookie);
+        } catch (IOException e)
+        {
+            Log.d(LOG_TAG, "IOException in encodeCookie", e);
+            return null;
+        }
+
+        return byteArrayToHexString(os.toByteArray());
+    }
+
+    protected Cookie decodeCookie(String cookieString)
+    {
+        byte[] bytes = hexStringToByteArray(cookieString);
+        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
+        Cookie cookie = null;
+        try
+        {
+            ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
+            cookie = ((SerializableHttpCookie) objectInputStream.readObject()).getCookie();
+        } catch (IOException e)
+        {
+            Log.d(LOG_TAG, "IOException in decodeCookie", e);
+        } catch (ClassNotFoundException e)
+        {
+            Log.d(LOG_TAG, "ClassNotFoundException in decodeCookie", e);
+        }
+
+        return cookie;
+    }
+
+    /**
+     * Using some super basic byte array &lt;-&gt; hex conversions so we don't have to rely on any
+     * large Base64 libraries. Can be overridden if you like!
+     *
+     * @param bytes byte array to be converted
+     * @return string containing hex values
+     */
+    protected String byteArrayToHexString(byte[] bytes)
+    {
+        StringBuilder sb = new StringBuilder(bytes.length * 2);
+        for (byte element : bytes)
+        {
+            int v = element & 0xff;
+            if (v < 16)
+            {
+                sb.append('0');
+            }
+            sb.append(Integer.toHexString(v));
+        }
+        return sb.toString().toUpperCase(Locale.US);
+    }
+
+    /**
+     * Converts hex values from strings to byte arra
+     *
+     * @param hexString string of hex-encoded values
+     * @return decoded byte array
+     */
+    protected byte[] hexStringToByteArray(String hexString)
+    {
+        int len = hexString.length();
+        byte[] data = new byte[len / 2];
+        for (int i = 0; i < len; i += 2)
+        {
+            data[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character.digit(hexString.charAt(i + 1), 16));
+        }
+        return data;
+    }
+}

+ 74 - 0
library/src/main/java/okhttp/cookie/store/SerializableHttpCookie.java

@@ -0,0 +1,74 @@
+package com.zhy.http.okhttp.cookie.store;
+
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.io.Serializable;
+
+import okhttp3.Cookie;
+
+/**
+ * from http://stackoverflow.com/questions/25461792/persistent-cookie-store-using-okhttp-2-on-android
+ * and<br/>
+ * http://www.geebr.com/post/okHttp3%E4%B9%8BCookies%E7%AE%A1%E7%90%86%E5%8F%8A%E6%8C%81%E4%B9%85%E5%8C%96
+ */
+
+public class SerializableHttpCookie implements Serializable
+{
+    private static final long serialVersionUID = 6374381323722046732L;
+
+    private transient final Cookie cookie;
+    private transient Cookie clientCookie;
+
+    public SerializableHttpCookie(Cookie cookie)
+    {
+        this.cookie = cookie;
+    }
+
+    public Cookie getCookie()
+    {
+        Cookie bestCookie = cookie;
+        if (clientCookie != null)
+        {
+            bestCookie = clientCookie;
+        }
+
+        return bestCookie;
+    }
+
+    private void writeObject(ObjectOutputStream out) throws IOException
+    {
+        out.writeObject(cookie.name());
+        out.writeObject(cookie.value());
+        out.writeLong(cookie.expiresAt());
+        out.writeObject(cookie.domain());
+        out.writeObject(cookie.path());
+        out.writeBoolean(cookie.secure());
+        out.writeBoolean(cookie.httpOnly());
+        out.writeBoolean(cookie.hostOnly());
+        out.writeBoolean(cookie.persistent());
+    }
+
+    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException
+    {
+        String name = (String) in.readObject();
+        String value = (String) in.readObject();
+        long expiresAt = in.readLong();
+        String domain = (String) in.readObject();
+        String path = (String) in.readObject();
+        boolean secure = in.readBoolean();
+        boolean httpOnly = in.readBoolean();
+        boolean hostOnly = in.readBoolean();
+        boolean persistent = in.readBoolean();
+        Cookie.Builder builder = new Cookie.Builder();
+        builder = builder.name(name);
+        builder = builder.value(value);
+        builder = builder.expiresAt(expiresAt);
+        builder = hostOnly ? builder.hostOnlyDomain(domain) : builder.domain(domain);
+        builder = builder.path(path);
+        builder = secure ? builder.secure() : builder;
+        builder = httpOnly ? builder.httpOnly() : builder;
+        clientCookie = builder.build();
+
+    }
+}

+ 232 - 0
library/src/main/java/okhttp/https/HttpsUtils.java

@@ -0,0 +1,232 @@
+package com.zhy.http.okhttp.https;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.security.KeyManagementException;
+import java.security.KeyStore;
+import java.security.KeyStoreException;
+import java.security.NoSuchAlgorithmException;
+import java.security.UnrecoverableKeyException;
+import java.security.cert.CertificateException;
+import java.security.cert.CertificateFactory;
+import java.security.cert.X509Certificate;
+
+import javax.net.ssl.HostnameVerifier;
+import javax.net.ssl.KeyManager;
+import javax.net.ssl.KeyManagerFactory;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLSession;
+import javax.net.ssl.SSLSocketFactory;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.TrustManagerFactory;
+import javax.net.ssl.X509TrustManager;
+
+/**
+ * Created by zhy on 15/12/14.
+ */
+public class HttpsUtils
+{
+    public static class SSLParams
+    {
+        public SSLSocketFactory sSLSocketFactory;
+        public X509TrustManager trustManager;
+    }
+
+    public static SSLParams getSslSocketFactory(InputStream[] certificates, InputStream bksFile, String password)
+    {
+        SSLParams sslParams = new SSLParams();
+        try
+        {
+            TrustManager[] trustManagers = prepareTrustManager(certificates);
+            KeyManager[] keyManagers = prepareKeyManager(bksFile, password);
+            SSLContext sslContext = SSLContext.getInstance("TLS");
+            X509TrustManager trustManager = null;
+            if (trustManagers != null)
+            {
+                trustManager = new MyTrustManager(chooseTrustManager(trustManagers));
+            } else
+            {
+                trustManager = new UnSafeTrustManager();
+            }
+            sslContext.init(keyManagers, new TrustManager[]{trustManager},null);
+            sslParams.sSLSocketFactory = sslContext.getSocketFactory();
+            sslParams.trustManager = trustManager;
+            return sslParams;
+        } catch (NoSuchAlgorithmException e)
+        {
+            throw new AssertionError(e);
+        } catch (KeyManagementException e)
+        {
+            throw new AssertionError(e);
+        } catch (KeyStoreException e)
+        {
+            throw new AssertionError(e);
+        }
+    }
+
+    private class UnSafeHostnameVerifier implements HostnameVerifier
+    {
+        @Override
+        public boolean verify(String hostname, SSLSession session)
+        {
+            return true;
+        }
+    }
+
+    private static class UnSafeTrustManager implements X509TrustManager
+    {
+        @Override
+        public void checkClientTrusted(X509Certificate[] chain, String authType)
+                throws CertificateException
+        {
+        }
+
+        @Override
+        public void checkServerTrusted(X509Certificate[] chain, String authType)
+                throws CertificateException
+        {
+        }
+
+        @Override
+        public X509Certificate[] getAcceptedIssuers()
+        {
+            return new java.security.cert.X509Certificate[]{};
+        }
+    }
+
+    private static TrustManager[] prepareTrustManager(InputStream... certificates)
+    {
+        if (certificates == null || certificates.length <= 0) return null;
+        try
+        {
+
+            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
+            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
+            keyStore.load(null);
+            int index = 0;
+            for (InputStream certificate : certificates)
+            {
+                String certificateAlias = Integer.toString(index++);
+                keyStore.setCertificateEntry(certificateAlias, certificateFactory.generateCertificate(certificate));
+                try
+                {
+                    if (certificate != null)
+                        certificate.close();
+                } catch (IOException e)
+
+                {
+                }
+            }
+            TrustManagerFactory trustManagerFactory = null;
+
+            trustManagerFactory = TrustManagerFactory.
+                    getInstance(TrustManagerFactory.getDefaultAlgorithm());
+            trustManagerFactory.init(keyStore);
+
+            TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
+
+            return trustManagers;
+        } catch (NoSuchAlgorithmException e)
+        {
+            e.printStackTrace();
+        } catch (CertificateException e)
+        {
+            e.printStackTrace();
+        } catch (KeyStoreException e)
+        {
+            e.printStackTrace();
+        } catch (Exception e)
+        {
+            e.printStackTrace();
+        }
+        return null;
+
+    }
+
+    private static KeyManager[] prepareKeyManager(InputStream bksFile, String password)
+    {
+        try
+        {
+            if (bksFile == null || password == null) return null;
+
+            KeyStore clientKeyStore = KeyStore.getInstance("BKS");
+            clientKeyStore.load(bksFile, password.toCharArray());
+            KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
+            keyManagerFactory.init(clientKeyStore, password.toCharArray());
+            return keyManagerFactory.getKeyManagers();
+
+        } catch (KeyStoreException e)
+        {
+            e.printStackTrace();
+        } catch (NoSuchAlgorithmException e)
+        {
+            e.printStackTrace();
+        } catch (UnrecoverableKeyException e)
+        {
+            e.printStackTrace();
+        } catch (CertificateException e)
+        {
+            e.printStackTrace();
+        } catch (IOException e)
+        {
+            e.printStackTrace();
+        } catch (Exception e)
+        {
+            e.printStackTrace();
+        }
+        return null;
+    }
+
+    private static X509TrustManager chooseTrustManager(TrustManager[] trustManagers)
+    {
+        for (TrustManager trustManager : trustManagers)
+        {
+            if (trustManager instanceof X509TrustManager)
+            {
+                return (X509TrustManager) trustManager;
+            }
+        }
+        return null;
+    }
+
+
+    private static class MyTrustManager implements X509TrustManager
+    {
+        private X509TrustManager defaultTrustManager;
+        private X509TrustManager localTrustManager;
+
+        public MyTrustManager(X509TrustManager localTrustManager) throws NoSuchAlgorithmException, KeyStoreException
+        {
+            TrustManagerFactory var4 = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
+            var4.init((KeyStore) null);
+            defaultTrustManager = chooseTrustManager(var4.getTrustManagers());
+            this.localTrustManager = localTrustManager;
+        }
+
+
+        @Override
+        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException
+        {
+
+        }
+
+        @Override
+        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException
+        {
+            try
+            {
+                defaultTrustManager.checkServerTrusted(chain, authType);
+            } catch (CertificateException ce)
+            {
+                localTrustManager.checkServerTrusted(chain, authType);
+            }
+        }
+
+
+        @Override
+        public X509Certificate[] getAcceptedIssuers()
+        {
+            return new X509Certificate[0];
+        }
+    }
+}

+ 165 - 0
library/src/main/java/okhttp/log/LoggerInterceptor.java

@@ -0,0 +1,165 @@
+package com.zhy.http.okhttp.log;
+
+import android.text.TextUtils;
+import android.util.Log;
+
+import java.io.IOException;
+
+import okhttp3.Headers;
+import okhttp3.Interceptor;
+import okhttp3.MediaType;
+import okhttp3.Request;
+import okhttp3.RequestBody;
+import okhttp3.Response;
+import okhttp3.ResponseBody;
+import okio.Buffer;
+
+/**
+ * Created by zhy on 16/3/1.
+ */
+public class LoggerInterceptor implements Interceptor
+{
+    public static final String TAG = "OkHttpUtils";
+    private String tag;
+    private boolean showResponse;
+
+    public LoggerInterceptor(String tag, boolean showResponse)
+    {
+        if (TextUtils.isEmpty(tag))
+        {
+            tag = TAG;
+        }
+        this.showResponse = showResponse;
+        this.tag = tag;
+    }
+
+    public LoggerInterceptor(String tag)
+    {
+        this(tag, false);
+    }
+
+    @Override
+    public Response intercept(Chain chain) throws IOException
+    {
+        Request request = chain.request();
+        logForRequest(request);
+        Response response = chain.proceed(request);
+        return logForResponse(response);
+    }
+
+    private Response logForResponse(Response response)
+    {
+        try
+        {
+            //===>response log
+            Log.e(tag, "========response'log=======");
+            Response.Builder builder = response.newBuilder();
+            Response clone = builder.build();
+            Log.e(tag, "url : " + clone.request().url());
+            Log.e(tag, "code : " + clone.code());
+            Log.e(tag, "protocol : " + clone.protocol());
+            if (!TextUtils.isEmpty(clone.message()))
+                Log.e(tag, "message : " + clone.message());
+
+            if (showResponse)
+            {
+                ResponseBody body = clone.body();
+                if (body != null)
+                {
+                    MediaType mediaType = body.contentType();
+                    if (mediaType != null)
+                    {
+                        Log.e(tag, "responseBody's contentType : " + mediaType.toString());
+                        if (isText(mediaType))
+                        {
+                            String resp = body.string();
+                            Log.e(tag, "responseBody's content : " + resp);
+
+                            body = ResponseBody.create(mediaType, resp);
+                            return response.newBuilder().body(body).build();
+                        } else
+                        {
+                            Log.e(tag, "responseBody's content : " + " maybe [file part] , too large too print , ignored!");
+                        }
+                    }
+                }
+            }
+
+            Log.e(tag, "========response'log=======end");
+        } catch (Exception e)
+        {
+//            e.printStackTrace();
+        }
+
+        return response;
+    }
+
+    private void logForRequest(Request request)
+    {
+        try
+        {
+            String url = request.url().toString();
+            Headers headers = request.headers();
+
+            Log.e(tag, "========request'log=======");
+            Log.e(tag, "method : " + request.method());
+            Log.e(tag, "url : " + url);
+            if (headers != null && headers.size() > 0)
+            {
+                Log.e(tag, "headers : " + headers.toString());
+            }
+            RequestBody requestBody = request.body();
+            if (requestBody != null)
+            {
+                MediaType mediaType = requestBody.contentType();
+                if (mediaType != null)
+                {
+                    Log.e(tag, "requestBody's contentType : " + mediaType.toString());
+                    if (isText(mediaType))
+                    {
+                        Log.e(tag, "requestBody's content : " + bodyToString(request));
+                    } else
+                    {
+                        Log.e(tag, "requestBody's content : " + " maybe [file part] , too large too print , ignored!");
+                    }
+                }
+            }
+            Log.e(tag, "========request'log=======end");
+        } catch (Exception e)
+        {
+//            e.printStackTrace();
+        }
+    }
+
+    private boolean isText(MediaType mediaType)
+    {
+        if (mediaType.type() != null && mediaType.type().equals("text"))
+        {
+            return true;
+        }
+        if (mediaType.subtype() != null)
+        {
+            if (mediaType.subtype().equals("json") ||
+                    mediaType.subtype().equals("xml") ||
+                    mediaType.subtype().equals("html") ||
+                    mediaType.subtype().equals("webviewhtml")
+                    )
+                return true;
+        }
+        return false;
+    }
+
+    private String bodyToString(final Request request)
+    {
+        try
+        {
+            final Request copy = request.newBuilder().build();
+            final Buffer buffer = new Buffer();
+            copy.body().writeTo(buffer);
+            return buffer.readUtf8();
+        } catch (final IOException e)
+        {
+            return "something error when show requestBody.";
+        }
+    }
+}

+ 92 - 0
library/src/main/java/okhttp/request/CountingRequestBody.java

@@ -0,0 +1,92 @@
+package com.zhy.http.okhttp.request;
+
+import okhttp3.MediaType;
+import okhttp3.RequestBody;
+
+import java.io.IOException;
+
+import okio.Buffer;
+import okio.BufferedSink;
+import okio.ForwardingSink;
+import okio.Okio;
+import okio.Sink;
+
+/**
+ * Decorates an OkHttp request body to count the number of bytes written when writing it. Can
+ * decorate any request body, but is most useful for tracking the upload progress of large
+ * multipart requests.
+ *
+ * @author Leo Nikkilä
+ */
+public class CountingRequestBody extends RequestBody
+{
+
+    protected RequestBody delegate;
+    protected Listener listener;
+
+    protected CountingSink countingSink;
+
+    public CountingRequestBody(RequestBody delegate, Listener listener)
+    {
+        this.delegate = delegate;
+        this.listener = listener;
+    }
+
+    @Override
+    public MediaType contentType()
+    {
+        return delegate.contentType();
+    }
+
+    @Override
+    public long contentLength()
+    {
+        try
+        {
+            return delegate.contentLength();
+        } catch (IOException e)
+        {
+            e.printStackTrace();
+        }
+        return -1;
+    }
+
+    @Override
+    public void writeTo(BufferedSink sink) throws IOException
+    {
+
+        countingSink = new CountingSink(sink);
+        BufferedSink bufferedSink = Okio.buffer(countingSink);
+
+        delegate.writeTo(bufferedSink);
+
+        bufferedSink.flush();
+    }
+
+    protected final class CountingSink extends ForwardingSink
+    {
+
+        private long bytesWritten = 0;
+
+        public CountingSink(Sink delegate)
+        {
+            super(delegate);
+        }
+
+        @Override
+        public void write(Buffer source, long byteCount) throws IOException
+        {
+            super.write(source, byteCount);
+
+            bytesWritten += byteCount;
+            listener.onRequestProgress(bytesWritten, contentLength());
+        }
+
+    }
+
+    public static interface Listener
+    {
+        public void onRequestProgress(long bytesWritten, long contentLength);
+    }
+
+}

+ 31 - 0
library/src/main/java/okhttp/request/GetRequest.java

@@ -0,0 +1,31 @@
+package com.zhy.http.okhttp.request;
+
+import java.util.Map;
+
+import okhttp3.Request;
+import okhttp3.RequestBody;
+
+/**
+ * Created by zhy on 15/12/14.
+ */
+public class GetRequest extends OkHttpRequest
+{
+    public GetRequest(String url, Object tag, Map<String, String> params, Map<String, String> headers,int id)
+    {
+        super(url, tag, params, headers,id);
+    }
+
+    @Override
+    protected RequestBody buildRequestBody()
+    {
+        return null;
+    }
+
+    @Override
+    protected Request buildRequest(RequestBody requestBody)
+    {
+        return builder.get().build();
+    }
+
+
+}

+ 94 - 0
library/src/main/java/okhttp/request/OkHttpRequest.java

@@ -0,0 +1,94 @@
+package com.zhy.http.okhttp.request;
+
+import com.zhy.http.okhttp.callback.Callback;
+import com.zhy.http.okhttp.utils.Exceptions;
+
+import java.util.Map;
+
+import okhttp3.Headers;
+import okhttp3.Request;
+import okhttp3.RequestBody;
+
+/**
+ * Created by zhy on 15/11/6.
+ */
+public abstract class OkHttpRequest
+{
+    protected String url;
+    protected Object tag;
+    protected Map<String, String> params;
+    protected Map<String, String> headers;
+    protected int id;
+
+    protected Request.Builder builder = new Request.Builder();
+
+    protected OkHttpRequest(String url, Object tag,
+                            Map<String, String> params, Map<String, String> headers,int id)
+    {
+        this.url = url;
+        this.tag = tag;
+        this.params = params;
+        this.headers = headers;
+        this.id = id ;
+
+        if (url == null)
+        {
+            Exceptions.illegalArgument("url can not be null.");
+        }
+
+        initBuilder();
+    }
+
+
+
+    /**
+     * 初始化一些基本参数 url , tag , headers
+     */
+    private void initBuilder()
+    {
+        builder.url(url).tag(tag);
+        appendHeaders();
+    }
+
+    protected abstract RequestBody buildRequestBody();
+
+    protected RequestBody wrapRequestBody(RequestBody requestBody, final Callback callback)
+    {
+        return requestBody;
+    }
+
+    protected abstract Request buildRequest(RequestBody requestBody);
+
+    public RequestCall build()
+    {
+        return new RequestCall(this);
+    }
+
+
+    public Request generateRequest(Callback callback)
+    {
+        RequestBody requestBody = buildRequestBody();
+        RequestBody wrappedRequestBody = wrapRequestBody(requestBody, callback);
+        Request request = buildRequest(wrappedRequestBody);
+        return request;
+    }
+
+
+    protected void appendHeaders()
+    {
+        Headers.Builder headerBuilder = new Headers.Builder();
+        if (headers == null || headers.isEmpty()) return;
+
+        for (String key : headers.keySet())
+        {
+            headerBuilder.add(key, headers.get(key));
+        }
+        builder.headers(headerBuilder.build());
+    }
+
+    public int getId()
+    {
+        return id  ;
+    }
+
+}

+ 74 - 0
library/src/main/java/okhttp/request/OtherRequest.java

@@ -0,0 +1,74 @@
+package com.zhy.http.okhttp.request;
+
+import android.text.TextUtils;
+
+import com.zhy.http.okhttp.OkHttpUtils;
+import com.zhy.http.okhttp.utils.Exceptions;
+
+import java.util.Map;
+
+import okhttp3.MediaType;
+import okhttp3.Request;
+import okhttp3.RequestBody;
+import okhttp3.internal.http.HttpMethod;
+
+/**
+ * Created by zhy on 16/2/23.
+ */
+public class OtherRequest extends OkHttpRequest
+{
+    private static MediaType MEDIA_TYPE_PLAIN = MediaType.parse("text/plain;charset=utf-8");
+
+    private RequestBody requestBody;
+    private String method;
+    private String content;
+
+    public OtherRequest(RequestBody requestBody, String content, String method, String url, Object tag, Map<String, String> params, Map<String, String> headers,int id)
+    {
+        super(url, tag, params, headers,id);
+        this.requestBody = requestBody;
+        this.method = method;
+        this.content = content;
+
+    }
+
+    @Override
+    protected RequestBody buildRequestBody()
+    {
+        if (requestBody == null && TextUtils.isEmpty(content) && HttpMethod.requiresRequestBody(method))
+        {
+            Exceptions.illegalArgument("requestBody and content can not be null in method:" + method);
+        }
+
+        if (requestBody == null && !TextUtils.isEmpty(content))
+        {
+            requestBody = RequestBody.create(MEDIA_TYPE_PLAIN, content);
+        }
+
+        return requestBody;
+    }
+
+    @Override
+    protected Request buildRequest(RequestBody requestBody)
+    {
+        if (method.equals(OkHttpUtils.METHOD.PUT))
+        {
+            builder.put(requestBody);
+        } else if (method.equals(OkHttpUtils.METHOD.DELETE))
+        {
+            if (requestBody == null)
+                builder.delete();
+            else
+                builder.delete(requestBody);
+        } else if (method.equals(OkHttpUtils.METHOD.HEAD))
+        {
+            builder.head();
+        } else if (method.equals(OkHttpUtils.METHOD.PATCH))
+        {
+            builder.patch(requestBody);
+        }
+
+        return builder.build();
+    }
+
+}

+ 78 - 0
library/src/main/java/okhttp/request/PostFileRequest.java

@@ -0,0 +1,78 @@
+package com.zhy.http.okhttp.request;
+
+import com.zhy.http.okhttp.OkHttpUtils;
+import com.zhy.http.okhttp.callback.Callback;
+import com.zhy.http.okhttp.utils.Exceptions;
+
+import java.io.File;
+import java.util.Map;
+
+import okhttp3.MediaType;
+import okhttp3.Request;
+import okhttp3.RequestBody;
+
+/**
+ * Created by zhy on 15/12/14.
+ */
+public class PostFileRequest extends OkHttpRequest
+{
+    private static MediaType MEDIA_TYPE_STREAM = MediaType.parse("application/octet-stream");
+
+    private File file;
+    private MediaType mediaType;
+
+    public PostFileRequest(String url, Object tag, Map<String, String> params, Map<String, String> headers, File file, MediaType mediaType,int id)
+    {
+        super(url, tag, params, headers,id);
+        this.file = file;
+        this.mediaType = mediaType;
+
+        if (this.file == null)
+        {
+            Exceptions.illegalArgument("the file can not be null !");
+        }
+        if (this.mediaType == null)
+        {
+            this.mediaType = MEDIA_TYPE_STREAM;
+        }
+    }
+
+    @Override
+    protected RequestBody buildRequestBody()
+    {
+        return RequestBody.create(mediaType, file);
+    }
+
+    @Override
+    protected RequestBody wrapRequestBody(RequestBody requestBody, final Callback callback)
+    {
+        if (callback == null) return requestBody;
+        CountingRequestBody countingRequestBody = new CountingRequestBody(requestBody, new CountingRequestBody.Listener()
+        {
+            @Override
+            public void onRequestProgress(final long bytesWritten, final long contentLength)
+            {
+
+                OkHttpUtils.getInstance().getDelivery().execute(new Runnable()
+                {
+                    @Override
+                    public void run()
+                    {
+                        callback.inProgress(bytesWritten * 1.0f / contentLength,contentLength,id);
+                    }
+                });
+
+            }
+        });
+        return countingRequestBody;
+    }
+
+    @Override
+    protected Request buildRequest(RequestBody requestBody)
+    {
+        return builder.post(requestBody).build();
+    }
+
+
+
+}

+ 130 - 0
library/src/main/java/okhttp/request/PostFormRequest.java

@@ -0,0 +1,130 @@
+package com.zhy.http.okhttp.request;
+
+import com.zhy.http.okhttp.OkHttpUtils;
+import com.zhy.http.okhttp.builder.PostFormBuilder;
+import com.zhy.http.okhttp.callback.Callback;
+
+import java.io.UnsupportedEncodingException;
+import java.net.FileNameMap;
+import java.net.URLConnection;
+import java.net.URLEncoder;
+import java.util.List;
+import java.util.Map;
+
+import okhttp3.FormBody;
+import okhttp3.Headers;
+import okhttp3.MediaType;
+import okhttp3.MultipartBody;
+import okhttp3.Request;
+import okhttp3.RequestBody;
+
+/**
+ * Created by zhy on 15/12/14.
+ */
+public class PostFormRequest extends OkHttpRequest
+{
+    private List<PostFormBuilder.FileInput> files;
+
+    public PostFormRequest(String url, Object tag, Map<String, String> params, Map<String, String> headers, List<PostFormBuilder.FileInput> files,int id)
+    {
+        super(url, tag, params, headers,id);
+        this.files = files;
+    }
+
+    @Override
+    protected RequestBody buildRequestBody()
+    {
+        if (files == null || files.isEmpty())
+        {
+            FormBody.Builder builder = new FormBody.Builder();
+            addParams(builder);
+            FormBody formBody = builder.build();
+            return formBody;
+        } else
+        {
+            MultipartBody.Builder builder = new MultipartBody.Builder()
+                    .setType(MultipartBody.FORM);
+            addParams(builder);
+
+            for (int i = 0; i < files.size(); i++)
+            {
+                PostFormBuilder.FileInput fileInput = files.get(i);
+                RequestBody fileBody = RequestBody.create(MediaType.parse(guessMimeType(fileInput.filename)), fileInput.file);
+                builder.addFormDataPart(fileInput.key, fileInput.filename, fileBody);
+            }
+            return builder.build();
+        }
+    }
+
+    @Override
+    protected RequestBody wrapRequestBody(RequestBody requestBody, final Callback callback)
+    {
+        if (callback == null) return requestBody;
+        CountingRequestBody countingRequestBody = new CountingRequestBody(requestBody, new CountingRequestBody.Listener()
+        {
+            @Override
+            public void onRequestProgress(final long bytesWritten, final long contentLength)
+            {
+
+                OkHttpUtils.getInstance().getDelivery().execute(new Runnable()
+                {
+                    @Override
+                    public void run()
+                    {
+                        callback.inProgress(bytesWritten * 1.0f / contentLength,contentLength,id);
+                    }
+                });
+
+            }
+        });
+        return countingRequestBody;
+    }
+
+    @Override
+    protected Request buildRequest(RequestBody requestBody)
+    {
+        return builder.post(requestBody).build();
+    }
+
+    private String guessMimeType(String path)
+    {
+        FileNameMap fileNameMap = URLConnection.getFileNameMap();
+        String contentTypeFor = null;
+        try
+        {
+            contentTypeFor = fileNameMap.getContentTypeFor(URLEncoder.encode(path, "UTF-8"));
+        } catch (UnsupportedEncodingException e)
+        {
+            e.printStackTrace();
+        }
+        if (contentTypeFor == null)
+        {
+            contentTypeFor = "application/octet-stream";
+        }
+        return contentTypeFor;
+    }
+
+    private void addParams(MultipartBody.Builder builder)
+    {
+        if (params != null && !params.isEmpty())
+        {
+            for (String key : params.keySet())
+            {
+                builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + key + "\""),
+                        RequestBody.create(null, params.get(key)));
+            }
+        }
+    }
+
+    private void addParams(FormBody.Builder builder)
+    {
+        if (params != null)
+        {
+            for (String key : params.keySet())
+            {
+                builder.add(key, params.get(key));
+            }
+        }
+    }
+
+}

+ 52 - 0
library/src/main/java/okhttp/request/PostStringRequest.java

@@ -0,0 +1,52 @@
+package com.zhy.http.okhttp.request;
+
+import com.zhy.http.okhttp.utils.Exceptions;
+
+import java.util.Map;
+
+import okhttp3.MediaType;
+import okhttp3.Request;
+import okhttp3.RequestBody;
+
+/**
+ * Created by zhy on 15/12/14.
+ */
+public class PostStringRequest extends OkHttpRequest
+{
+    private static MediaType MEDIA_TYPE_PLAIN = MediaType.parse("text/plain;charset=utf-8");
+
+    private String content;
+    private MediaType mediaType;
+
+
+    public PostStringRequest(String url, Object tag, Map<String, String> params, Map<String, String> headers, String content, MediaType mediaType,int id)
+    {
+        super(url, tag, params, headers,id);
+        this.content = content;
+        this.mediaType = mediaType;
+
+        if (this.content == null)
+        {
+            Exceptions.illegalArgument("the content can not be null !");
+        }
+        if (this.mediaType == null)
+        {
+            this.mediaType = MEDIA_TYPE_PLAIN;
+        }
+
+    }
+
+    @Override
+    protected RequestBody buildRequestBody()
+    {
+        return RequestBody.create(mediaType, content);
+    }
+
+    @Override
+    protected Request buildRequest( RequestBody requestBody)
+    {
+        return builder.post(requestBody).build();
+    }
+
+
+}

+ 124 - 0
library/src/main/java/okhttp/request/RequestCall.java

@@ -0,0 +1,124 @@
+package com.zhy.http.okhttp.request;
+
+import com.zhy.http.okhttp.OkHttpUtils;
+import com.zhy.http.okhttp.callback.Callback;
+
+import java.io.IOException;
+import java.util.concurrent.TimeUnit;
+
+import okhttp3.Call;
+import okhttp3.OkHttpClient;
+import okhttp3.Request;
+import okhttp3.Response;
+
+/**
+ * Created by zhy on 15/12/15.
+ * 对OkHttpRequest的封装,对外提供更多的接口:cancel(),readTimeOut()...
+ */
+public class RequestCall
+{
+    private OkHttpRequest okHttpRequest;
+    private Request request;
+    private Call call;
+
+    private long readTimeOut;
+    private long writeTimeOut;
+    private long connTimeOut;
+
+    private OkHttpClient clone;
+
+    public RequestCall(OkHttpRequest request)
+    {
+        this.okHttpRequest = request;
+    }
+
+    public RequestCall readTimeOut(long readTimeOut)
+    {
+        this.readTimeOut = readTimeOut;
+        return this;
+    }
+
+    public RequestCall writeTimeOut(long writeTimeOut)
+    {
+        this.writeTimeOut = writeTimeOut;
+        return this;
+    }
+
+    public RequestCall connTimeOut(long connTimeOut)
+    {
+        this.connTimeOut = connTimeOut;
+        return this;
+    }
+
+    public Call buildCall(Callback callback)
+    {
+        request = generateRequest(callback);
+
+        if (readTimeOut > 0 || writeTimeOut > 0 || connTimeOut > 0)
+        {
+            readTimeOut = readTimeOut > 0 ? readTimeOut : OkHttpUtils.DEFAULT_MILLISECONDS;
+            writeTimeOut = writeTimeOut > 0 ? writeTimeOut : OkHttpUtils.DEFAULT_MILLISECONDS;
+            connTimeOut = connTimeOut > 0 ? connTimeOut : OkHttpUtils.DEFAULT_MILLISECONDS;
+
+            clone = OkHttpUtils.getInstance().getOkHttpClient().newBuilder()
+                    .readTimeout(readTimeOut, TimeUnit.MILLISECONDS)
+                    .writeTimeout(writeTimeOut, TimeUnit.MILLISECONDS)
+                    .connectTimeout(connTimeOut, TimeUnit.MILLISECONDS)
+                    .build();
+
+            call = clone.newCall(request);
+        } else
+        {
+            call = OkHttpUtils.getInstance().getOkHttpClient().newCall(request);
+        }
+        return call;
+    }
+
+    private Request generateRequest(Callback callback)
+    {
+        return okHttpRequest.generateRequest(callback);
+    }
+
+    public void execute(Callback callback)
+    {
+        buildCall(callback);
+
+        if (callback != null)
+        {
+            callback.onBefore(request, getOkHttpRequest().getId());
+        }
+
+        OkHttpUtils.getInstance().execute(this, callback);
+    }
+
+    public Call getCall()
+    {
+        return call;
+    }
+
+    public Request getRequest()
+    {
+        return request;
+    }
+
+    public OkHttpRequest getOkHttpRequest()
+    {
+        return okHttpRequest;
+    }
+
+    public Response execute() throws IOException
+    {
+        buildCall(null);
+        return call.execute();
+    }
+
+    public void cancel()
+    {
+        if (call != null)
+        {
+            call.cancel();
+        }
+    }
+
+
+}

+ 14 - 0
library/src/main/java/okhttp/utils/Exceptions.java

@@ -0,0 +1,14 @@
+package com.zhy.http.okhttp.utils;
+
+/**
+ * Created by zhy on 15/12/14.
+ */
+public class Exceptions
+{
+    public static void illegalArgument(String msg, Object... params)
+    {
+        throw new IllegalArgumentException(String.format(msg, params));
+    }
+
+
+}

+ 196 - 0
library/src/main/java/okhttp/utils/ImageUtils.java

@@ -0,0 +1,196 @@
+package com.zhy.http.okhttp.utils;
+
+import android.graphics.BitmapFactory;
+import android.util.DisplayMetrics;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.ImageView;
+
+import java.io.InputStream;
+import java.lang.reflect.Field;
+
+/**
+ * Created by zhy on 15/11/6.
+ */
+public class ImageUtils
+{
+    /**
+     * 根据InputStream获取图片实际的宽度和高度
+     *
+     * @param imageStream
+     * @return
+     */
+    public static ImageSize getImageSize(InputStream imageStream)
+    {
+        BitmapFactory.Options options = new BitmapFactory.Options();
+        options.inJustDecodeBounds = true;
+        BitmapFactory.decodeStream(imageStream, null, options);
+        return new ImageSize(options.outWidth, options.outHeight);
+    }
+
+    public static class ImageSize
+    {
+        int width;
+        int height;
+
+        public ImageSize()
+        {
+        }
+
+        public ImageSize(int width, int height)
+        {
+            this.width = width;
+            this.height = height;
+        }
+
+        @Override
+        public String toString()
+        {
+            return "ImageSize{" +
+                    "width=" + width +
+                    ", height=" + height +
+                    '}';
+        }
+    }
+
+    public static int calculateInSampleSize(ImageSize srcSize, ImageSize targetSize)
+    {
+        // 源图片的宽度
+        int width = srcSize.width;
+        int height = srcSize.height;
+        int inSampleSize = 1;
+
+        int reqWidth = targetSize.width;
+        int reqHeight = targetSize.height;
+
+        if (width > reqWidth && height > reqHeight)
+        {
+            // 计算出实际宽度和目标宽度的比率
+            int widthRatio = Math.round((float) width / (float) reqWidth);
+            int heightRatio = Math.round((float) height / (float) reqHeight);
+            inSampleSize = Math.max(widthRatio, heightRatio);
+        }
+        return inSampleSize;
+    }
+
+    /**
+     * 根据ImageView获适当的压缩的宽和高
+     *
+     * @param view
+     * @return
+     */
+    public static ImageSize getImageViewSize(View view)
+    {
+
+        ImageSize imageSize = new ImageSize();
+
+        imageSize.width = getExpectWidth(view);
+        imageSize.height = getExpectHeight(view);
+
+        return imageSize;
+    }
+
+    /**
+     * 根据view获得期望的高度
+     *
+     * @param view
+     * @return
+     */
+    private static int getExpectHeight(View view)
+    {
+
+        int height = 0;
+        if (view == null) return 0;
+
+        final ViewGroup.LayoutParams params = view.getLayoutParams();
+        //如果是WRAP_CONTENT,此时图片还没加载,getWidth根本无效
+        if (params != null && params.height != ViewGroup.LayoutParams.WRAP_CONTENT)
+        {
+            height = view.getWidth(); // 获得实际的宽度
+        }
+        if (height <= 0 && params != null)
+        {
+            height = params.height; // 获得布局文件中的声明的宽度
+        }
+
+        if (height <= 0)
+        {
+            height = getImageViewFieldValue(view, "mMaxHeight");// 获得设置的最大的宽度
+        }
+
+        //如果宽度还是没有获取到,憋大招,使用屏幕的宽度
+        if (height <= 0)
+        {
+            DisplayMetrics displayMetrics = view.getContext().getResources()
+                    .getDisplayMetrics();
+            height = displayMetrics.heightPixels;
+        }
+
+        return height;
+    }
+
+    /**
+     * 根据view获得期望的宽度
+     *
+     * @param view
+     * @return
+     */
+    private static int getExpectWidth(View view)
+    {
+        int width = 0;
+        if (view == null) return 0;
+
+        final ViewGroup.LayoutParams params = view.getLayoutParams();
+        //如果是WRAP_CONTENT,此时图片还没加载,getWidth根本无效
+        if (params != null && params.width != ViewGroup.LayoutParams.WRAP_CONTENT)
+        {
+            width = view.getWidth(); // 获得实际的宽度
+        }
+        if (width <= 0 && params != null)
+        {
+            width = params.width; // 获得布局文件中的声明的宽度
+        }
+
+        if (width <= 0)
+
+        {
+            width = getImageViewFieldValue(view, "mMaxWidth");// 获得设置的最大的宽度
+        }
+        //如果宽度还是没有获取到,憋大招,使用屏幕的宽度
+        if (width <= 0)
+
+        {
+            DisplayMetrics displayMetrics = view.getContext().getResources()
+                    .getDisplayMetrics();
+            width = displayMetrics.widthPixels;
+        }
+
+        return width;
+    }
+
+    /**
+     * 通过反射获取imageview的某个属性值
+     *
+     * @param object
+     * @param fieldName
+     * @return
+     */
+    private static int getImageViewFieldValue(Object object, String fieldName)
+    {
+        int value = 0;
+        try
+        {
+            Field field = ImageView.class.getDeclaredField(fieldName);
+            field.setAccessible(true);
+            int fieldValue = field.getInt(object);
+            if (fieldValue > 0 && fieldValue < Integer.MAX_VALUE)
+            {
+                value = fieldValue;
+            }
+        } catch (Exception e)
+        {
+        }
+        return value;
+
+    }
+}

+ 21 - 0
library/src/main/java/okhttp/utils/L.java

@@ -0,0 +1,21 @@
+package com.zhy.http.okhttp.utils;
+
+import android.util.Log;
+
+/**
+ * Created by zhy on 15/11/6.
+ */
+public class L
+{
+    private static boolean debug = false;
+
+    public static void e(String msg)
+    {
+        if (debug)
+        {
+            Log.e("OkHttp", msg);
+        }
+    }
+
+}
+

+ 82 - 0
library/src/main/java/okhttp/utils/Platform.java

@@ -0,0 +1,82 @@
+/*
+ * Copyright (C) 2013 Square, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.zhy.http.okhttp.utils;
+
+import android.os.Build;
+import android.os.Handler;
+import android.os.Looper;
+
+import java.util.concurrent.Executor;
+import java.util.concurrent.Executors;
+
+public class Platform
+{
+    private static final Platform PLATFORM = findPlatform();
+
+    public static Platform get()
+    {
+        L.e(PLATFORM.getClass().toString());
+        return PLATFORM;
+    }
+
+    private static Platform findPlatform()
+    {
+        try
+        {
+            Class.forName("android.os.Build");
+            if (Build.VERSION.SDK_INT != 0)
+            {
+                return new Android();
+            }
+        } catch (ClassNotFoundException ignored)
+        {
+        }
+        return new Platform();
+    }
+
+    public Executor defaultCallbackExecutor()
+    {
+        return Executors.newCachedThreadPool();
+    }
+
+    public void execute(Runnable runnable)
+    {
+        defaultCallbackExecutor().execute(runnable);
+    }
+
+
+    static class Android extends Platform
+    {
+        @Override
+        public Executor defaultCallbackExecutor()
+        {
+            return new MainThreadExecutor();
+        }
+
+        static class MainThreadExecutor implements Executor
+        {
+            private final Handler handler = new Handler(Looper.getMainLooper());
+
+            @Override
+            public void execute(Runnable r)
+            {
+                handler.post(r);
+            }
+        }
+    }
+
+
+}

+ 8 - 0
library/src/main/java/utils/AppVersionUtil.java

@@ -0,0 +1,8 @@
+package utils;
+
+/**
+ * 作者:fuchangle on 2018/1/26 16:29
+ */
+
+public class AppVersionUtil {
+}

+ 8 - 0
library/src/main/java/utils/ArithUtil.java

@@ -0,0 +1,8 @@
+package utils;
+
+/**
+ * 作者:fuchangle on 2018/1/26 16:26
+ */
+
+public class ArithUtil {
+}

+ 8 - 0
library/src/main/java/utils/DateUtils.java

@@ -0,0 +1,8 @@
+package utils;
+
+/**
+ * 作者:fuchangle on 2018/1/26 16:35
+ */
+
+public class DateUtils {
+}

+ 8 - 0
library/src/main/java/utils/FileUtils.java

@@ -0,0 +1,8 @@
+package utils;
+
+/**
+ * 作者:fuchangle on 2018/1/26 16:35
+ */
+
+public class FileUtils {
+}

+ 8 - 0
library/src/main/java/utils/JsonAssetsReaderUtil.java

@@ -0,0 +1,8 @@
+package utils;
+
+/**
+ * 作者:fuchangle on 2018/1/26 16:30
+ */
+
+public class JsonAssetsReaderUtil {
+}

+ 8 - 0
library/src/main/java/utils/LogUtil.java

@@ -0,0 +1,8 @@
+package utils;
+
+/**
+ * 作者:fuchangle on 2018/1/26 16:31
+ */
+
+public class LogUtil {
+}

+ 8 - 0
library/src/main/java/utils/MD5Utils.java

@@ -0,0 +1,8 @@
+package utils;
+
+/**
+ * 作者:fuchangle on 2018/1/26 16:31
+ */
+
+public class MD5Utils {
+}

+ 8 - 0
library/src/main/java/utils/NetWorkUtil.java

@@ -0,0 +1,8 @@
+package utils;
+
+/**
+ * 作者:fuchangle on 2018/1/26 16:27
+ */
+
+public class NetWorkUtil {
+}

+ 8 - 0
library/src/main/java/utils/PixelUtil.java

@@ -0,0 +1,8 @@
+package utils;
+
+/**
+ * 作者:fuchangle on 2018/1/26 16:33
+ */
+
+public class PixelUtil {
+}

+ 8 - 0
library/src/main/java/utils/RegularUtils.java

@@ -0,0 +1,8 @@
+package utils;
+
+/**
+ * 作者:fuchangle on 2018/1/26 16:32
+ */
+
+public class RegularUtils {
+}

+ 3 - 0
library/src/main/res/values/strings.xml

@@ -0,0 +1,3 @@
+<resources>
+    <string name="app_name">library</string>
+</resources>

+ 1 - 1
app/src/test/java/com/ynstkz/shitu/android/ExampleUnitTest.java

@@ -1,4 +1,4 @@
-package com.ynstkz.shitu.android;
+package test.kotlin.com.library;
 
 import org.junit.Test;