├── okhttp3utils ├── .gitignore ├── src │ └── main │ │ ├── res │ │ └── values │ │ │ └── strings.xml │ │ ├── AndroidManifest.xml │ │ └── java │ │ └── itheima │ │ └── okhttp3utils │ │ ├── WSCallBack.java │ │ └── ItHeiMaHttp.java ├── proguard-rules.pro └── build.gradle ├── settings.gradle ├── jitpack.png ├── .gitignore ├── gradle.properties └── README.md /okhttp3utils/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':okhttp3utils' 2 | -------------------------------------------------------------------------------- /jitpack.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/open-android/OkHttp3Utils/HEAD/jitpack.png -------------------------------------------------------------------------------- /okhttp3utils/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | OkHttp3Utils 3 | 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea/workspace.xml 5 | /.idea/libraries 6 | .DS_Store 7 | /build 8 | /captures 9 | .externalNativeBuild 10 | /.idea/ 11 | /gradle/ 12 | /gradlew 13 | /gradlew.bat 14 | -------------------------------------------------------------------------------- /okhttp3utils/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /okhttp3utils/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in D:\DevlopmentAndroid\AndroidStudio\sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) users: 4 | # Gradle settings configured through the IDE *will override* 5 | # any settings specified in this file. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | org.gradle.jvmargs=-Xmx1536m 13 | 14 | # When configured, Gradle will run in incubating parallel mode. 15 | # This option should only be used with decoupled projects. More details, visit 16 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 17 | # org.gradle.parallel=true 18 | -------------------------------------------------------------------------------- /okhttp3utils/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | apply plugin: 'com.github.dcendents.android-maven' 3 | group = 'com.github.itcastsh' 4 | 5 | android { 6 | compileSdkVersion 24 7 | buildToolsVersion "23.0.3" 8 | 9 | defaultConfig { 10 | minSdkVersion 8 11 | targetSdkVersion 23 12 | versionCode 1 13 | versionName "0.1.0" 14 | 15 | } 16 | 17 | buildTypes { 18 | release { 19 | minifyEnabled false 20 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt' 21 | } 22 | } 23 | lintOptions { 24 | abortOnError false 25 | } 26 | 27 | 28 | } 29 | 30 | dependencies { 31 | compile 'com.squareup.okhttp3:okhttp:3.2.0' 32 | compile 'com.google.code.gson:gson:2.6.2' 33 | } 34 | -------------------------------------------------------------------------------- /okhttp3utils/src/main/java/itheima/okhttp3utils/WSCallBack.java: -------------------------------------------------------------------------------- 1 | package itheima.okhttp3utils; 2 | 3 | import com.google.gson.internal.$Gson$Types; 4 | 5 | import java.lang.reflect.ParameterizedType; 6 | import java.lang.reflect.Type; 7 | 8 | import okhttp3.Call; 9 | 10 | /** 11 | * Created by wschun on 2016/10/7. 12 | */ 13 | 14 | public abstract class WSCallBack { 15 | 16 | Type type; 17 | 18 | static Type getSuperclassTypeParameter(Class subclass) 19 | { 20 | Type superclass = subclass.getGenericSuperclass(); 21 | if (superclass instanceof Class) 22 | { 23 | throw new RuntimeException("Missing type parameter."); 24 | } 25 | ParameterizedType parameterized = (ParameterizedType) superclass; 26 | return $Gson$Types.canonicalize(parameterized.getActualTypeArguments()[0]); 27 | } 28 | 29 | public WSCallBack() 30 | { 31 | type = getSuperclassTypeParameter(getClass()); 32 | } 33 | 34 | public abstract void onFailure(Call call, Exception e) ; 35 | 36 | public abstract void onSuccess(T t); 37 | 38 | } 39 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | #OkHttp3Utils 2 | 3 | OkHttp3.0封装框架,内部使用gson解析json数据 4 | 5 | 项目地址:[https://github.com/open-android/OkHttp3Utils](https://github.com/open-android/OkHttp3Utils "OKHttp3.0") 6 | 7 | 简书:[http://www.jianshu.com/p/e9258c1bc5ce](http://www.jianshu.com/p/e9258c1bc5ce "OKHttp3.0") 8 | 9 | * 爱生活,爱学习,更爱做代码的搬运工,分类查找更方便请下载黑马助手app 10 | 11 | 12 | ![黑马助手.png](http://upload-images.jianshu.io/upload_images/4037105-f777f1214328dcc4.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 13 | 14 | 15 | ## 使用步骤 16 | ### 1. 在project的build.gradle添加如下代码(如下图) 17 | 18 | allprojects { 19 | repositories { 20 | ... 21 | maven { url "https://jitpack.io" } 22 | } 23 | } 24 | 25 | ![](http://oi5nqn6ce.bkt.clouddn.com/itheima/booster/code/jitpack.png) 26 | 27 | ### 2. 在Module的build.gradle添加依赖 28 | 29 | compile 'com.github.open-android:OkHttp3Utils:0.0.4' 30 | 31 | 32 | 33 | ### 3. 需要的权限 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | ### 4. GET请求(内部使用Gson解析json数据) 42 | 43 | ItHeiMaHttp heiMaHttp = ItHeiMaHttp.getInstance(). 44 | addHead("参数名称", "参数"). //加头 45 | addParam("参数名称", "参数"); //参数 46 | 47 | // WSCallBack 中的数据类型必须给,如果只想要JSON,传入String即可 48 | heiMaHttp.get("BASE_URL", new WSCallBack() { 49 | @Override 50 | public void onFailure(Call call, Exception e) { 51 | //失败 52 | } 53 | 54 | @Override 55 | public void onSuccess(Bean bean) { 56 | //成功, 自己想要的Bean 57 | } 58 | }); 59 | 60 | ### POST请求(内部使用Gson解析json数据) 61 | 62 | ItHeiMaHttp heiMaHttp = ItHeiMaHttp.getInstance(). 63 | addHead("参数名称", "参数"). //加头 64 | addParam("参数名称", "参数"); //参数 65 | 66 | // WSCallBack 中的数据类型必须给,如果只想要JSON,传入String即可 67 | heiMaHttp.post("BASE_URL", new WSCallBack() { 68 | @Override 69 | public void onFailure(Call call, Exception e) { 70 | //失败 71 | } 72 | 73 | @Override 74 | public void onSuccess(Bean bean) { 75 | //成功, 自己想要的Bean 76 | } 77 | }); 78 | 79 | ### 添加请求参数 80 | 81 | heiMaHttp.addParam("key","value") 82 | .addParam("key","value") 83 | .addParam("key","value"); 84 | 85 | 86 | ### 添加请头 87 | 88 | heiMaHttp.addHead("key","value") 89 | .addHead("ke","value") 90 | .addHead("key","value"); 91 | 92 | 93 | * retrofit网络工具类推荐:[https://github.com/open-android/RetrofitUtils](https://github.com/open-android/RetrofitUtils "retrofit") 94 | 95 | 详细的使用方法在DEMO里面都演示啦,如果你觉得这个库还不错,请赏我一颗star吧~~~ 96 | 97 | 欢迎关注微信公众号 98 | 99 | ![](http://oi5nqn6ce.bkt.clouddn.com/itheima/booster/code/qrcode.png) 100 | -------------------------------------------------------------------------------- /okhttp3utils/src/main/java/itheima/okhttp3utils/ItHeiMaHttp.java: -------------------------------------------------------------------------------- 1 | package itheima.okhttp3utils; 2 | 3 | import android.os.Handler; 4 | import android.os.Looper; 5 | 6 | import com.google.gson.Gson; 7 | import com.google.gson.JsonParseException; 8 | 9 | import java.io.IOException; 10 | import java.util.HashMap; 11 | import java.util.Map; 12 | import java.util.concurrent.TimeUnit; 13 | 14 | import okhttp3.Call; 15 | import okhttp3.Callback; 16 | import okhttp3.FormBody; 17 | import okhttp3.OkHttpClient; 18 | import okhttp3.Request; 19 | import okhttp3.RequestBody; 20 | import okhttp3.Response; 21 | 22 | 23 | /** 24 | * Created by wschun on 2016/10/7. 25 | */ 26 | 27 | public class ItHeiMaHttp { 28 | 29 | private final OkHttpClient okHttpClient; 30 | private Map params = null; 31 | private Map heads = null; 32 | 33 | private Gson gson; 34 | private final Handler handler; 35 | 36 | private ItHeiMaHttp() { 37 | okHttpClient = new OkHttpClient(); 38 | okHttpClient.newBuilder().connectTimeout(10, TimeUnit.SECONDS); 39 | okHttpClient.newBuilder().writeTimeout(10, TimeUnit.SECONDS); 40 | okHttpClient.newBuilder().readTimeout(10, TimeUnit.SECONDS); 41 | gson = new Gson(); 42 | handler = new Handler(Looper.myLooper()); 43 | this.params = new HashMap(); 44 | this.heads=new HashMap(); 45 | } 46 | 47 | 48 | public Map getParams() { 49 | return params; 50 | } 51 | 52 | 53 | public ItHeiMaHttp addParam(String key, String value) { 54 | this.params.put(new String(key), value); 55 | return this; 56 | } 57 | 58 | public Map getHeads() { 59 | return heads; 60 | } 61 | 62 | 63 | public ItHeiMaHttp addHeads(String key, String value) { 64 | this.heads.put(new String(key), value); 65 | return this; 66 | } 67 | 68 | 69 | 70 | public static ItHeiMaHttp httpManager; 71 | 72 | public static ItHeiMaHttp getInstance() { 73 | if (httpManager == null) { 74 | synchronized (ItHeiMaHttp.class) { 75 | httpManager = new ItHeiMaHttp(); 76 | } 77 | } 78 | return httpManager; 79 | } 80 | 81 | public void get(String url, WSCallBack bcb) { 82 | Request request = buildRequest(url, RequestType.GET); 83 | doRequest(request, bcb); 84 | } 85 | 86 | public void post(String url, WSCallBack bcb) { 87 | Request request = buildRequest(url, RequestType.POST); 88 | doRequest(request, bcb); 89 | } 90 | 91 | 92 | 93 | private Request buildRequest(String url, RequestType type) { 94 | Request.Builder builder = new Request.Builder(); 95 | if (type == RequestType.GET) { 96 | url = getParamWithString(url); 97 | builder.get(); 98 | } else if (type == RequestType.POST) { 99 | RequestBody requestBody = getFormatData(params); 100 | builder.post(requestBody); 101 | } 102 | builder.url(url); 103 | addAllHeads(builder); 104 | return builder.build(); 105 | } 106 | 107 | private void addAllHeads(Request.Builder builder) { 108 | if (heads.size()>0){ 109 | for (Map.Entry entry : heads.entrySet()) { 110 | builder.addHeader(entry.getKey(),entry.getValue()); 111 | } 112 | } 113 | } 114 | 115 | 116 | public String getParamWithString(String url) { 117 | if (params == null || params.size() < 1) 118 | return url; 119 | StringBuilder sb = new StringBuilder(); 120 | if (url.indexOf("http://") == 0 121 | || url.indexOf("https://") == 0) { 122 | sb.append(url + "?"); 123 | } 124 | 125 | for (Map.Entry entry : params.entrySet()) { 126 | sb.append(entry.getKey()).append("=").append(entry.getValue()) 127 | .append("&"); 128 | } 129 | 130 | return sb.toString().substring(0, (sb.toString().length() - 1)); 131 | } 132 | 133 | private RequestBody getFormatData(Map params) { 134 | FormBody.Builder builder = new FormBody.Builder(); 135 | if (params != null && params.size() > 0) 136 | for (Map.Entry entry : params.entrySet()) { 137 | builder.add(entry.getKey(), entry.getValue()); 138 | } 139 | return builder.build(); 140 | } 141 | 142 | enum RequestType { 143 | GET, 144 | POST 145 | } 146 | 147 | private void doRequest(Request request, final WSCallBack baseCallBack) { 148 | 149 | okHttpClient.newCall(request).enqueue(new Callback() { 150 | @Override 151 | public void onFailure(Call call, IOException e) { 152 | sendFaile(baseCallBack, call, e); 153 | } 154 | 155 | @Override 156 | public void onResponse(Call call, Response response) throws IOException { 157 | if (response.isSuccessful()) { 158 | String json = response.body().string(); 159 | sendSuccess(json, call, baseCallBack); 160 | } else { 161 | sendFaile(baseCallBack, call, null); 162 | } 163 | } 164 | }); 165 | 166 | } 167 | 168 | private void sendFaile(final WSCallBack bcb, final Call call, Exception e) { 169 | handler.post(new Runnable() { 170 | @Override 171 | public void run() { 172 | bcb.onFailure(call, null); 173 | } 174 | }); 175 | } 176 | 177 | private void sendSuccess(final String json, final Call call, final WSCallBack bcb) { 178 | handler.post(new Runnable() { 179 | @Override 180 | public void run() { 181 | if (bcb.type == String.class) { 182 | bcb.onSuccess(json); 183 | } else { 184 | try { 185 | Object object = gson.fromJson(json, bcb.type); 186 | bcb.onSuccess(object); 187 | } catch (JsonParseException e) { 188 | sendFaile(bcb, call, e); 189 | } 190 | } 191 | } 192 | }); 193 | } 194 | 195 | 196 | } 197 | --------------------------------------------------------------------------------