├── .gitignore ├── .idea ├── .name ├── compiler.xml ├── copyright │ └── profiles_settings.xml ├── gradle.xml ├── misc.xml ├── modules.xml ├── runConfigurations.xml └── vcs.xml ├── LICENSE ├── OkHttpManager.iml ├── README.md ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── okhttp-utils.iml ├── okhttputils-2_6_2.jar ├── okhttputils ├── .gitignore ├── build.gradle ├── okhttputils.iml ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── zhy │ │ └── http │ │ └── okhttp │ │ └── ApplicationTest.java │ └── main │ ├── AndroidManifest.xml │ └── java │ └── com │ └── zhy │ └── http │ └── okhttp │ ├── OkHttpUtils.java │ ├── builder │ ├── GetBuilder.java │ ├── HasParamsable.java │ ├── HeadBuilder.java │ ├── OkHttpRequestBuilder.java │ ├── OtherRequestBuilder.java │ ├── PostFileBuilder.java │ ├── PostFormBuilder.java │ └── PostStringBuilder.java │ ├── callback │ ├── BitmapCallback.java │ ├── Callback.java │ ├── FileCallBack.java │ ├── GenericsCallback.java │ ├── IGenericsSerializator.java │ └── StringCallback.java │ ├── cookie │ ├── CookieJarImpl.java │ └── store │ │ ├── CookieStore.java │ │ ├── HasCookieStore.java │ │ ├── MemoryCookieStore.java │ │ ├── PersistentCookieStore.java │ │ └── SerializableHttpCookie.java │ ├── https │ └── HttpsUtils.java │ ├── log │ └── LoggerInterceptor.java │ ├── request │ ├── CountingRequestBody.java │ ├── GetRequest.java │ ├── OkHttpRequest.java │ ├── OtherRequest.java │ ├── PostFileRequest.java │ ├── PostFormRequest.java │ ├── PostStringRequest.java │ └── RequestCall.java │ └── utils │ ├── Exceptions.java │ ├── ImageUtils.java │ ├── L.java │ └── Platform.java ├── sample-okhttp ├── .gitignore ├── build.gradle ├── proguard-rules.pro ├── sample-okhttp.iml └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── zhy │ │ └── sample_okhttp │ │ └── ApplicationTest.java │ └── main │ ├── AndroidManifest.xml │ ├── assets │ ├── srca.cer │ ├── zhy_client.bks │ └── zhy_server.cer │ ├── java │ └── com │ │ └── zhy │ │ └── sample_okhttp │ │ ├── FlowLayout.java │ │ ├── JsonGenericsSerializator.java │ │ ├── ListUserCallback.java │ │ ├── MainActivity.java │ │ ├── MyApplication.java │ │ ├── User.java │ │ └── UserCallback.java │ └── res │ ├── layout │ └── activity_main.xml │ ├── menu │ └── menu_main.xml │ ├── mipmap-hdpi │ └── ic_launcher.png │ ├── mipmap-mdpi │ └── ic_launcher.png │ ├── mipmap-xhdpi │ └── ic_launcher.png │ ├── mipmap-xxhdpi │ └── ic_launcher.png │ ├── values-w820dp │ └── dimens.xml │ └── values │ ├── dimens.xml │ ├── strings.xml │ └── styles.xml └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | /local.properties 3 | /.idea/ 4 | /.idea/workspace.xml 5 | /.idea/libraries 6 | .DS_Store 7 | /build 8 | /captures 9 | /okhttp3* 10 | -------------------------------------------------------------------------------- /.idea/.name: -------------------------------------------------------------------------------- 1 | okhttp-utils -------------------------------------------------------------------------------- /.idea/compiler.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 22 | -------------------------------------------------------------------------------- /.idea/copyright/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /.idea/gradle.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 25 | 26 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 19 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 46 | 47 | 48 | 49 | 50 | 1.7 51 | 52 | 57 | 58 | 59 | 60 | 61 | 62 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /.idea/runConfigurations.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 11 | 12 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /OkHttpManager.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # okhttp-utils 2 | 3 | >由于个人原因,现已停止维护。 4 | 5 | 对okhttp的封装类,okhttp见:[https://github.com/square/okhttp](https://github.com/square/okhttp). 6 | 7 | 目前对应okhttp版本`3.3.1`. 8 | 9 | ## 用法 10 | 11 | * Android Studio 12 | 13 | ``` 14 | compile 'com.zhy:okhttputils:2.6.2' 15 | ``` 16 | 17 | * Eclipse 18 | 19 | 下载最新jar:[okhttputils-2\_6\_2.jar](okhttputils-2_6_2.jar?raw=true) 20 | 21 | 注:需要同时导入okhttp和okio的jar,下载见:[https://github.com/square/okhttp](https://github.com/square/okhttp). 22 | 23 | 24 | ## 目前对以下需求进行了封装 25 | * 一般的get请求 26 | * 一般的post请求 27 | * 基于Http Post的文件上传(类似表单) 28 | * 文件下载/加载图片 29 | * 上传下载的进度回调 30 | * 支持取消某个请求 31 | * 支持自定义Callback 32 | * 支持HEAD、DELETE、PATCH、PUT 33 | * 支持session的保持 34 | * 支持自签名网站https的访问,提供方法设置下证书就行 35 | 36 | ## 配置OkhttpClient 37 | 38 | 默认情况下,将直接使用okhttp默认的配置生成OkhttpClient,如果你有任何配置,记得在Application中调用`initClient`方法进行设置。 39 | 40 | ```java 41 | public class MyApplication extends Application 42 | { 43 | @Override 44 | public void onCreate() 45 | { 46 | super.onCreate(); 47 | 48 | OkHttpClient okHttpClient = new OkHttpClient.Builder() 49 | // .addInterceptor(new LoggerInterceptor("TAG")) 50 | .connectTimeout(10000L, TimeUnit.MILLISECONDS) 51 | .readTimeout(10000L, TimeUnit.MILLISECONDS) 52 | //其他配置 53 | .build(); 54 | 55 | OkHttpUtils.initClient(okHttpClient); 56 | 57 | } 58 | } 59 | ``` 60 | 别忘了在AndroidManifest中设置。 61 | 62 | ## 对于Cookie(包含Session) 63 | 64 | 对于cookie一样,直接通过cookiejar方法配置,参考上面的配置过程。 65 | 66 | ``` 67 | CookieJarImpl cookieJar = new CookieJarImpl(new PersistentCookieStore(getApplicationContext())); 68 | OkHttpClient okHttpClient = new OkHttpClient.Builder() 69 | .cookieJar(cookieJar) 70 | //其他配置 71 | .build(); 72 | 73 | OkHttpUtils.initClient(okHttpClient); 74 | ``` 75 | 目前项目中包含: 76 | 77 | * PersistentCookieStore //持久化cookie 78 | * SerializableHttpCookie //持久化cookie 79 | * MemoryCookieStore //cookie信息存在内存中 80 | 81 | 如果遇到问题,欢迎反馈,当然也可以自己实现CookieJar接口,编写cookie管理相关代码。 82 | 83 | 此外,对于持久化cookie还可以使用[https://github.com/franmontiel/PersistentCookieJar](https://github.com/franmontiel/PersistentCookieJar). 84 | 85 | 相当于框架中只是提供了几个实现类,你可以自行定制或者选择使用。 86 | 87 | ## 对于Log 88 | 89 | 初始化OkhttpClient时,通过设置拦截器实现,框架中提供了一个`LoggerInterceptor `,当然你可以自行实现一个Interceptor 。 90 | 91 | ``` 92 | OkHttpClient okHttpClient = new OkHttpClient.Builder() 93 | .addInterceptor(new LoggerInterceptor("TAG")) 94 | //其他配置 95 | .build(); 96 | OkHttpUtils.initClient(okHttpClient); 97 | ``` 98 | 99 | 100 | ## 对于Https 101 | 102 | 依然是通过配置即可,框架中提供了一个类`HttpsUtils` 103 | 104 | * 设置可访问所有的https网站 105 | 106 | ``` 107 | HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory(null, null, null); 108 | OkHttpClient okHttpClient = new OkHttpClient.Builder() 109 | .sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager) 110 | //其他配置 111 | .build(); 112 | OkHttpUtils.initClient(okHttpClient); 113 | ``` 114 | 115 | * 设置具体的证书 116 | 117 | ``` 118 | HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory(证书的inputstream, null, null); 119 | OkHttpClient okHttpClient = new OkHttpClient.Builder() 120 | .sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager)) 121 | //其他配置 122 | .build(); 123 | OkHttpUtils.initClient(okHttpClient); 124 | ``` 125 | 126 | * 双向认证 127 | 128 | ``` 129 | HttpsUtils.getSslSocketFactory( 130 | 证书的inputstream, 131 | 本地证书的inputstream, 132 | 本地证书的密码) 133 | ``` 134 | 135 | 同样的,框架中只是提供了几个实现类,你可以自行实现`SSLSocketFactory`,传入sslSocketFactory即可。 136 | 137 | ##其他用法示例 138 | 139 | ### GET请求 140 | 141 | ```java 142 | String url = "http://www.csdn.net/"; 143 | OkHttpUtils 144 | .get() 145 | .url(url) 146 | .addParams("username", "hyman") 147 | .addParams("password", "123") 148 | .build() 149 | .execute(new StringCallback() 150 | { 151 | @Override 152 | public void onError(Request request, Exception e) 153 | { 154 | 155 | } 156 | 157 | @Override 158 | public void onResponse(String response) 159 | { 160 | 161 | } 162 | }); 163 | ``` 164 | 165 | ### POST请求 166 | 167 | ```java 168 | OkHttpUtils 169 | .post() 170 | .url(url) 171 | .addParams("username", "hyman") 172 | .addParams("password", "123") 173 | .build() 174 | .execute(callback); 175 | 176 | ``` 177 | 178 | ### Post JSON 179 | 180 | ```java 181 | OkHttpUtils 182 | .postString() 183 | .url(url) 184 | .content(new Gson().toJson(new User("zhy", "123"))) 185 | .mediaType(MediaType.parse("application/json; charset=utf-8")) 186 | .build() 187 | .execute(new MyStringCallback()); 188 | ``` 189 | 190 | 提交一个Gson字符串到服务器端,注意:传递JSON的时候,不要通过addHeader去设置contentType,而使用`.mediaType(MediaType.parse("application/json; charset=utf-8"))`.。 191 | 192 | ### Post File 193 | 194 | ```java 195 | OkHttpUtils 196 | .postFile() 197 | .url(url) 198 | .file(file) 199 | .build() 200 | .execute(new MyStringCallback()); 201 | ``` 202 | 将文件作为请求体,发送到服务器。 203 | 204 | 205 | ### Post表单形式上传文件 206 | 207 | ```java 208 | OkHttpUtils.post()// 209 | .addFile("mFile", "messenger_01.png", file)// 210 | .addFile("mFile", "test1.txt", file2)// 211 | .url(url) 212 | .params(params)// 213 | .headers(headers)// 214 | .build()// 215 | .execute(new MyStringCallback()); 216 | ``` 217 | 218 | 支持单个多个文件,`addFile`的第一个参数为文件的key,即类别表单中``的name属性。 219 | 220 | ### 自定义CallBack 221 | 222 | 目前内部包含`StringCallBack`,`FileCallBack`,`BitmapCallback`,可以根据自己的需求去自定义Callback,例如希望回调User对象: 223 | 224 | ```java 225 | public abstract class UserCallback extends Callback 226 | { 227 | @Override 228 | public User parseNetworkResponse(Response response) throws IOException 229 | { 230 | String string = response.body().string(); 231 | User user = new Gson().fromJson(string, User.class); 232 | return user; 233 | } 234 | } 235 | 236 | OkHttpUtils 237 | .get()// 238 | .url(url)// 239 | .addParams("username", "hyman")// 240 | .addParams("password", "123")// 241 | .build()// 242 | .execute(new UserCallback() 243 | { 244 | @Override 245 | public void onError(Request request, Exception e) 246 | { 247 | mTv.setText("onError:" + e.getMessage()); 248 | } 249 | 250 | @Override 251 | public void onResponse(User response) 252 | { 253 | mTv.setText("onResponse:" + response.username); 254 | } 255 | }); 256 | 257 | ``` 258 | 259 | 通过`parseNetworkResponse `回调的response进行解析,该方法运行在子线程,所以可以进行任何耗时操作,详细参见sample。 260 | 261 | 262 | ### 下载文件 263 | 264 | ```java 265 | OkHttpUtils// 266 | .get()// 267 | .url(url)// 268 | .build()// 269 | .execute(new FileCallBack(Environment.getExternalStorageDirectory().getAbsolutePath(), "gson-2.2.1.jar")// 270 | { 271 | @Override 272 | public void inProgress(float progress) 273 | { 274 | mProgressBar.setProgress((int) (100 * progress)); 275 | } 276 | 277 | @Override 278 | public void onError(Request request, Exception e) 279 | { 280 | Log.e(TAG, "onError :" + e.getMessage()); 281 | } 282 | 283 | @Override 284 | public void onResponse(File file) 285 | { 286 | Log.e(TAG, "onResponse :" + file.getAbsolutePath()); 287 | } 288 | }); 289 | ``` 290 | 291 | 注意下载文件可以使用`FileCallback`,需要传入文件需要保存的文件夹以及文件名。 292 | 293 | 294 | ### 显示图片 295 | 296 | ```java 297 | OkHttpUtils 298 | .get()// 299 | .url(url)// 300 | .build()// 301 | .execute(new BitmapCallback() 302 | { 303 | @Override 304 | public void onError(Request request, Exception e) 305 | { 306 | mTv.setText("onError:" + e.getMessage()); 307 | } 308 | 309 | @Override 310 | public void onResponse(Bitmap bitmap) 311 | { 312 | mImageView.setImageBitmap(bitmap); 313 | } 314 | }); 315 | ``` 316 | 317 | 显示图片,回调传入`BitmapCallback`即可。 318 | 319 | 320 | ### 上传下载的进度显示 321 | 322 | ```java 323 | new Callback() 324 | { 325 | //... 326 | @Override 327 | public void inProgress(float progress) 328 | { 329 | //use progress: 0 ~ 1 330 | } 331 | } 332 | ``` 333 | 334 | callback回调中有`inProgress `方法,直接复写即可。 335 | 336 | ### HEAD、DELETE、PUT、PATCH 337 | 338 | ```java 339 | 340 | OkHttpUtils 341 | .put()//also can use delete() ,head() , patch() 342 | .requestBody(RequestBody.create(null, "may be something"))// 343 | .build()// 344 | .execute(new MyStringCallback()); 345 | ``` 346 | 347 | 如果需要requestBody,例如:PUT、PATCH,自行构造进行传入。 348 | 349 | 350 | 351 | ### 同步的请求 352 | 353 | ``` 354 | Response response = OkHttpUtils 355 | .get()// 356 | .url(url)// 357 | .tag(this)// 358 | .build()// 359 | .execute(); 360 | ``` 361 | 362 | execute方法不传入callback即为同步的请求,返回Response。 363 | 364 | 365 | ### 取消单个请求 366 | 367 | ```java 368 | RequestCall call = OkHttpUtils.get().url(url).build(); 369 | call.cancel(); 370 | 371 | ``` 372 | 373 | ### 根据tag取消请求 374 | 375 | 目前对于支持的方法都添加了最后一个参数`Object tag`,取消则通过` OkHttpUtils.cancelTag(tag)`执行。 376 | 377 | 例如:在Activity中,当Activity销毁取消请求: 378 | 379 | ``` 380 | OkHttpUtils 381 | .get()// 382 | .url(url)// 383 | .tag(this)// 384 | .build()// 385 | 386 | @Override 387 | protected void onDestroy() 388 | { 389 | super.onDestroy(); 390 | //可以取消同一个tag的 391 | OkHttpUtils.cancelTag(this);//取消以Activity.this作为tag的请求 392 | } 393 | ``` 394 | 比如,当前Activity页面所有的请求以Activity对象作为tag,可以在onDestory里面统一取消。 395 | 396 | ## 混淆 397 | 398 | ``` 399 | #okhttputils 400 | -dontwarn com.zhy.http.** 401 | -keep class com.zhy.http.**{*;} 402 | 403 | 404 | #okhttp 405 | -dontwarn okhttp3.** 406 | -keep class okhttp3.**{*;} 407 | 408 | 409 | #okio 410 | -dontwarn okio.** 411 | -keep class okio.**{*;} 412 | 413 | 414 | ``` 415 | 416 | 417 | 418 | 419 | 420 | 421 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | 3 | buildscript { 4 | repositories { 5 | jcenter() 6 | 7 | } 8 | dependencies { 9 | classpath 'com.android.tools.build:gradle:2.1.0' 10 | classpath 'com.novoda:bintray-release:0.3.4' 11 | 12 | 13 | // NOTE: Do not place your application dependencies here; they belong 14 | // in the individual module build.gradle files 15 | } 16 | } 17 | 18 | allprojects { 19 | repositories { 20 | jcenter() 21 | maven { url "https://www.jitpack.io" } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /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 | # Default value: -Xmx10248m -XX:MaxPermSize=256m 13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 14 | 15 | # When configured, Gradle will run in incubating parallel mode. 16 | # This option should only be used with decoupled projects. More details, visit 17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 18 | # org.gradle.parallel=true -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hongyangAndroid/okhttputils/11fdc3c7368e481cc182e79188973418bc5d0939/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Wed Jun 01 11:58:20 GMT+08:00 2016 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.10-all.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # For Cygwin, ensure paths are in UNIX format before anything is touched. 46 | if $cygwin ; then 47 | [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 48 | fi 49 | 50 | # Attempt to set APP_HOME 51 | # Resolve links: $0 may be a link 52 | PRG="$0" 53 | # Need this for relative symlinks. 54 | while [ -h "$PRG" ] ; do 55 | ls=`ls -ld "$PRG"` 56 | link=`expr "$ls" : '.*-> \(.*\)$'` 57 | if expr "$link" : '/.*' > /dev/null; then 58 | PRG="$link" 59 | else 60 | PRG=`dirname "$PRG"`"/$link" 61 | fi 62 | done 63 | SAVED="`pwd`" 64 | cd "`dirname \"$PRG\"`/" >&- 65 | APP_HOME="`pwd -P`" 66 | cd "$SAVED" >&- 67 | 68 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 69 | 70 | # Determine the Java command to use to start the JVM. 71 | if [ -n "$JAVA_HOME" ] ; then 72 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 73 | # IBM's JDK on AIX uses strange locations for the executables 74 | JAVACMD="$JAVA_HOME/jre/sh/java" 75 | else 76 | JAVACMD="$JAVA_HOME/bin/java" 77 | fi 78 | if [ ! -x "$JAVACMD" ] ; then 79 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 80 | 81 | Please set the JAVA_HOME variable in your environment to match the 82 | location of your Java installation." 83 | fi 84 | else 85 | JAVACMD="java" 86 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 87 | 88 | Please set the JAVA_HOME variable in your environment to match the 89 | location of your Java installation." 90 | fi 91 | 92 | # Increase the maximum file descriptors if we can. 93 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 94 | MAX_FD_LIMIT=`ulimit -H -n` 95 | if [ $? -eq 0 ] ; then 96 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 97 | MAX_FD="$MAX_FD_LIMIT" 98 | fi 99 | ulimit -n $MAX_FD 100 | if [ $? -ne 0 ] ; then 101 | warn "Could not set maximum file descriptor limit: $MAX_FD" 102 | fi 103 | else 104 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 105 | fi 106 | fi 107 | 108 | # For Darwin, add options to specify how the application appears in the dock 109 | if $darwin; then 110 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 111 | fi 112 | 113 | # For Cygwin, switch paths to Windows format before running java 114 | if $cygwin ; then 115 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 116 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 158 | function splitJvmOpts() { 159 | JVM_OPTS=("$@") 160 | } 161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 163 | 164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 165 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /okhttp-utils.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /okhttputils-2_6_2.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hongyangAndroid/okhttputils/11fdc3c7368e481cc182e79188973418bc5d0939/okhttputils-2_6_2.jar -------------------------------------------------------------------------------- /okhttputils/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /okhttputils/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | apply plugin: 'com.novoda.bintray-release'//添加 3 | 4 | 5 | android { 6 | compileSdkVersion 23 7 | buildToolsVersion "23.0.1" 8 | 9 | defaultConfig { 10 | minSdkVersion 9 11 | targetSdkVersion 23 12 | versionCode 1 13 | versionName "1.0" 14 | } 15 | buildTypes { 16 | release { 17 | minifyEnabled false 18 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 19 | } 20 | } 21 | lintOptions{ 22 | abortOnError false 23 | warning 'InvalidPackage' 24 | } 25 | 26 | } 27 | 28 | 29 | task clearJar(type: Delete) { 30 | delete 'build/outputs/okhttputils.jar' 31 | } 32 | 33 | task makeJar(type: Copy) { 34 | from('build/intermediates/bundles/release/') 35 | into('build/outputs/') 36 | include('classes.jar') 37 | rename ('classes.jar', 'okhttputils-2_6_2.jar') 38 | } 39 | 40 | makeJar.dependsOn(clearJar, build) 41 | 42 | 43 | 44 | dependencies { 45 | compile fileTree(dir: 'libs', include: ['*.jar']) 46 | compile 'com.squareup.okhttp3:okhttp:3.3.1' 47 | } 48 | 49 | //添加 50 | publish { 51 | userOrg = 'hongyangandroid'//bintray.com用户名 52 | groupId = 'com.zhy'//jcenter上的路径 53 | artifactId = 'okhttputils'//项目名称 54 | publishVersion = '2.6.2'//版本号 55 | desc = 'Oh hi, this is a nice description for a project, right?' 56 | website = 'https://github.com/hongyangAndroid/okhttp-utils' 57 | } 58 | 59 | -------------------------------------------------------------------------------- /okhttputils/okhttputils.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 8 | 9 | 10 | 11 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | -------------------------------------------------------------------------------- /okhttputils/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 /Users/zhy/android/sdk/android-sdk-macosx/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 | -------------------------------------------------------------------------------- /okhttputils/src/androidTest/java/com/zhy/http/okhttp/ApplicationTest.java: -------------------------------------------------------------------------------- 1 | package com.zhy.http.okhttp; 2 | 3 | import android.app.Application; 4 | import android.test.ApplicationTestCase; 5 | 6 | /** 7 | * Testing Fundamentals 8 | */ 9 | public class ApplicationTest extends ApplicationTestCase 10 | { 11 | public ApplicationTest() 12 | { 13 | super(Application.class); 14 | } 15 | } -------------------------------------------------------------------------------- /okhttputils/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /okhttputils/src/main/java/com/zhy/http/okhttp/OkHttpUtils.java: -------------------------------------------------------------------------------- 1 | package com.zhy.http.okhttp; 2 | 3 | import com.zhy.http.okhttp.builder.GetBuilder; 4 | import com.zhy.http.okhttp.builder.HeadBuilder; 5 | import com.zhy.http.okhttp.builder.OtherRequestBuilder; 6 | import com.zhy.http.okhttp.builder.PostFileBuilder; 7 | import com.zhy.http.okhttp.builder.PostFormBuilder; 8 | import com.zhy.http.okhttp.builder.PostStringBuilder; 9 | import com.zhy.http.okhttp.callback.Callback; 10 | import com.zhy.http.okhttp.request.RequestCall; 11 | import com.zhy.http.okhttp.utils.Platform; 12 | 13 | import java.io.IOException; 14 | import java.util.concurrent.Executor; 15 | 16 | import okhttp3.Call; 17 | import okhttp3.OkHttpClient; 18 | import okhttp3.Response; 19 | 20 | /** 21 | * Created by zhy on 15/8/17. 22 | */ 23 | public class OkHttpUtils 24 | { 25 | public static final long DEFAULT_MILLISECONDS = 10_000L; 26 | private volatile static OkHttpUtils mInstance; 27 | private OkHttpClient mOkHttpClient; 28 | private Platform mPlatform; 29 | 30 | public OkHttpUtils(OkHttpClient okHttpClient) 31 | { 32 | if (okHttpClient == null) 33 | { 34 | mOkHttpClient = new OkHttpClient(); 35 | } else 36 | { 37 | mOkHttpClient = okHttpClient; 38 | } 39 | 40 | mPlatform = Platform.get(); 41 | } 42 | 43 | 44 | public static OkHttpUtils initClient(OkHttpClient okHttpClient) 45 | { 46 | if (mInstance == null) 47 | { 48 | synchronized (OkHttpUtils.class) 49 | { 50 | if (mInstance == null) 51 | { 52 | mInstance = new OkHttpUtils(okHttpClient); 53 | } 54 | } 55 | } 56 | return mInstance; 57 | } 58 | 59 | public static OkHttpUtils getInstance() 60 | { 61 | return initClient(null); 62 | } 63 | 64 | 65 | public Executor getDelivery() 66 | { 67 | return mPlatform.defaultCallbackExecutor(); 68 | } 69 | 70 | public OkHttpClient getOkHttpClient() 71 | { 72 | return mOkHttpClient; 73 | } 74 | 75 | public static GetBuilder get() 76 | { 77 | return new GetBuilder(); 78 | } 79 | 80 | public static PostStringBuilder postString() 81 | { 82 | return new PostStringBuilder(); 83 | } 84 | 85 | public static PostFileBuilder postFile() 86 | { 87 | return new PostFileBuilder(); 88 | } 89 | 90 | public static PostFormBuilder post() 91 | { 92 | return new PostFormBuilder(); 93 | } 94 | 95 | public static OtherRequestBuilder put() 96 | { 97 | return new OtherRequestBuilder(METHOD.PUT); 98 | } 99 | 100 | public static HeadBuilder head() 101 | { 102 | return new HeadBuilder(); 103 | } 104 | 105 | public static OtherRequestBuilder delete() 106 | { 107 | return new OtherRequestBuilder(METHOD.DELETE); 108 | } 109 | 110 | public static OtherRequestBuilder patch() 111 | { 112 | return new OtherRequestBuilder(METHOD.PATCH); 113 | } 114 | 115 | public void execute(final RequestCall requestCall, Callback callback) 116 | { 117 | if (callback == null) 118 | callback = Callback.CALLBACK_DEFAULT; 119 | final Callback finalCallback = callback; 120 | final int id = requestCall.getOkHttpRequest().getId(); 121 | 122 | requestCall.getCall().enqueue(new okhttp3.Callback() 123 | { 124 | @Override 125 | public void onFailure(Call call, final IOException e) 126 | { 127 | sendFailResultCallback(call, e, finalCallback, id); 128 | } 129 | 130 | @Override 131 | public void onResponse(final Call call, final Response response) 132 | { 133 | try 134 | { 135 | if (call.isCanceled()) 136 | { 137 | sendFailResultCallback(call, new IOException("Canceled!"), finalCallback, id); 138 | return; 139 | } 140 | 141 | if (!finalCallback.validateReponse(response, id)) 142 | { 143 | sendFailResultCallback(call, new IOException("request failed , reponse's code is : " + response.code()), finalCallback, id); 144 | return; 145 | } 146 | 147 | Object o = finalCallback.parseNetworkResponse(response, id); 148 | sendSuccessResultCallback(o, finalCallback, id); 149 | } catch (Exception e) 150 | { 151 | sendFailResultCallback(call, e, finalCallback, id); 152 | } finally 153 | { 154 | if (response.body() != null) 155 | response.body().close(); 156 | } 157 | 158 | } 159 | }); 160 | } 161 | 162 | 163 | public void sendFailResultCallback(final Call call, final Exception e, final Callback callback, final int id) 164 | { 165 | if (callback == null) return; 166 | 167 | mPlatform.execute(new Runnable() 168 | { 169 | @Override 170 | public void run() 171 | { 172 | callback.onError(call, e, id); 173 | callback.onAfter(id); 174 | } 175 | }); 176 | } 177 | 178 | public void sendSuccessResultCallback(final Object object, final Callback callback, final int id) 179 | { 180 | if (callback == null) return; 181 | mPlatform.execute(new Runnable() 182 | { 183 | @Override 184 | public void run() 185 | { 186 | callback.onResponse(object, id); 187 | callback.onAfter(id); 188 | } 189 | }); 190 | } 191 | 192 | public void cancelTag(Object tag) 193 | { 194 | for (Call call : mOkHttpClient.dispatcher().queuedCalls()) 195 | { 196 | if (tag.equals(call.request().tag())) 197 | { 198 | call.cancel(); 199 | } 200 | } 201 | for (Call call : mOkHttpClient.dispatcher().runningCalls()) 202 | { 203 | if (tag.equals(call.request().tag())) 204 | { 205 | call.cancel(); 206 | } 207 | } 208 | } 209 | 210 | public static class METHOD 211 | { 212 | public static final String HEAD = "HEAD"; 213 | public static final String DELETE = "DELETE"; 214 | public static final String PUT = "PUT"; 215 | public static final String PATCH = "PATCH"; 216 | } 217 | } 218 | 219 | -------------------------------------------------------------------------------- /okhttputils/src/main/java/com/zhy/http/okhttp/builder/GetBuilder.java: -------------------------------------------------------------------------------- 1 | package com.zhy.http.okhttp.builder; 2 | 3 | import android.net.Uri; 4 | 5 | import com.zhy.http.okhttp.request.GetRequest; 6 | import com.zhy.http.okhttp.request.RequestCall; 7 | 8 | import java.util.Iterator; 9 | import java.util.LinkedHashMap; 10 | import java.util.Map; 11 | import java.util.Set; 12 | 13 | /** 14 | * Created by zhy on 15/12/14. 15 | */ 16 | public class GetBuilder extends OkHttpRequestBuilder implements HasParamsable 17 | { 18 | @Override 19 | public RequestCall build() 20 | { 21 | if (params != null) 22 | { 23 | url = appendParams(url, params); 24 | } 25 | 26 | return new GetRequest(url, tag, params, headers,id).build(); 27 | } 28 | 29 | protected String appendParams(String url, Map params) 30 | { 31 | if (url == null || params == null || params.isEmpty()) 32 | { 33 | return url; 34 | } 35 | Uri.Builder builder = Uri.parse(url).buildUpon(); 36 | Set keys = params.keySet(); 37 | Iterator iterator = keys.iterator(); 38 | while (iterator.hasNext()) 39 | { 40 | String key = iterator.next(); 41 | builder.appendQueryParameter(key, params.get(key)); 42 | } 43 | return builder.build().toString(); 44 | } 45 | 46 | 47 | @Override 48 | public GetBuilder params(Map params) 49 | { 50 | this.params = params; 51 | return this; 52 | } 53 | 54 | @Override 55 | public GetBuilder addParams(String key, String val) 56 | { 57 | if (this.params == null) 58 | { 59 | params = new LinkedHashMap<>(); 60 | } 61 | params.put(key, val); 62 | return this; 63 | } 64 | 65 | 66 | } 67 | -------------------------------------------------------------------------------- /okhttputils/src/main/java/com/zhy/http/okhttp/builder/HasParamsable.java: -------------------------------------------------------------------------------- 1 | package com.zhy.http.okhttp.builder; 2 | 3 | import java.util.Map; 4 | 5 | /** 6 | * Created by zhy on 16/3/1. 7 | */ 8 | public interface HasParamsable 9 | { 10 | OkHttpRequestBuilder params(Map params); 11 | OkHttpRequestBuilder addParams(String key, String val); 12 | } 13 | -------------------------------------------------------------------------------- /okhttputils/src/main/java/com/zhy/http/okhttp/builder/HeadBuilder.java: -------------------------------------------------------------------------------- 1 | package com.zhy.http.okhttp.builder; 2 | 3 | import com.zhy.http.okhttp.OkHttpUtils; 4 | import com.zhy.http.okhttp.request.OtherRequest; 5 | import com.zhy.http.okhttp.request.RequestCall; 6 | 7 | /** 8 | * Created by zhy on 16/3/2. 9 | */ 10 | public class HeadBuilder extends GetBuilder 11 | { 12 | @Override 13 | public RequestCall build() 14 | { 15 | return new OtherRequest(null, null, OkHttpUtils.METHOD.HEAD, url, tag, params, headers,id).build(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /okhttputils/src/main/java/com/zhy/http/okhttp/builder/OkHttpRequestBuilder.java: -------------------------------------------------------------------------------- 1 | package com.zhy.http.okhttp.builder; 2 | 3 | import com.zhy.http.okhttp.request.RequestCall; 4 | 5 | import java.util.LinkedHashMap; 6 | import java.util.Map; 7 | 8 | /** 9 | * Created by zhy on 15/12/14. 10 | */ 11 | public abstract class OkHttpRequestBuilder 12 | { 13 | protected String url; 14 | protected Object tag; 15 | protected Map headers; 16 | protected Map params; 17 | protected int id; 18 | 19 | public T id(int id) 20 | { 21 | this.id = id; 22 | return (T) this; 23 | } 24 | 25 | public T url(String url) 26 | { 27 | this.url = url; 28 | return (T) this; 29 | } 30 | 31 | 32 | public T tag(Object tag) 33 | { 34 | this.tag = tag; 35 | return (T) this; 36 | } 37 | 38 | public T headers(Map headers) 39 | { 40 | this.headers = headers; 41 | return (T) this; 42 | } 43 | 44 | public T addHeader(String key, String val) 45 | { 46 | if (this.headers == null) 47 | { 48 | headers = new LinkedHashMap<>(); 49 | } 50 | headers.put(key, val); 51 | return (T) this; 52 | } 53 | 54 | public abstract RequestCall build(); 55 | } 56 | -------------------------------------------------------------------------------- /okhttputils/src/main/java/com/zhy/http/okhttp/builder/OtherRequestBuilder.java: -------------------------------------------------------------------------------- 1 | package com.zhy.http.okhttp.builder; 2 | 3 | import com.zhy.http.okhttp.request.OtherRequest; 4 | import com.zhy.http.okhttp.request.RequestCall; 5 | 6 | import okhttp3.RequestBody; 7 | 8 | /** 9 | * DELETE、PUT、PATCH等其他方法 10 | */ 11 | public class OtherRequestBuilder extends OkHttpRequestBuilder 12 | { 13 | private RequestBody requestBody; 14 | private String method; 15 | private String content; 16 | 17 | public OtherRequestBuilder(String method) 18 | { 19 | this.method = method; 20 | } 21 | 22 | @Override 23 | public RequestCall build() 24 | { 25 | return new OtherRequest(requestBody, content, method, url, tag, params, headers,id).build(); 26 | } 27 | 28 | public OtherRequestBuilder requestBody(RequestBody requestBody) 29 | { 30 | this.requestBody = requestBody; 31 | return this; 32 | } 33 | 34 | public OtherRequestBuilder requestBody(String content) 35 | { 36 | this.content = content; 37 | return this; 38 | } 39 | 40 | 41 | } 42 | -------------------------------------------------------------------------------- /okhttputils/src/main/java/com/zhy/http/okhttp/builder/PostFileBuilder.java: -------------------------------------------------------------------------------- 1 | package com.zhy.http.okhttp.builder; 2 | 3 | import com.zhy.http.okhttp.request.PostFileRequest; 4 | import com.zhy.http.okhttp.request.RequestCall; 5 | 6 | import java.io.File; 7 | 8 | import okhttp3.MediaType; 9 | 10 | /** 11 | * Created by zhy on 15/12/14. 12 | */ 13 | public class PostFileBuilder extends OkHttpRequestBuilder 14 | { 15 | private File file; 16 | private MediaType mediaType; 17 | 18 | 19 | public OkHttpRequestBuilder file(File file) 20 | { 21 | this.file = file; 22 | return this; 23 | } 24 | 25 | public OkHttpRequestBuilder mediaType(MediaType mediaType) 26 | { 27 | this.mediaType = mediaType; 28 | return this; 29 | } 30 | 31 | @Override 32 | public RequestCall build() 33 | { 34 | return new PostFileRequest(url, tag, params, headers, file, mediaType,id).build(); 35 | } 36 | 37 | 38 | } 39 | -------------------------------------------------------------------------------- /okhttputils/src/main/java/com/zhy/http/okhttp/builder/PostFormBuilder.java: -------------------------------------------------------------------------------- 1 | package com.zhy.http.okhttp.builder; 2 | 3 | import com.zhy.http.okhttp.request.PostFormRequest; 4 | import com.zhy.http.okhttp.request.RequestCall; 5 | 6 | import java.io.File; 7 | import java.util.ArrayList; 8 | import java.util.LinkedHashMap; 9 | import java.util.List; 10 | import java.util.Map; 11 | 12 | /** 13 | * Created by zhy on 15/12/14. 14 | */ 15 | public class PostFormBuilder extends OkHttpRequestBuilder implements HasParamsable 16 | { 17 | private List files = new ArrayList<>(); 18 | 19 | @Override 20 | public RequestCall build() 21 | { 22 | return new PostFormRequest(url, tag, params, headers, files,id).build(); 23 | } 24 | 25 | public PostFormBuilder files(String key, Map files) 26 | { 27 | for (String filename : files.keySet()) 28 | { 29 | this.files.add(new FileInput(key, filename, files.get(filename))); 30 | } 31 | return this; 32 | } 33 | 34 | public PostFormBuilder addFile(String name, String filename, File file) 35 | { 36 | files.add(new FileInput(name, filename, file)); 37 | return this; 38 | } 39 | 40 | public static class FileInput 41 | { 42 | public String key; 43 | public String filename; 44 | public File file; 45 | 46 | public FileInput(String name, String filename, File file) 47 | { 48 | this.key = name; 49 | this.filename = filename; 50 | this.file = file; 51 | } 52 | 53 | @Override 54 | public String toString() 55 | { 56 | return "FileInput{" + 57 | "key='" + key + '\'' + 58 | ", filename='" + filename + '\'' + 59 | ", file=" + file + 60 | '}'; 61 | } 62 | } 63 | 64 | 65 | 66 | @Override 67 | public PostFormBuilder params(Map params) 68 | { 69 | this.params = params; 70 | return this; 71 | } 72 | 73 | @Override 74 | public PostFormBuilder addParams(String key, String val) 75 | { 76 | if (this.params == null) 77 | { 78 | params = new LinkedHashMap<>(); 79 | } 80 | params.put(key, val); 81 | return this; 82 | } 83 | 84 | 85 | 86 | 87 | } 88 | -------------------------------------------------------------------------------- /okhttputils/src/main/java/com/zhy/http/okhttp/builder/PostStringBuilder.java: -------------------------------------------------------------------------------- 1 | package com.zhy.http.okhttp.builder; 2 | 3 | import com.zhy.http.okhttp.request.PostStringRequest; 4 | import com.zhy.http.okhttp.request.RequestCall; 5 | 6 | import okhttp3.MediaType; 7 | 8 | /** 9 | * Created by zhy on 15/12/14. 10 | */ 11 | public class PostStringBuilder extends OkHttpRequestBuilder 12 | { 13 | private String content; 14 | private MediaType mediaType; 15 | 16 | 17 | public PostStringBuilder content(String content) 18 | { 19 | this.content = content; 20 | return this; 21 | } 22 | 23 | public PostStringBuilder mediaType(MediaType mediaType) 24 | { 25 | this.mediaType = mediaType; 26 | return this; 27 | } 28 | 29 | @Override 30 | public RequestCall build() 31 | { 32 | return new PostStringRequest(url, tag, params, headers, content, mediaType,id).build(); 33 | } 34 | 35 | 36 | } 37 | -------------------------------------------------------------------------------- /okhttputils/src/main/java/com/zhy/http/okhttp/callback/BitmapCallback.java: -------------------------------------------------------------------------------- 1 | package com.zhy.http.okhttp.callback; 2 | 3 | import android.graphics.Bitmap; 4 | import android.graphics.BitmapFactory; 5 | 6 | import okhttp3.Response; 7 | 8 | /** 9 | * Created by zhy on 15/12/14. 10 | */ 11 | public abstract class BitmapCallback extends Callback 12 | { 13 | @Override 14 | public Bitmap parseNetworkResponse(Response response , int id) throws Exception 15 | { 16 | return BitmapFactory.decodeStream(response.body().byteStream()); 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /okhttputils/src/main/java/com/zhy/http/okhttp/callback/Callback.java: -------------------------------------------------------------------------------- 1 | package com.zhy.http.okhttp.callback; 2 | 3 | import okhttp3.Call; 4 | import okhttp3.Request; 5 | import okhttp3.Response; 6 | 7 | public abstract class Callback 8 | { 9 | /** 10 | * UI Thread 11 | * 12 | * @param request 13 | */ 14 | public void onBefore(Request request, int id) 15 | { 16 | } 17 | 18 | /** 19 | * UI Thread 20 | * 21 | * @param 22 | */ 23 | public void onAfter(int id) 24 | { 25 | } 26 | 27 | /** 28 | * UI Thread 29 | * 30 | * @param progress 31 | */ 32 | public void inProgress(float progress, long total , int id) 33 | { 34 | 35 | } 36 | 37 | /** 38 | * if you parse reponse code in parseNetworkResponse, you should make this method return true. 39 | * 40 | * @param response 41 | * @return 42 | */ 43 | public boolean validateReponse(Response response, int id) 44 | { 45 | return response.isSuccessful(); 46 | } 47 | 48 | /** 49 | * Thread Pool Thread 50 | * 51 | * @param response 52 | */ 53 | public abstract T parseNetworkResponse(Response response, int id) throws Exception; 54 | 55 | public abstract void onError(Call call, Exception e, int id); 56 | 57 | public abstract void onResponse(T response, int id); 58 | 59 | 60 | public static Callback CALLBACK_DEFAULT = new Callback() 61 | { 62 | 63 | @Override 64 | public Object parseNetworkResponse(Response response, int id) throws Exception 65 | { 66 | return null; 67 | } 68 | 69 | @Override 70 | public void onError(Call call, Exception e, int id) 71 | { 72 | 73 | } 74 | 75 | @Override 76 | public void onResponse(Object response, int id) 77 | { 78 | 79 | } 80 | }; 81 | 82 | } -------------------------------------------------------------------------------- /okhttputils/src/main/java/com/zhy/http/okhttp/callback/FileCallBack.java: -------------------------------------------------------------------------------- 1 | package com.zhy.http.okhttp.callback; 2 | 3 | import com.zhy.http.okhttp.OkHttpUtils; 4 | 5 | import java.io.File; 6 | import java.io.FileOutputStream; 7 | import java.io.IOException; 8 | import java.io.InputStream; 9 | 10 | import okhttp3.Response; 11 | 12 | /** 13 | * Created by zhy on 15/12/15. 14 | */ 15 | public abstract class FileCallBack extends Callback 16 | { 17 | /** 18 | * 目标文件存储的文件夹路径 19 | */ 20 | private String destFileDir; 21 | /** 22 | * 目标文件存储的文件名 23 | */ 24 | private String destFileName; 25 | 26 | 27 | public FileCallBack(String destFileDir, String destFileName) 28 | { 29 | this.destFileDir = destFileDir; 30 | this.destFileName = destFileName; 31 | } 32 | 33 | 34 | @Override 35 | public File parseNetworkResponse(Response response, int id) throws Exception 36 | { 37 | return saveFile(response,id); 38 | } 39 | 40 | 41 | public File saveFile(Response response,final int id) throws IOException 42 | { 43 | InputStream is = null; 44 | byte[] buf = new byte[2048]; 45 | int len = 0; 46 | FileOutputStream fos = null; 47 | try 48 | { 49 | is = response.body().byteStream(); 50 | final long total = response.body().contentLength(); 51 | 52 | long sum = 0; 53 | 54 | File dir = new File(destFileDir); 55 | if (!dir.exists()) 56 | { 57 | dir.mkdirs(); 58 | } 59 | File file = new File(dir, destFileName); 60 | fos = new FileOutputStream(file); 61 | while ((len = is.read(buf)) != -1) 62 | { 63 | sum += len; 64 | fos.write(buf, 0, len); 65 | final long finalSum = sum; 66 | OkHttpUtils.getInstance().getDelivery().execute(new Runnable() 67 | { 68 | @Override 69 | public void run() 70 | { 71 | 72 | inProgress(finalSum * 1.0f / total,total,id); 73 | } 74 | }); 75 | } 76 | fos.flush(); 77 | 78 | return file; 79 | 80 | } finally 81 | { 82 | try 83 | { 84 | response.body().close(); 85 | if (is != null) is.close(); 86 | } catch (IOException e) 87 | { 88 | } 89 | try 90 | { 91 | if (fos != null) fos.close(); 92 | } catch (IOException e) 93 | { 94 | } 95 | 96 | } 97 | } 98 | 99 | 100 | } 101 | -------------------------------------------------------------------------------- /okhttputils/src/main/java/com/zhy/http/okhttp/callback/GenericsCallback.java: -------------------------------------------------------------------------------- 1 | package com.zhy.http.okhttp.callback; 2 | 3 | import java.io.IOException; 4 | import java.lang.reflect.ParameterizedType; 5 | 6 | import okhttp3.Response; 7 | 8 | /** 9 | * Created by JimGong on 2016/6/23. 10 | */ 11 | 12 | public abstract class GenericsCallback extends Callback { 13 | IGenericsSerializator mGenericsSerializator; 14 | 15 | public GenericsCallback(IGenericsSerializator serializator) { 16 | mGenericsSerializator = serializator; 17 | } 18 | 19 | @Override 20 | public T parseNetworkResponse(Response response, int id) throws IOException { 21 | String string = response.body().string(); 22 | Class entityClass = (Class) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]; 23 | if (entityClass == String.class) { 24 | return (T) string; 25 | } 26 | T bean = mGenericsSerializator.transform(string, entityClass); 27 | return bean; 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /okhttputils/src/main/java/com/zhy/http/okhttp/callback/IGenericsSerializator.java: -------------------------------------------------------------------------------- 1 | package com.zhy.http.okhttp.callback; 2 | 3 | /** 4 | * Created by JimGong on 2016/6/23. 5 | */ 6 | public interface IGenericsSerializator { 7 | T transform(String response, Class classOfT); 8 | } 9 | -------------------------------------------------------------------------------- /okhttputils/src/main/java/com/zhy/http/okhttp/callback/StringCallback.java: -------------------------------------------------------------------------------- 1 | package com.zhy.http.okhttp.callback; 2 | 3 | import java.io.IOException; 4 | 5 | import okhttp3.Response; 6 | 7 | /** 8 | * Created by zhy on 15/12/14. 9 | */ 10 | public abstract class StringCallback extends Callback 11 | { 12 | @Override 13 | public String parseNetworkResponse(Response response, int id) throws IOException 14 | { 15 | return response.body().string(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /okhttputils/src/main/java/com/zhy/http/okhttp/cookie/CookieJarImpl.java: -------------------------------------------------------------------------------- 1 | package com.zhy.http.okhttp.cookie; 2 | 3 | import com.zhy.http.okhttp.cookie.store.CookieStore; 4 | import com.zhy.http.okhttp.utils.Exceptions; 5 | 6 | import java.util.List; 7 | 8 | import okhttp3.Cookie; 9 | import okhttp3.CookieJar; 10 | import okhttp3.HttpUrl; 11 | 12 | /** 13 | * Created by zhy on 16/3/10. 14 | */ 15 | public class CookieJarImpl implements CookieJar 16 | { 17 | private CookieStore cookieStore; 18 | 19 | public CookieJarImpl(CookieStore cookieStore) 20 | { 21 | if (cookieStore == null) Exceptions.illegalArgument("cookieStore can not be null."); 22 | this.cookieStore = cookieStore; 23 | } 24 | 25 | @Override 26 | public synchronized void saveFromResponse(HttpUrl url, List cookies) 27 | { 28 | cookieStore.add(url, cookies); 29 | } 30 | 31 | @Override 32 | public synchronized List loadForRequest(HttpUrl url) 33 | { 34 | return cookieStore.get(url); 35 | } 36 | 37 | public CookieStore getCookieStore() 38 | { 39 | return cookieStore; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /okhttputils/src/main/java/com/zhy/http/okhttp/cookie/store/CookieStore.java: -------------------------------------------------------------------------------- 1 | package com.zhy.http.okhttp.cookie.store; 2 | 3 | import java.util.List; 4 | 5 | import okhttp3.Cookie; 6 | import okhttp3.HttpUrl; 7 | 8 | public interface CookieStore 9 | { 10 | 11 | void add(HttpUrl uri, List cookie); 12 | 13 | List get(HttpUrl uri); 14 | 15 | List getCookies(); 16 | 17 | boolean remove(HttpUrl uri, Cookie cookie); 18 | 19 | boolean removeAll(); 20 | 21 | } 22 | -------------------------------------------------------------------------------- /okhttputils/src/main/java/com/zhy/http/okhttp/cookie/store/HasCookieStore.java: -------------------------------------------------------------------------------- 1 | package com.zhy.http.okhttp.cookie.store; 2 | 3 | /** 4 | * Created by zhy on 16/3/10. 5 | */ 6 | public interface HasCookieStore 7 | { 8 | CookieStore getCookieStore(); 9 | } 10 | -------------------------------------------------------------------------------- /okhttputils/src/main/java/com/zhy/http/okhttp/cookie/store/MemoryCookieStore.java: -------------------------------------------------------------------------------- 1 | package com.zhy.http.okhttp.cookie.store; 2 | 3 | import java.util.ArrayList; 4 | import java.util.HashMap; 5 | import java.util.Iterator; 6 | import java.util.List; 7 | import java.util.Set; 8 | 9 | import okhttp3.Cookie; 10 | import okhttp3.HttpUrl; 11 | 12 | /** 13 | * Created by zhy on 16/3/10. 14 | */ 15 | public class MemoryCookieStore implements CookieStore 16 | { 17 | private final HashMap> allCookies = new HashMap<>(); 18 | 19 | @Override 20 | public void add(HttpUrl url, List cookies) 21 | { 22 | List oldCookies = allCookies.get(url.host()); 23 | 24 | if (oldCookies != null) 25 | { 26 | Iterator itNew = cookies.iterator(); 27 | Iterator itOld = oldCookies.iterator(); 28 | while (itNew.hasNext()) 29 | { 30 | String va = itNew.next().name(); 31 | while (va != null && itOld.hasNext()) 32 | { 33 | String v = itOld.next().name(); 34 | if (v != null && va.equals(v)) 35 | { 36 | itOld.remove(); 37 | } 38 | } 39 | } 40 | oldCookies.addAll(cookies); 41 | } else 42 | { 43 | allCookies.put(url.host(), cookies); 44 | } 45 | 46 | 47 | } 48 | 49 | @Override 50 | public List get(HttpUrl uri) 51 | { 52 | List cookies = allCookies.get(uri.host()); 53 | if (cookies == null) 54 | { 55 | cookies = new ArrayList<>(); 56 | allCookies.put(uri.host(), cookies); 57 | } 58 | return cookies; 59 | 60 | } 61 | 62 | @Override 63 | public boolean removeAll() 64 | { 65 | allCookies.clear(); 66 | return true; 67 | } 68 | 69 | @Override 70 | public List getCookies() 71 | { 72 | List cookies = new ArrayList<>(); 73 | Set httpUrls = allCookies.keySet(); 74 | for (String url : httpUrls) 75 | { 76 | cookies.addAll(allCookies.get(url)); 77 | } 78 | return cookies; 79 | } 80 | 81 | 82 | @Override 83 | public boolean remove(HttpUrl uri, Cookie cookie) 84 | { 85 | List cookies = allCookies.get(uri.host()); 86 | if (cookie != null) 87 | { 88 | return cookies.remove(cookie); 89 | } 90 | return false; 91 | } 92 | 93 | 94 | } 95 | -------------------------------------------------------------------------------- /okhttputils/src/main/java/com/zhy/http/okhttp/cookie/store/PersistentCookieStore.java: -------------------------------------------------------------------------------- 1 | package com.zhy.http.okhttp.cookie.store; 2 | 3 | import android.content.Context; 4 | import android.content.SharedPreferences; 5 | import android.text.TextUtils; 6 | import android.util.Log; 7 | 8 | import java.io.ByteArrayInputStream; 9 | import java.io.ByteArrayOutputStream; 10 | import java.io.IOException; 11 | import java.io.ObjectInputStream; 12 | import java.io.ObjectOutputStream; 13 | import java.util.ArrayList; 14 | import java.util.Collection; 15 | import java.util.HashMap; 16 | import java.util.List; 17 | import java.util.Locale; 18 | import java.util.Map; 19 | import java.util.concurrent.ConcurrentHashMap; 20 | 21 | import okhttp3.Cookie; 22 | import okhttp3.HttpUrl; 23 | 24 | /** 25 | *
 26 |  *     OkHttpClient client = new OkHttpClient.Builder()
 27 |  *             .cookieJar(new JavaNetCookieJar(new CookieManager(
 28 |  *                     new PersistentCookieStore(getApplicationContext()),
 29 |  *                             CookiePolicy.ACCEPT_ALL))
 30 |  *             .build();
 31 |  *
 32 |  * 
33 | *

34 | * from http://stackoverflow.com/questions/25461792/persistent-cookie-store-using-okhttp-2-on-android 35 | *

36 | *
37 | * A persistent cookie store which implements the Apache HttpClient CookieStore interface. 38 | * Cookies are stored and will persist on the user's device between application sessions since they 39 | * are serialized and stored in SharedPreferences. Instances of this class are 40 | * designed to be used with AsyncHttpClient#setCookieStore, but can also be used with a 41 | * regular old apache HttpClient/HttpContext if you prefer. 42 | */ 43 | public class PersistentCookieStore implements CookieStore 44 | { 45 | 46 | private static final String LOG_TAG = "PersistentCookieStore"; 47 | private static final String COOKIE_PREFS = "CookiePrefsFile"; 48 | private static final String COOKIE_NAME_PREFIX = "cookie_"; 49 | 50 | private final HashMap> cookies; 51 | private final SharedPreferences cookiePrefs; 52 | 53 | /** 54 | * Construct a persistent cookie store. 55 | * 56 | * @param context Context to attach cookie store to 57 | */ 58 | public PersistentCookieStore(Context context) 59 | { 60 | cookiePrefs = context.getSharedPreferences(COOKIE_PREFS, 0); 61 | cookies = new HashMap>(); 62 | 63 | // Load any previously stored cookies into the store 64 | Map prefsMap = cookiePrefs.getAll(); 65 | for (Map.Entry entry : prefsMap.entrySet()) 66 | { 67 | if (((String) entry.getValue()) != null && !((String) entry.getValue()).startsWith(COOKIE_NAME_PREFIX)) 68 | { 69 | String[] cookieNames = TextUtils.split((String) entry.getValue(), ","); 70 | for (String name : cookieNames) 71 | { 72 | String encodedCookie = cookiePrefs.getString(COOKIE_NAME_PREFIX + name, null); 73 | if (encodedCookie != null) 74 | { 75 | Cookie decodedCookie = decodeCookie(encodedCookie); 76 | if (decodedCookie != null) 77 | { 78 | if (!cookies.containsKey(entry.getKey())) 79 | cookies.put(entry.getKey(), new ConcurrentHashMap()); 80 | cookies.get(entry.getKey()).put(name, decodedCookie); 81 | } 82 | } 83 | } 84 | 85 | } 86 | } 87 | } 88 | 89 | protected void add(HttpUrl uri, Cookie cookie) 90 | { 91 | String name = getCookieToken(cookie); 92 | 93 | if (cookie.persistent()) 94 | { 95 | if (!cookies.containsKey(uri.host())) 96 | { 97 | cookies.put(uri.host(), new ConcurrentHashMap()); 98 | } 99 | cookies.get(uri.host()).put(name, cookie); 100 | } else 101 | { 102 | if (cookies.containsKey(uri.host())) 103 | { 104 | cookies.get(uri.host()).remove(name); 105 | }else 106 | { 107 | return ; 108 | } 109 | } 110 | 111 | // Save cookie into persistent store 112 | SharedPreferences.Editor prefsWriter = cookiePrefs.edit(); 113 | prefsWriter.putString(uri.host(), TextUtils.join(",", cookies.get(uri.host()).keySet())); 114 | prefsWriter.putString(COOKIE_NAME_PREFIX + name, encodeCookie(new SerializableHttpCookie(cookie))); 115 | prefsWriter.apply(); 116 | } 117 | 118 | protected String getCookieToken(Cookie cookie) 119 | { 120 | return cookie.name() + cookie.domain(); 121 | } 122 | 123 | @Override 124 | public void add(HttpUrl uri, List cookies) 125 | { 126 | for (Cookie cookie : cookies) 127 | { 128 | add(uri, cookie); 129 | } 130 | } 131 | 132 | @Override 133 | public List get(HttpUrl uri) 134 | { 135 | ArrayList ret = new ArrayList(); 136 | if (cookies.containsKey(uri.host())) 137 | { 138 | Collection cookies = this.cookies.get(uri.host()).values(); 139 | for (Cookie cookie : cookies) 140 | { 141 | if (isCookieExpired(cookie)) 142 | { 143 | remove(uri, cookie); 144 | } else 145 | { 146 | ret.add(cookie); 147 | } 148 | } 149 | } 150 | 151 | return ret; 152 | } 153 | 154 | private static boolean isCookieExpired(Cookie cookie) 155 | { 156 | return cookie.expiresAt() < System.currentTimeMillis(); 157 | } 158 | 159 | @Override 160 | public boolean removeAll() 161 | { 162 | SharedPreferences.Editor prefsWriter = cookiePrefs.edit(); 163 | prefsWriter.clear(); 164 | prefsWriter.apply(); 165 | cookies.clear(); 166 | return true; 167 | } 168 | 169 | 170 | @Override 171 | public boolean remove(HttpUrl uri, Cookie cookie) 172 | { 173 | String name = getCookieToken(cookie); 174 | 175 | if (cookies.containsKey(uri.host()) && cookies.get(uri.host()).containsKey(name)) 176 | { 177 | cookies.get(uri.host()).remove(name); 178 | 179 | SharedPreferences.Editor prefsWriter = cookiePrefs.edit(); 180 | if (cookiePrefs.contains(COOKIE_NAME_PREFIX + name)) 181 | { 182 | prefsWriter.remove(COOKIE_NAME_PREFIX + name); 183 | } 184 | prefsWriter.putString(uri.host(), TextUtils.join(",", cookies.get(uri.host()).keySet())); 185 | prefsWriter.apply(); 186 | 187 | return true; 188 | } else 189 | { 190 | return false; 191 | } 192 | } 193 | 194 | @Override 195 | public List getCookies() 196 | { 197 | ArrayList ret = new ArrayList(); 198 | for (String key : cookies.keySet()) 199 | ret.addAll(cookies.get(key).values()); 200 | 201 | return ret; 202 | } 203 | 204 | 205 | protected String encodeCookie(SerializableHttpCookie cookie) 206 | { 207 | if (cookie == null) 208 | return null; 209 | ByteArrayOutputStream os = new ByteArrayOutputStream(); 210 | try 211 | { 212 | ObjectOutputStream outputStream = new ObjectOutputStream(os); 213 | outputStream.writeObject(cookie); 214 | } catch (IOException e) 215 | { 216 | Log.d(LOG_TAG, "IOException in encodeCookie", e); 217 | return null; 218 | } 219 | 220 | return byteArrayToHexString(os.toByteArray()); 221 | } 222 | 223 | protected Cookie decodeCookie(String cookieString) 224 | { 225 | byte[] bytes = hexStringToByteArray(cookieString); 226 | ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); 227 | Cookie cookie = null; 228 | try 229 | { 230 | ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); 231 | cookie = ((SerializableHttpCookie) objectInputStream.readObject()).getCookie(); 232 | } catch (IOException e) 233 | { 234 | Log.d(LOG_TAG, "IOException in decodeCookie", e); 235 | } catch (ClassNotFoundException e) 236 | { 237 | Log.d(LOG_TAG, "ClassNotFoundException in decodeCookie", e); 238 | } 239 | 240 | return cookie; 241 | } 242 | 243 | /** 244 | * Using some super basic byte array <-> hex conversions so we don't have to rely on any 245 | * large Base64 libraries. Can be overridden if you like! 246 | * 247 | * @param bytes byte array to be converted 248 | * @return string containing hex values 249 | */ 250 | protected String byteArrayToHexString(byte[] bytes) 251 | { 252 | StringBuilder sb = new StringBuilder(bytes.length * 2); 253 | for (byte element : bytes) 254 | { 255 | int v = element & 0xff; 256 | if (v < 16) 257 | { 258 | sb.append('0'); 259 | } 260 | sb.append(Integer.toHexString(v)); 261 | } 262 | return sb.toString().toUpperCase(Locale.US); 263 | } 264 | 265 | /** 266 | * Converts hex values from strings to byte arra 267 | * 268 | * @param hexString string of hex-encoded values 269 | * @return decoded byte array 270 | */ 271 | protected byte[] hexStringToByteArray(String hexString) 272 | { 273 | int len = hexString.length(); 274 | byte[] data = new byte[len / 2]; 275 | for (int i = 0; i < len; i += 2) 276 | { 277 | data[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character.digit(hexString.charAt(i + 1), 16)); 278 | } 279 | return data; 280 | } 281 | } 282 | -------------------------------------------------------------------------------- /okhttputils/src/main/java/com/zhy/http/okhttp/cookie/store/SerializableHttpCookie.java: -------------------------------------------------------------------------------- 1 | package com.zhy.http.okhttp.cookie.store; 2 | 3 | import java.io.IOException; 4 | import java.io.ObjectInputStream; 5 | import java.io.ObjectOutputStream; 6 | import java.io.Serializable; 7 | 8 | import okhttp3.Cookie; 9 | 10 | /** 11 | * from http://stackoverflow.com/questions/25461792/persistent-cookie-store-using-okhttp-2-on-android 12 | * and
13 | * 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 14 | */ 15 | 16 | public class SerializableHttpCookie implements Serializable 17 | { 18 | private static final long serialVersionUID = 6374381323722046732L; 19 | 20 | private transient final Cookie cookie; 21 | private transient Cookie clientCookie; 22 | 23 | public SerializableHttpCookie(Cookie cookie) 24 | { 25 | this.cookie = cookie; 26 | } 27 | 28 | public Cookie getCookie() 29 | { 30 | Cookie bestCookie = cookie; 31 | if (clientCookie != null) 32 | { 33 | bestCookie = clientCookie; 34 | } 35 | 36 | return bestCookie; 37 | } 38 | 39 | private void writeObject(ObjectOutputStream out) throws IOException 40 | { 41 | out.writeObject(cookie.name()); 42 | out.writeObject(cookie.value()); 43 | out.writeLong(cookie.expiresAt()); 44 | out.writeObject(cookie.domain()); 45 | out.writeObject(cookie.path()); 46 | out.writeBoolean(cookie.secure()); 47 | out.writeBoolean(cookie.httpOnly()); 48 | out.writeBoolean(cookie.hostOnly()); 49 | out.writeBoolean(cookie.persistent()); 50 | } 51 | 52 | private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException 53 | { 54 | String name = (String) in.readObject(); 55 | String value = (String) in.readObject(); 56 | long expiresAt = in.readLong(); 57 | String domain = (String) in.readObject(); 58 | String path = (String) in.readObject(); 59 | boolean secure = in.readBoolean(); 60 | boolean httpOnly = in.readBoolean(); 61 | boolean hostOnly = in.readBoolean(); 62 | boolean persistent = in.readBoolean(); 63 | Cookie.Builder builder = new Cookie.Builder(); 64 | builder = builder.name(name); 65 | builder = builder.value(value); 66 | builder = builder.expiresAt(expiresAt); 67 | builder = hostOnly ? builder.hostOnlyDomain(domain) : builder.domain(domain); 68 | builder = builder.path(path); 69 | builder = secure ? builder.secure() : builder; 70 | builder = httpOnly ? builder.httpOnly() : builder; 71 | clientCookie = builder.build(); 72 | 73 | } 74 | } -------------------------------------------------------------------------------- /okhttputils/src/main/java/com/zhy/http/okhttp/https/HttpsUtils.java: -------------------------------------------------------------------------------- 1 | package com.zhy.http.okhttp.https; 2 | 3 | import java.io.IOException; 4 | import java.io.InputStream; 5 | import java.security.KeyManagementException; 6 | import java.security.KeyStore; 7 | import java.security.KeyStoreException; 8 | import java.security.NoSuchAlgorithmException; 9 | import java.security.UnrecoverableKeyException; 10 | import java.security.cert.CertificateException; 11 | import java.security.cert.CertificateFactory; 12 | import java.security.cert.X509Certificate; 13 | 14 | import javax.net.ssl.HostnameVerifier; 15 | import javax.net.ssl.KeyManager; 16 | import javax.net.ssl.KeyManagerFactory; 17 | import javax.net.ssl.SSLContext; 18 | import javax.net.ssl.SSLSession; 19 | import javax.net.ssl.SSLSocketFactory; 20 | import javax.net.ssl.TrustManager; 21 | import javax.net.ssl.TrustManagerFactory; 22 | import javax.net.ssl.X509TrustManager; 23 | 24 | /** 25 | * Created by zhy on 15/12/14. 26 | */ 27 | public class HttpsUtils 28 | { 29 | public static class SSLParams 30 | { 31 | public SSLSocketFactory sSLSocketFactory; 32 | public X509TrustManager trustManager; 33 | } 34 | 35 | public static SSLParams getSslSocketFactory(InputStream[] certificates, InputStream bksFile, String password) 36 | { 37 | SSLParams sslParams = new SSLParams(); 38 | try 39 | { 40 | TrustManager[] trustManagers = prepareTrustManager(certificates); 41 | KeyManager[] keyManagers = prepareKeyManager(bksFile, password); 42 | SSLContext sslContext = SSLContext.getInstance("TLS"); 43 | X509TrustManager trustManager = null; 44 | if (trustManagers != null) 45 | { 46 | trustManager = new MyTrustManager(chooseTrustManager(trustManagers)); 47 | } else 48 | { 49 | trustManager = new UnSafeTrustManager(); 50 | } 51 | sslContext.init(keyManagers, new TrustManager[]{trustManager},null); 52 | sslParams.sSLSocketFactory = sslContext.getSocketFactory(); 53 | sslParams.trustManager = trustManager; 54 | return sslParams; 55 | } catch (NoSuchAlgorithmException e) 56 | { 57 | throw new AssertionError(e); 58 | } catch (KeyManagementException e) 59 | { 60 | throw new AssertionError(e); 61 | } catch (KeyStoreException e) 62 | { 63 | throw new AssertionError(e); 64 | } 65 | } 66 | 67 | private class UnSafeHostnameVerifier implements HostnameVerifier 68 | { 69 | @Override 70 | public boolean verify(String hostname, SSLSession session) 71 | { 72 | return true; 73 | } 74 | } 75 | 76 | private static class UnSafeTrustManager implements X509TrustManager 77 | { 78 | @Override 79 | public void checkClientTrusted(X509Certificate[] chain, String authType) 80 | throws CertificateException 81 | { 82 | } 83 | 84 | @Override 85 | public void checkServerTrusted(X509Certificate[] chain, String authType) 86 | throws CertificateException 87 | { 88 | } 89 | 90 | @Override 91 | public X509Certificate[] getAcceptedIssuers() 92 | { 93 | return new java.security.cert.X509Certificate[]{}; 94 | } 95 | } 96 | 97 | private static TrustManager[] prepareTrustManager(InputStream... certificates) 98 | { 99 | if (certificates == null || certificates.length <= 0) return null; 100 | try 101 | { 102 | 103 | CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); 104 | KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); 105 | keyStore.load(null); 106 | int index = 0; 107 | for (InputStream certificate : certificates) 108 | { 109 | String certificateAlias = Integer.toString(index++); 110 | keyStore.setCertificateEntry(certificateAlias, certificateFactory.generateCertificate(certificate)); 111 | try 112 | { 113 | if (certificate != null) 114 | certificate.close(); 115 | } catch (IOException e) 116 | 117 | { 118 | } 119 | } 120 | TrustManagerFactory trustManagerFactory = null; 121 | 122 | trustManagerFactory = TrustManagerFactory. 123 | getInstance(TrustManagerFactory.getDefaultAlgorithm()); 124 | trustManagerFactory.init(keyStore); 125 | 126 | TrustManager[] trustManagers = trustManagerFactory.getTrustManagers(); 127 | 128 | return trustManagers; 129 | } catch (NoSuchAlgorithmException e) 130 | { 131 | e.printStackTrace(); 132 | } catch (CertificateException e) 133 | { 134 | e.printStackTrace(); 135 | } catch (KeyStoreException e) 136 | { 137 | e.printStackTrace(); 138 | } catch (Exception e) 139 | { 140 | e.printStackTrace(); 141 | } 142 | return null; 143 | 144 | } 145 | 146 | private static KeyManager[] prepareKeyManager(InputStream bksFile, String password) 147 | { 148 | try 149 | { 150 | if (bksFile == null || password == null) return null; 151 | 152 | KeyStore clientKeyStore = KeyStore.getInstance("BKS"); 153 | clientKeyStore.load(bksFile, password.toCharArray()); 154 | KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); 155 | keyManagerFactory.init(clientKeyStore, password.toCharArray()); 156 | return keyManagerFactory.getKeyManagers(); 157 | 158 | } catch (KeyStoreException e) 159 | { 160 | e.printStackTrace(); 161 | } catch (NoSuchAlgorithmException e) 162 | { 163 | e.printStackTrace(); 164 | } catch (UnrecoverableKeyException e) 165 | { 166 | e.printStackTrace(); 167 | } catch (CertificateException e) 168 | { 169 | e.printStackTrace(); 170 | } catch (IOException e) 171 | { 172 | e.printStackTrace(); 173 | } catch (Exception e) 174 | { 175 | e.printStackTrace(); 176 | } 177 | return null; 178 | } 179 | 180 | private static X509TrustManager chooseTrustManager(TrustManager[] trustManagers) 181 | { 182 | for (TrustManager trustManager : trustManagers) 183 | { 184 | if (trustManager instanceof X509TrustManager) 185 | { 186 | return (X509TrustManager) trustManager; 187 | } 188 | } 189 | return null; 190 | } 191 | 192 | 193 | private static class MyTrustManager implements X509TrustManager 194 | { 195 | private X509TrustManager defaultTrustManager; 196 | private X509TrustManager localTrustManager; 197 | 198 | public MyTrustManager(X509TrustManager localTrustManager) throws NoSuchAlgorithmException, KeyStoreException 199 | { 200 | TrustManagerFactory var4 = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); 201 | var4.init((KeyStore) null); 202 | defaultTrustManager = chooseTrustManager(var4.getTrustManagers()); 203 | this.localTrustManager = localTrustManager; 204 | } 205 | 206 | 207 | @Override 208 | public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException 209 | { 210 | 211 | } 212 | 213 | @Override 214 | public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException 215 | { 216 | try 217 | { 218 | defaultTrustManager.checkServerTrusted(chain, authType); 219 | } catch (CertificateException ce) 220 | { 221 | localTrustManager.checkServerTrusted(chain, authType); 222 | } 223 | } 224 | 225 | 226 | @Override 227 | public X509Certificate[] getAcceptedIssuers() 228 | { 229 | return new X509Certificate[0]; 230 | } 231 | } 232 | } 233 | -------------------------------------------------------------------------------- /okhttputils/src/main/java/com/zhy/http/okhttp/log/LoggerInterceptor.java: -------------------------------------------------------------------------------- 1 | package com.zhy.http.okhttp.log; 2 | 3 | import android.text.TextUtils; 4 | import android.util.Log; 5 | 6 | import java.io.IOException; 7 | 8 | import okhttp3.Headers; 9 | import okhttp3.Interceptor; 10 | import okhttp3.MediaType; 11 | import okhttp3.Request; 12 | import okhttp3.RequestBody; 13 | import okhttp3.Response; 14 | import okhttp3.ResponseBody; 15 | import okio.Buffer; 16 | 17 | /** 18 | * Created by zhy on 16/3/1. 19 | */ 20 | public class LoggerInterceptor implements Interceptor 21 | { 22 | public static final String TAG = "OkHttpUtils"; 23 | private String tag; 24 | private boolean showResponse; 25 | 26 | public LoggerInterceptor(String tag, boolean showResponse) 27 | { 28 | if (TextUtils.isEmpty(tag)) 29 | { 30 | tag = TAG; 31 | } 32 | this.showResponse = showResponse; 33 | this.tag = tag; 34 | } 35 | 36 | public LoggerInterceptor(String tag) 37 | { 38 | this(tag, false); 39 | } 40 | 41 | @Override 42 | public Response intercept(Chain chain) throws IOException 43 | { 44 | Request request = chain.request(); 45 | logForRequest(request); 46 | Response response = chain.proceed(request); 47 | return logForResponse(response); 48 | } 49 | 50 | private Response logForResponse(Response response) 51 | { 52 | try 53 | { 54 | //===>response log 55 | Log.e(tag, "========response'log======="); 56 | Response.Builder builder = response.newBuilder(); 57 | Response clone = builder.build(); 58 | Log.e(tag, "url : " + clone.request().url()); 59 | Log.e(tag, "code : " + clone.code()); 60 | Log.e(tag, "protocol : " + clone.protocol()); 61 | if (!TextUtils.isEmpty(clone.message())) 62 | Log.e(tag, "message : " + clone.message()); 63 | 64 | if (showResponse) 65 | { 66 | ResponseBody body = clone.body(); 67 | if (body != null) 68 | { 69 | MediaType mediaType = body.contentType(); 70 | if (mediaType != null) 71 | { 72 | Log.e(tag, "responseBody's contentType : " + mediaType.toString()); 73 | if (isText(mediaType)) 74 | { 75 | String resp = body.string(); 76 | Log.e(tag, "responseBody's content : " + resp); 77 | 78 | body = ResponseBody.create(mediaType, resp); 79 | return response.newBuilder().body(body).build(); 80 | } else 81 | { 82 | Log.e(tag, "responseBody's content : " + " maybe [file part] , too large too print , ignored!"); 83 | } 84 | } 85 | } 86 | } 87 | 88 | Log.e(tag, "========response'log=======end"); 89 | } catch (Exception e) 90 | { 91 | // e.printStackTrace(); 92 | } 93 | 94 | return response; 95 | } 96 | 97 | private void logForRequest(Request request) 98 | { 99 | try 100 | { 101 | String url = request.url().toString(); 102 | Headers headers = request.headers(); 103 | 104 | Log.e(tag, "========request'log======="); 105 | Log.e(tag, "method : " + request.method()); 106 | Log.e(tag, "url : " + url); 107 | if (headers != null && headers.size() > 0) 108 | { 109 | Log.e(tag, "headers : " + headers.toString()); 110 | } 111 | RequestBody requestBody = request.body(); 112 | if (requestBody != null) 113 | { 114 | MediaType mediaType = requestBody.contentType(); 115 | if (mediaType != null) 116 | { 117 | Log.e(tag, "requestBody's contentType : " + mediaType.toString()); 118 | if (isText(mediaType)) 119 | { 120 | Log.e(tag, "requestBody's content : " + bodyToString(request)); 121 | } else 122 | { 123 | Log.e(tag, "requestBody's content : " + " maybe [file part] , too large too print , ignored!"); 124 | } 125 | } 126 | } 127 | Log.e(tag, "========request'log=======end"); 128 | } catch (Exception e) 129 | { 130 | // e.printStackTrace(); 131 | } 132 | } 133 | 134 | private boolean isText(MediaType mediaType) 135 | { 136 | if (mediaType.type() != null && mediaType.type().equals("text")) 137 | { 138 | return true; 139 | } 140 | if (mediaType.subtype() != null) 141 | { 142 | if (mediaType.subtype().equals("json") || 143 | mediaType.subtype().equals("xml") || 144 | mediaType.subtype().equals("html") || 145 | mediaType.subtype().equals("webviewhtml") 146 | ) 147 | return true; 148 | } 149 | return false; 150 | } 151 | 152 | private String bodyToString(final Request request) 153 | { 154 | try 155 | { 156 | final Request copy = request.newBuilder().build(); 157 | final Buffer buffer = new Buffer(); 158 | copy.body().writeTo(buffer); 159 | return buffer.readUtf8(); 160 | } catch (final IOException e) 161 | { 162 | return "something error when show requestBody."; 163 | } 164 | } 165 | } 166 | -------------------------------------------------------------------------------- /okhttputils/src/main/java/com/zhy/http/okhttp/request/CountingRequestBody.java: -------------------------------------------------------------------------------- 1 | package com.zhy.http.okhttp.request; 2 | 3 | import okhttp3.MediaType; 4 | import okhttp3.RequestBody; 5 | 6 | import java.io.IOException; 7 | 8 | import okio.Buffer; 9 | import okio.BufferedSink; 10 | import okio.ForwardingSink; 11 | import okio.Okio; 12 | import okio.Sink; 13 | 14 | /** 15 | * Decorates an OkHttp request body to count the number of bytes written when writing it. Can 16 | * decorate any request body, but is most useful for tracking the upload progress of large 17 | * multipart requests. 18 | * 19 | * @author Leo Nikkilä 20 | */ 21 | public class CountingRequestBody extends RequestBody 22 | { 23 | 24 | protected RequestBody delegate; 25 | protected Listener listener; 26 | 27 | protected CountingSink countingSink; 28 | 29 | public CountingRequestBody(RequestBody delegate, Listener listener) 30 | { 31 | this.delegate = delegate; 32 | this.listener = listener; 33 | } 34 | 35 | @Override 36 | public MediaType contentType() 37 | { 38 | return delegate.contentType(); 39 | } 40 | 41 | @Override 42 | public long contentLength() 43 | { 44 | try 45 | { 46 | return delegate.contentLength(); 47 | } catch (IOException e) 48 | { 49 | e.printStackTrace(); 50 | } 51 | return -1; 52 | } 53 | 54 | @Override 55 | public void writeTo(BufferedSink sink) throws IOException 56 | { 57 | 58 | countingSink = new CountingSink(sink); 59 | BufferedSink bufferedSink = Okio.buffer(countingSink); 60 | 61 | delegate.writeTo(bufferedSink); 62 | 63 | bufferedSink.flush(); 64 | } 65 | 66 | protected final class CountingSink extends ForwardingSink 67 | { 68 | 69 | private long bytesWritten = 0; 70 | 71 | public CountingSink(Sink delegate) 72 | { 73 | super(delegate); 74 | } 75 | 76 | @Override 77 | public void write(Buffer source, long byteCount) throws IOException 78 | { 79 | super.write(source, byteCount); 80 | 81 | bytesWritten += byteCount; 82 | listener.onRequestProgress(bytesWritten, contentLength()); 83 | } 84 | 85 | } 86 | 87 | public static interface Listener 88 | { 89 | public void onRequestProgress(long bytesWritten, long contentLength); 90 | } 91 | 92 | } -------------------------------------------------------------------------------- /okhttputils/src/main/java/com/zhy/http/okhttp/request/GetRequest.java: -------------------------------------------------------------------------------- 1 | package com.zhy.http.okhttp.request; 2 | 3 | import java.util.Map; 4 | 5 | import okhttp3.Request; 6 | import okhttp3.RequestBody; 7 | 8 | /** 9 | * Created by zhy on 15/12/14. 10 | */ 11 | public class GetRequest extends OkHttpRequest 12 | { 13 | public GetRequest(String url, Object tag, Map params, Map headers,int id) 14 | { 15 | super(url, tag, params, headers,id); 16 | } 17 | 18 | @Override 19 | protected RequestBody buildRequestBody() 20 | { 21 | return null; 22 | } 23 | 24 | @Override 25 | protected Request buildRequest(RequestBody requestBody) 26 | { 27 | return builder.get().build(); 28 | } 29 | 30 | 31 | } 32 | -------------------------------------------------------------------------------- /okhttputils/src/main/java/com/zhy/http/okhttp/request/OkHttpRequest.java: -------------------------------------------------------------------------------- 1 | package com.zhy.http.okhttp.request; 2 | 3 | import com.zhy.http.okhttp.callback.Callback; 4 | import com.zhy.http.okhttp.utils.Exceptions; 5 | 6 | import java.util.Map; 7 | 8 | import okhttp3.Headers; 9 | import okhttp3.Request; 10 | import okhttp3.RequestBody; 11 | 12 | /** 13 | * Created by zhy on 15/11/6. 14 | */ 15 | public abstract class OkHttpRequest 16 | { 17 | protected String url; 18 | protected Object tag; 19 | protected Map params; 20 | protected Map headers; 21 | protected int id; 22 | 23 | protected Request.Builder builder = new Request.Builder(); 24 | 25 | protected OkHttpRequest(String url, Object tag, 26 | Map params, Map headers,int id) 27 | { 28 | this.url = url; 29 | this.tag = tag; 30 | this.params = params; 31 | this.headers = headers; 32 | this.id = id ; 33 | 34 | if (url == null) 35 | { 36 | Exceptions.illegalArgument("url can not be null."); 37 | } 38 | 39 | initBuilder(); 40 | } 41 | 42 | 43 | 44 | /** 45 | * 初始化一些基本参数 url , tag , headers 46 | */ 47 | private void initBuilder() 48 | { 49 | builder.url(url).tag(tag); 50 | appendHeaders(); 51 | } 52 | 53 | protected abstract RequestBody buildRequestBody(); 54 | 55 | protected RequestBody wrapRequestBody(RequestBody requestBody, final Callback callback) 56 | { 57 | return requestBody; 58 | } 59 | 60 | protected abstract Request buildRequest(RequestBody requestBody); 61 | 62 | public RequestCall build() 63 | { 64 | return new RequestCall(this); 65 | } 66 | 67 | 68 | public Request generateRequest(Callback callback) 69 | { 70 | RequestBody requestBody = buildRequestBody(); 71 | RequestBody wrappedRequestBody = wrapRequestBody(requestBody, callback); 72 | Request request = buildRequest(wrappedRequestBody); 73 | return request; 74 | } 75 | 76 | 77 | protected void appendHeaders() 78 | { 79 | Headers.Builder headerBuilder = new Headers.Builder(); 80 | if (headers == null || headers.isEmpty()) return; 81 | 82 | for (String key : headers.keySet()) 83 | { 84 | headerBuilder.add(key, headers.get(key)); 85 | } 86 | builder.headers(headerBuilder.build()); 87 | } 88 | 89 | public int getId() 90 | { 91 | return id ; 92 | } 93 | 94 | } 95 | -------------------------------------------------------------------------------- /okhttputils/src/main/java/com/zhy/http/okhttp/request/OtherRequest.java: -------------------------------------------------------------------------------- 1 | package com.zhy.http.okhttp.request; 2 | 3 | import android.text.TextUtils; 4 | 5 | import com.zhy.http.okhttp.OkHttpUtils; 6 | import com.zhy.http.okhttp.utils.Exceptions; 7 | 8 | import java.util.Map; 9 | 10 | import okhttp3.MediaType; 11 | import okhttp3.Request; 12 | import okhttp3.RequestBody; 13 | import okhttp3.internal.http.HttpMethod; 14 | 15 | /** 16 | * Created by zhy on 16/2/23. 17 | */ 18 | public class OtherRequest extends OkHttpRequest 19 | { 20 | private static MediaType MEDIA_TYPE_PLAIN = MediaType.parse("text/plain;charset=utf-8"); 21 | 22 | private RequestBody requestBody; 23 | private String method; 24 | private String content; 25 | 26 | public OtherRequest(RequestBody requestBody, String content, String method, String url, Object tag, Map params, Map headers,int id) 27 | { 28 | super(url, tag, params, headers,id); 29 | this.requestBody = requestBody; 30 | this.method = method; 31 | this.content = content; 32 | 33 | } 34 | 35 | @Override 36 | protected RequestBody buildRequestBody() 37 | { 38 | if (requestBody == null && TextUtils.isEmpty(content) && HttpMethod.requiresRequestBody(method)) 39 | { 40 | Exceptions.illegalArgument("requestBody and content can not be null in method:" + method); 41 | } 42 | 43 | if (requestBody == null && !TextUtils.isEmpty(content)) 44 | { 45 | requestBody = RequestBody.create(MEDIA_TYPE_PLAIN, content); 46 | } 47 | 48 | return requestBody; 49 | } 50 | 51 | @Override 52 | protected Request buildRequest(RequestBody requestBody) 53 | { 54 | if (method.equals(OkHttpUtils.METHOD.PUT)) 55 | { 56 | builder.put(requestBody); 57 | } else if (method.equals(OkHttpUtils.METHOD.DELETE)) 58 | { 59 | if (requestBody == null) 60 | builder.delete(); 61 | else 62 | builder.delete(requestBody); 63 | } else if (method.equals(OkHttpUtils.METHOD.HEAD)) 64 | { 65 | builder.head(); 66 | } else if (method.equals(OkHttpUtils.METHOD.PATCH)) 67 | { 68 | builder.patch(requestBody); 69 | } 70 | 71 | return builder.build(); 72 | } 73 | 74 | } 75 | -------------------------------------------------------------------------------- /okhttputils/src/main/java/com/zhy/http/okhttp/request/PostFileRequest.java: -------------------------------------------------------------------------------- 1 | package com.zhy.http.okhttp.request; 2 | 3 | import com.zhy.http.okhttp.OkHttpUtils; 4 | import com.zhy.http.okhttp.callback.Callback; 5 | import com.zhy.http.okhttp.utils.Exceptions; 6 | 7 | import java.io.File; 8 | import java.util.Map; 9 | 10 | import okhttp3.MediaType; 11 | import okhttp3.Request; 12 | import okhttp3.RequestBody; 13 | 14 | /** 15 | * Created by zhy on 15/12/14. 16 | */ 17 | public class PostFileRequest extends OkHttpRequest 18 | { 19 | private static MediaType MEDIA_TYPE_STREAM = MediaType.parse("application/octet-stream"); 20 | 21 | private File file; 22 | private MediaType mediaType; 23 | 24 | public PostFileRequest(String url, Object tag, Map params, Map headers, File file, MediaType mediaType,int id) 25 | { 26 | super(url, tag, params, headers,id); 27 | this.file = file; 28 | this.mediaType = mediaType; 29 | 30 | if (this.file == null) 31 | { 32 | Exceptions.illegalArgument("the file can not be null !"); 33 | } 34 | if (this.mediaType == null) 35 | { 36 | this.mediaType = MEDIA_TYPE_STREAM; 37 | } 38 | } 39 | 40 | @Override 41 | protected RequestBody buildRequestBody() 42 | { 43 | return RequestBody.create(mediaType, file); 44 | } 45 | 46 | @Override 47 | protected RequestBody wrapRequestBody(RequestBody requestBody, final Callback callback) 48 | { 49 | if (callback == null) return requestBody; 50 | CountingRequestBody countingRequestBody = new CountingRequestBody(requestBody, new CountingRequestBody.Listener() 51 | { 52 | @Override 53 | public void onRequestProgress(final long bytesWritten, final long contentLength) 54 | { 55 | 56 | OkHttpUtils.getInstance().getDelivery().execute(new Runnable() 57 | { 58 | @Override 59 | public void run() 60 | { 61 | callback.inProgress(bytesWritten * 1.0f / contentLength,contentLength,id); 62 | } 63 | }); 64 | 65 | } 66 | }); 67 | return countingRequestBody; 68 | } 69 | 70 | @Override 71 | protected Request buildRequest(RequestBody requestBody) 72 | { 73 | return builder.post(requestBody).build(); 74 | } 75 | 76 | 77 | 78 | } 79 | -------------------------------------------------------------------------------- /okhttputils/src/main/java/com/zhy/http/okhttp/request/PostFormRequest.java: -------------------------------------------------------------------------------- 1 | package com.zhy.http.okhttp.request; 2 | 3 | import com.zhy.http.okhttp.OkHttpUtils; 4 | import com.zhy.http.okhttp.builder.PostFormBuilder; 5 | import com.zhy.http.okhttp.callback.Callback; 6 | 7 | import java.io.UnsupportedEncodingException; 8 | import java.net.FileNameMap; 9 | import java.net.URLConnection; 10 | import java.net.URLEncoder; 11 | import java.util.List; 12 | import java.util.Map; 13 | 14 | import okhttp3.FormBody; 15 | import okhttp3.Headers; 16 | import okhttp3.MediaType; 17 | import okhttp3.MultipartBody; 18 | import okhttp3.Request; 19 | import okhttp3.RequestBody; 20 | 21 | /** 22 | * Created by zhy on 15/12/14. 23 | */ 24 | public class PostFormRequest extends OkHttpRequest 25 | { 26 | private List files; 27 | 28 | public PostFormRequest(String url, Object tag, Map params, Map headers, List files,int id) 29 | { 30 | super(url, tag, params, headers,id); 31 | this.files = files; 32 | } 33 | 34 | @Override 35 | protected RequestBody buildRequestBody() 36 | { 37 | if (files == null || files.isEmpty()) 38 | { 39 | FormBody.Builder builder = new FormBody.Builder(); 40 | addParams(builder); 41 | FormBody formBody = builder.build(); 42 | return formBody; 43 | } else 44 | { 45 | MultipartBody.Builder builder = new MultipartBody.Builder() 46 | .setType(MultipartBody.FORM); 47 | addParams(builder); 48 | 49 | for (int i = 0; i < files.size(); i++) 50 | { 51 | PostFormBuilder.FileInput fileInput = files.get(i); 52 | RequestBody fileBody = RequestBody.create(MediaType.parse(guessMimeType(fileInput.filename)), fileInput.file); 53 | builder.addFormDataPart(fileInput.key, fileInput.filename, fileBody); 54 | } 55 | return builder.build(); 56 | } 57 | } 58 | 59 | @Override 60 | protected RequestBody wrapRequestBody(RequestBody requestBody, final Callback callback) 61 | { 62 | if (callback == null) return requestBody; 63 | CountingRequestBody countingRequestBody = new CountingRequestBody(requestBody, new CountingRequestBody.Listener() 64 | { 65 | @Override 66 | public void onRequestProgress(final long bytesWritten, final long contentLength) 67 | { 68 | 69 | OkHttpUtils.getInstance().getDelivery().execute(new Runnable() 70 | { 71 | @Override 72 | public void run() 73 | { 74 | callback.inProgress(bytesWritten * 1.0f / contentLength,contentLength,id); 75 | } 76 | }); 77 | 78 | } 79 | }); 80 | return countingRequestBody; 81 | } 82 | 83 | @Override 84 | protected Request buildRequest(RequestBody requestBody) 85 | { 86 | return builder.post(requestBody).build(); 87 | } 88 | 89 | private String guessMimeType(String path) 90 | { 91 | FileNameMap fileNameMap = URLConnection.getFileNameMap(); 92 | String contentTypeFor = null; 93 | try 94 | { 95 | contentTypeFor = fileNameMap.getContentTypeFor(URLEncoder.encode(path, "UTF-8")); 96 | } catch (UnsupportedEncodingException e) 97 | { 98 | e.printStackTrace(); 99 | } 100 | if (contentTypeFor == null) 101 | { 102 | contentTypeFor = "application/octet-stream"; 103 | } 104 | return contentTypeFor; 105 | } 106 | 107 | private void addParams(MultipartBody.Builder builder) 108 | { 109 | if (params != null && !params.isEmpty()) 110 | { 111 | for (String key : params.keySet()) 112 | { 113 | builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + key + "\""), 114 | RequestBody.create(null, params.get(key))); 115 | } 116 | } 117 | } 118 | 119 | private void addParams(FormBody.Builder builder) 120 | { 121 | if (params != null) 122 | { 123 | for (String key : params.keySet()) 124 | { 125 | builder.add(key, params.get(key)); 126 | } 127 | } 128 | } 129 | 130 | } 131 | -------------------------------------------------------------------------------- /okhttputils/src/main/java/com/zhy/http/okhttp/request/PostStringRequest.java: -------------------------------------------------------------------------------- 1 | package com.zhy.http.okhttp.request; 2 | 3 | import com.zhy.http.okhttp.utils.Exceptions; 4 | 5 | import java.util.Map; 6 | 7 | import okhttp3.MediaType; 8 | import okhttp3.Request; 9 | import okhttp3.RequestBody; 10 | 11 | /** 12 | * Created by zhy on 15/12/14. 13 | */ 14 | public class PostStringRequest extends OkHttpRequest 15 | { 16 | private static MediaType MEDIA_TYPE_PLAIN = MediaType.parse("text/plain;charset=utf-8"); 17 | 18 | private String content; 19 | private MediaType mediaType; 20 | 21 | 22 | public PostStringRequest(String url, Object tag, Map params, Map headers, String content, MediaType mediaType,int id) 23 | { 24 | super(url, tag, params, headers,id); 25 | this.content = content; 26 | this.mediaType = mediaType; 27 | 28 | if (this.content == null) 29 | { 30 | Exceptions.illegalArgument("the content can not be null !"); 31 | } 32 | if (this.mediaType == null) 33 | { 34 | this.mediaType = MEDIA_TYPE_PLAIN; 35 | } 36 | 37 | } 38 | 39 | @Override 40 | protected RequestBody buildRequestBody() 41 | { 42 | return RequestBody.create(mediaType, content); 43 | } 44 | 45 | @Override 46 | protected Request buildRequest( RequestBody requestBody) 47 | { 48 | return builder.post(requestBody).build(); 49 | } 50 | 51 | 52 | } 53 | -------------------------------------------------------------------------------- /okhttputils/src/main/java/com/zhy/http/okhttp/request/RequestCall.java: -------------------------------------------------------------------------------- 1 | package com.zhy.http.okhttp.request; 2 | 3 | import com.zhy.http.okhttp.OkHttpUtils; 4 | import com.zhy.http.okhttp.callback.Callback; 5 | 6 | import java.io.IOException; 7 | import java.util.concurrent.TimeUnit; 8 | 9 | import okhttp3.Call; 10 | import okhttp3.OkHttpClient; 11 | import okhttp3.Request; 12 | import okhttp3.Response; 13 | 14 | /** 15 | * Created by zhy on 15/12/15. 16 | * 对OkHttpRequest的封装,对外提供更多的接口:cancel(),readTimeOut()... 17 | */ 18 | public class RequestCall 19 | { 20 | private OkHttpRequest okHttpRequest; 21 | private Request request; 22 | private Call call; 23 | 24 | private long readTimeOut; 25 | private long writeTimeOut; 26 | private long connTimeOut; 27 | 28 | private OkHttpClient clone; 29 | 30 | public RequestCall(OkHttpRequest request) 31 | { 32 | this.okHttpRequest = request; 33 | } 34 | 35 | public RequestCall readTimeOut(long readTimeOut) 36 | { 37 | this.readTimeOut = readTimeOut; 38 | return this; 39 | } 40 | 41 | public RequestCall writeTimeOut(long writeTimeOut) 42 | { 43 | this.writeTimeOut = writeTimeOut; 44 | return this; 45 | } 46 | 47 | public RequestCall connTimeOut(long connTimeOut) 48 | { 49 | this.connTimeOut = connTimeOut; 50 | return this; 51 | } 52 | 53 | public Call buildCall(Callback callback) 54 | { 55 | request = generateRequest(callback); 56 | 57 | if (readTimeOut > 0 || writeTimeOut > 0 || connTimeOut > 0) 58 | { 59 | readTimeOut = readTimeOut > 0 ? readTimeOut : OkHttpUtils.DEFAULT_MILLISECONDS; 60 | writeTimeOut = writeTimeOut > 0 ? writeTimeOut : OkHttpUtils.DEFAULT_MILLISECONDS; 61 | connTimeOut = connTimeOut > 0 ? connTimeOut : OkHttpUtils.DEFAULT_MILLISECONDS; 62 | 63 | clone = OkHttpUtils.getInstance().getOkHttpClient().newBuilder() 64 | .readTimeout(readTimeOut, TimeUnit.MILLISECONDS) 65 | .writeTimeout(writeTimeOut, TimeUnit.MILLISECONDS) 66 | .connectTimeout(connTimeOut, TimeUnit.MILLISECONDS) 67 | .build(); 68 | 69 | call = clone.newCall(request); 70 | } else 71 | { 72 | call = OkHttpUtils.getInstance().getOkHttpClient().newCall(request); 73 | } 74 | return call; 75 | } 76 | 77 | private Request generateRequest(Callback callback) 78 | { 79 | return okHttpRequest.generateRequest(callback); 80 | } 81 | 82 | public void execute(Callback callback) 83 | { 84 | buildCall(callback); 85 | 86 | if (callback != null) 87 | { 88 | callback.onBefore(request, getOkHttpRequest().getId()); 89 | } 90 | 91 | OkHttpUtils.getInstance().execute(this, callback); 92 | } 93 | 94 | public Call getCall() 95 | { 96 | return call; 97 | } 98 | 99 | public Request getRequest() 100 | { 101 | return request; 102 | } 103 | 104 | public OkHttpRequest getOkHttpRequest() 105 | { 106 | return okHttpRequest; 107 | } 108 | 109 | public Response execute() throws IOException 110 | { 111 | buildCall(null); 112 | return call.execute(); 113 | } 114 | 115 | public void cancel() 116 | { 117 | if (call != null) 118 | { 119 | call.cancel(); 120 | } 121 | } 122 | 123 | 124 | } 125 | -------------------------------------------------------------------------------- /okhttputils/src/main/java/com/zhy/http/okhttp/utils/Exceptions.java: -------------------------------------------------------------------------------- 1 | package com.zhy.http.okhttp.utils; 2 | 3 | /** 4 | * Created by zhy on 15/12/14. 5 | */ 6 | public class Exceptions 7 | { 8 | public static void illegalArgument(String msg, Object... params) 9 | { 10 | throw new IllegalArgumentException(String.format(msg, params)); 11 | } 12 | 13 | 14 | } 15 | -------------------------------------------------------------------------------- /okhttputils/src/main/java/com/zhy/http/okhttp/utils/ImageUtils.java: -------------------------------------------------------------------------------- 1 | package com.zhy.http.okhttp.utils; 2 | 3 | import android.graphics.BitmapFactory; 4 | import android.util.DisplayMetrics; 5 | import android.view.View; 6 | import android.view.ViewGroup; 7 | import android.widget.ImageView; 8 | 9 | import java.io.InputStream; 10 | import java.lang.reflect.Field; 11 | 12 | /** 13 | * Created by zhy on 15/11/6. 14 | */ 15 | public class ImageUtils 16 | { 17 | /** 18 | * 根据InputStream获取图片实际的宽度和高度 19 | * 20 | * @param imageStream 21 | * @return 22 | */ 23 | public static ImageSize getImageSize(InputStream imageStream) 24 | { 25 | BitmapFactory.Options options = new BitmapFactory.Options(); 26 | options.inJustDecodeBounds = true; 27 | BitmapFactory.decodeStream(imageStream, null, options); 28 | return new ImageSize(options.outWidth, options.outHeight); 29 | } 30 | 31 | public static class ImageSize 32 | { 33 | int width; 34 | int height; 35 | 36 | public ImageSize() 37 | { 38 | } 39 | 40 | public ImageSize(int width, int height) 41 | { 42 | this.width = width; 43 | this.height = height; 44 | } 45 | 46 | @Override 47 | public String toString() 48 | { 49 | return "ImageSize{" + 50 | "width=" + width + 51 | ", height=" + height + 52 | '}'; 53 | } 54 | } 55 | 56 | public static int calculateInSampleSize(ImageSize srcSize, ImageSize targetSize) 57 | { 58 | // 源图片的宽度 59 | int width = srcSize.width; 60 | int height = srcSize.height; 61 | int inSampleSize = 1; 62 | 63 | int reqWidth = targetSize.width; 64 | int reqHeight = targetSize.height; 65 | 66 | if (width > reqWidth && height > reqHeight) 67 | { 68 | // 计算出实际宽度和目标宽度的比率 69 | int widthRatio = Math.round((float) width / (float) reqWidth); 70 | int heightRatio = Math.round((float) height / (float) reqHeight); 71 | inSampleSize = Math.max(widthRatio, heightRatio); 72 | } 73 | return inSampleSize; 74 | } 75 | 76 | /** 77 | * 根据ImageView获适当的压缩的宽和高 78 | * 79 | * @param view 80 | * @return 81 | */ 82 | public static ImageSize getImageViewSize(View view) 83 | { 84 | 85 | ImageSize imageSize = new ImageSize(); 86 | 87 | imageSize.width = getExpectWidth(view); 88 | imageSize.height = getExpectHeight(view); 89 | 90 | return imageSize; 91 | } 92 | 93 | /** 94 | * 根据view获得期望的高度 95 | * 96 | * @param view 97 | * @return 98 | */ 99 | private static int getExpectHeight(View view) 100 | { 101 | 102 | int height = 0; 103 | if (view == null) return 0; 104 | 105 | final ViewGroup.LayoutParams params = view.getLayoutParams(); 106 | //如果是WRAP_CONTENT,此时图片还没加载,getWidth根本无效 107 | if (params != null && params.height != ViewGroup.LayoutParams.WRAP_CONTENT) 108 | { 109 | height = view.getWidth(); // 获得实际的宽度 110 | } 111 | if (height <= 0 && params != null) 112 | { 113 | height = params.height; // 获得布局文件中的声明的宽度 114 | } 115 | 116 | if (height <= 0) 117 | { 118 | height = getImageViewFieldValue(view, "mMaxHeight");// 获得设置的最大的宽度 119 | } 120 | 121 | //如果宽度还是没有获取到,憋大招,使用屏幕的宽度 122 | if (height <= 0) 123 | { 124 | DisplayMetrics displayMetrics = view.getContext().getResources() 125 | .getDisplayMetrics(); 126 | height = displayMetrics.heightPixels; 127 | } 128 | 129 | return height; 130 | } 131 | 132 | /** 133 | * 根据view获得期望的宽度 134 | * 135 | * @param view 136 | * @return 137 | */ 138 | private static int getExpectWidth(View view) 139 | { 140 | int width = 0; 141 | if (view == null) return 0; 142 | 143 | final ViewGroup.LayoutParams params = view.getLayoutParams(); 144 | //如果是WRAP_CONTENT,此时图片还没加载,getWidth根本无效 145 | if (params != null && params.width != ViewGroup.LayoutParams.WRAP_CONTENT) 146 | { 147 | width = view.getWidth(); // 获得实际的宽度 148 | } 149 | if (width <= 0 && params != null) 150 | { 151 | width = params.width; // 获得布局文件中的声明的宽度 152 | } 153 | 154 | if (width <= 0) 155 | 156 | { 157 | width = getImageViewFieldValue(view, "mMaxWidth");// 获得设置的最大的宽度 158 | } 159 | //如果宽度还是没有获取到,憋大招,使用屏幕的宽度 160 | if (width <= 0) 161 | 162 | { 163 | DisplayMetrics displayMetrics = view.getContext().getResources() 164 | .getDisplayMetrics(); 165 | width = displayMetrics.widthPixels; 166 | } 167 | 168 | return width; 169 | } 170 | 171 | /** 172 | * 通过反射获取imageview的某个属性值 173 | * 174 | * @param object 175 | * @param fieldName 176 | * @return 177 | */ 178 | private static int getImageViewFieldValue(Object object, String fieldName) 179 | { 180 | int value = 0; 181 | try 182 | { 183 | Field field = ImageView.class.getDeclaredField(fieldName); 184 | field.setAccessible(true); 185 | int fieldValue = field.getInt(object); 186 | if (fieldValue > 0 && fieldValue < Integer.MAX_VALUE) 187 | { 188 | value = fieldValue; 189 | } 190 | } catch (Exception e) 191 | { 192 | } 193 | return value; 194 | 195 | } 196 | } 197 | -------------------------------------------------------------------------------- /okhttputils/src/main/java/com/zhy/http/okhttp/utils/L.java: -------------------------------------------------------------------------------- 1 | package com.zhy.http.okhttp.utils; 2 | 3 | import android.util.Log; 4 | 5 | /** 6 | * Created by zhy on 15/11/6. 7 | */ 8 | public class L 9 | { 10 | private static boolean debug = false; 11 | 12 | public static void e(String msg) 13 | { 14 | if (debug) 15 | { 16 | Log.e("OkHttp", msg); 17 | } 18 | } 19 | 20 | } 21 | 22 | -------------------------------------------------------------------------------- /okhttputils/src/main/java/com/zhy/http/okhttp/utils/Platform.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2013 Square, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.zhy.http.okhttp.utils; 17 | 18 | import android.os.Build; 19 | import android.os.Handler; 20 | import android.os.Looper; 21 | 22 | import java.util.concurrent.Executor; 23 | import java.util.concurrent.Executors; 24 | 25 | public class Platform 26 | { 27 | private static final Platform PLATFORM = findPlatform(); 28 | 29 | public static Platform get() 30 | { 31 | L.e(PLATFORM.getClass().toString()); 32 | return PLATFORM; 33 | } 34 | 35 | private static Platform findPlatform() 36 | { 37 | try 38 | { 39 | Class.forName("android.os.Build"); 40 | if (Build.VERSION.SDK_INT != 0) 41 | { 42 | return new Android(); 43 | } 44 | } catch (ClassNotFoundException ignored) 45 | { 46 | } 47 | return new Platform(); 48 | } 49 | 50 | public Executor defaultCallbackExecutor() 51 | { 52 | return Executors.newCachedThreadPool(); 53 | } 54 | 55 | public void execute(Runnable runnable) 56 | { 57 | defaultCallbackExecutor().execute(runnable); 58 | } 59 | 60 | 61 | static class Android extends Platform 62 | { 63 | @Override 64 | public Executor defaultCallbackExecutor() 65 | { 66 | return new MainThreadExecutor(); 67 | } 68 | 69 | static class MainThreadExecutor implements Executor 70 | { 71 | private final Handler handler = new Handler(Looper.getMainLooper()); 72 | 73 | @Override 74 | public void execute(Runnable r) 75 | { 76 | handler.post(r); 77 | } 78 | } 79 | } 80 | 81 | 82 | } 83 | -------------------------------------------------------------------------------- /sample-okhttp/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /sample-okhttp/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 22 5 | buildToolsVersion "22.0.1" 6 | 7 | defaultConfig { 8 | applicationId "com.zhy.sample_okhttp" 9 | minSdkVersion 10 10 | targetSdkVersion 22 11 | versionCode 1 12 | versionName "1.0" 13 | } 14 | buildTypes { 15 | release { 16 | minifyEnabled false 17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 18 | } 19 | 20 | } 21 | 22 | lintOptions{ 23 | abortOnError false 24 | } 25 | } 26 | 27 | dependencies { 28 | compile fileTree(dir: 'libs', include: ['*.jar']) 29 | compile 'com.android.support:appcompat-v7:22.2.1' 30 | compile project(':okhttputils') 31 | // compile 'com.zhy:okhttputils:2.6.1' 32 | compile 'com.google.code.gson:gson:2.3.1' 33 | compile 'com.squareup.okhttp3:okhttp-urlconnection:3.2.0' 34 | compile 'com.github.franmontiel:PersistentCookieJar:v0.9.3' 35 | } 36 | -------------------------------------------------------------------------------- /sample-okhttp/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 /Users/zhy/android/sdk/android-sdk-macosx/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 | #shrink,测试后发现会将一些无效代码给移除,即没有被显示调用的代码,该选项 表示 不启用 shrink。 19 | -dontshrink 20 | #指定重新打包,所有包重命名,这个选项会进一步模糊包名,将包里的类混淆成n个再重新打包到一个个的package中 21 | -flattenpackagehierarchy 22 | #优化时允许访问并修改有修饰符的类和类的成员 23 | -allowaccessmodification 24 | #混淆前后的映射 25 | -printmapping map.txt 26 | #不跳过(混淆) jars中的 非public classes 默认选项 27 | -dontskipnonpubliclibraryclassmembers 28 | #忽略警告 29 | -ignorewarnings 30 | #指定代码的压缩级别 31 | -optimizationpasses 5 32 | #不使用大小写混合类名 33 | -dontusemixedcaseclassnames 34 | #不去忽略非公共的库类 35 | -dontskipnonpubliclibraryclasses 36 | #不启用优化 不优化输入的类文件 37 | -dontoptimize 38 | #不预校验 39 | -dontpreverify 40 | #混淆时是否记录日志 41 | -verbose 42 | #混淆时所采用的算法 43 | -optimizations !code/simplification/arithmetic,!field/*,!class/merging/* 44 | #保护注解 45 | -renamesourcefileattribute SourceFile 46 | #保持源文件和行号的信息,用于混淆后定位错误位置 47 | -keepattributes SourceFile,LineNumberTable 48 | -keepattributes SourceFile,LineNumberTable 49 | #保持含有Annotation字符串的 attributes 50 | -keepattributes *Annotation* 51 | -keepattributes Signature 52 | -keepattributes Exceptions,InnerClasses 53 | 54 | -dontwarn org.apache.** 55 | -dontwarn android.support.** 56 | 57 | #基础配置 58 | # 保持哪些类不被混淆 59 | # 系统组件 60 | -keep public class * extends android.app.Fragment 61 | -keep public class * extends android.app.Activity 62 | -keep public class * extends android.app.Application 63 | -keep public class * extends android.app.Service 64 | -keep public class * extends android.content.BroadcastReceiver 65 | -keep public class * extends android.content.ContentProvider 66 | -keep public class * extends android.app.backup.BackupAgentHelper 67 | -keep public class * extends android.preference.Preference 68 | -keep public class com.android.vending.licensing.ILicensingService 69 | #如果有引用v4包可以添加下面这行 70 | -keep public class * extends android.support.v4.app.Fragment 71 | #自定义View 72 | -keep public class * extends android.view.View 73 | # V4,V7 74 | -keep class android.support.v4.**{ *; } 75 | -keep class android.support.v7.**{ *; } 76 | -keep class android.webkit.**{*;} 77 | -keep interface android.support.v4.app.** { *; } 78 | #保持 本化方法及其类声明 79 | -keepclasseswithmembers class * { 80 | native ; 81 | } 82 | #保持view的子类成员: getter setter 83 | -keepclassmembers public class * extends android.view.View { 84 | void set*(***); 85 | *** get*(); 86 | } 87 | #保持Activity的子类成员:参数为一个View类型的方法 如setContentView(View v) 88 | -keepclassmembers class * extends android.app.Activity { 89 | public void *(android.view.View); 90 | } 91 | #保持枚举类的成员:values方法和valueOf (每个enum 类都默认有这两个方法) 92 | -keepclassmembers enum * { 93 | public static **[] values(); 94 | public static ** valueOf(java.lang.String); 95 | } 96 | #保持Parcelable的实现类和它的成员:类型为android.os.Parcelable$Creator 名字任意的 属性 97 | -keep class * implements android.os.Parcelable { 98 | public static final android.os.Parcelable$Creator *; 99 | } 100 | #保持 任意包名.R类的类成员属性。 即保护R文件中的属性名不变 101 | -keepclassmembers class **.R$* { 102 | public static ; 103 | } 104 | 105 | #MPermission 106 | -dontwarn com.zhy.m.** 107 | -keep class com.zhy.m.** {*;} 108 | -keep interface com.zhy.m.** { *; } 109 | -keep class **$$PermissionProxy { *; } 110 | 111 | #okio 112 | -dontwarn okio.** 113 | -keep class okio.**{*;} 114 | -keep interface okio.**{*;} 115 | 116 | #okhttputils 117 | -dontwarn com.zhy.http.** 118 | -keep class com.zhy.http.**{*;} 119 | -keep interface com.zhy.http.**{*;} 120 | 121 | #okhttp 122 | -dontwarn okhttp3.** 123 | -keep class okhttp3.**{*;} 124 | -keep interface okhttp3.**{*;} -------------------------------------------------------------------------------- /sample-okhttp/sample-okhttp.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 8 | 9 | 10 | 11 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | -------------------------------------------------------------------------------- /sample-okhttp/src/androidTest/java/com/zhy/sample_okhttp/ApplicationTest.java: -------------------------------------------------------------------------------- 1 | package com.zhy.sample_okhttp; 2 | 3 | import android.app.Application; 4 | import android.test.ApplicationTestCase; 5 | 6 | /** 7 | * Testing Fundamentals 8 | */ 9 | public class ApplicationTest extends ApplicationTestCase 10 | { 11 | public ApplicationTest() 12 | { 13 | super(Application.class); 14 | } 15 | } -------------------------------------------------------------------------------- /sample-okhttp/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 14 | 15 | android:theme="@style/AppTheme" > 16 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /sample-okhttp/src/main/assets/srca.cer: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hongyangAndroid/okhttputils/11fdc3c7368e481cc182e79188973418bc5d0939/sample-okhttp/src/main/assets/srca.cer -------------------------------------------------------------------------------- /sample-okhttp/src/main/assets/zhy_client.bks: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hongyangAndroid/okhttputils/11fdc3c7368e481cc182e79188973418bc5d0939/sample-okhttp/src/main/assets/zhy_client.bks -------------------------------------------------------------------------------- /sample-okhttp/src/main/assets/zhy_server.cer: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hongyangAndroid/okhttputils/11fdc3c7368e481cc182e79188973418bc5d0939/sample-okhttp/src/main/assets/zhy_server.cer -------------------------------------------------------------------------------- /sample-okhttp/src/main/java/com/zhy/sample_okhttp/FlowLayout.java: -------------------------------------------------------------------------------- 1 | package com.zhy.sample_okhttp; 2 | 3 | import android.content.Context; 4 | import android.util.AttributeSet; 5 | import android.view.View; 6 | import android.view.ViewGroup; 7 | 8 | import java.util.ArrayList; 9 | import java.util.List; 10 | 11 | public class FlowLayout extends ViewGroup 12 | { 13 | 14 | public FlowLayout(Context context, AttributeSet attrs, int defStyle) 15 | { 16 | super(context, attrs, defStyle); 17 | // 18 | } 19 | 20 | public FlowLayout(Context context, AttributeSet attrs) 21 | { 22 | this(context, attrs, 0); 23 | } 24 | 25 | public FlowLayout(Context context) 26 | { 27 | this(context, null); 28 | } 29 | 30 | @Override 31 | protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) 32 | { 33 | int sizeWidth = MeasureSpec.getSize(widthMeasureSpec); 34 | int modeWidth = MeasureSpec.getMode(widthMeasureSpec); 35 | int sizeHeight = MeasureSpec.getSize(heightMeasureSpec); 36 | int modeHeight = MeasureSpec.getMode(heightMeasureSpec); 37 | 38 | int width = 0; 39 | int height = 0; 40 | 41 | int lineWidth = 0; 42 | int lineHeight = 0; 43 | 44 | int cCount = getChildCount(); 45 | 46 | for (int i = 0; i < cCount; i++) 47 | { 48 | View child = getChildAt(i); 49 | measureChild(child, widthMeasureSpec, heightMeasureSpec); 50 | MarginLayoutParams lp = (MarginLayoutParams) child 51 | .getLayoutParams(); 52 | 53 | int childWidth = child.getMeasuredWidth() + lp.leftMargin 54 | + lp.rightMargin; 55 | int childHeight = child.getMeasuredHeight() + lp.topMargin 56 | + lp.bottomMargin; 57 | 58 | if (lineWidth + childWidth > sizeWidth - getPaddingLeft() - getPaddingRight()) 59 | { 60 | width = Math.max(width, lineWidth); 61 | lineWidth = childWidth; 62 | height += lineHeight; 63 | lineHeight = childHeight; 64 | } else 65 | { 66 | lineWidth += childWidth; 67 | lineHeight = Math.max(lineHeight, childHeight); 68 | } 69 | if (i == cCount - 1) 70 | { 71 | width = Math.max(lineWidth, width); 72 | height += lineHeight; 73 | } 74 | } 75 | setMeasuredDimension( 76 | // 77 | modeWidth == MeasureSpec.EXACTLY ? sizeWidth : width + getPaddingLeft() + getPaddingRight(), 78 | modeHeight == MeasureSpec.EXACTLY ? sizeHeight : height + getPaddingTop()+ getPaddingBottom()// 79 | ); 80 | 81 | } 82 | 83 | private List> mAllViews = new ArrayList>(); 84 | private List mLineHeight = new ArrayList(); 85 | 86 | @Override 87 | protected void onLayout(boolean changed, int l, int t, int r, int b) 88 | { 89 | mAllViews.clear(); 90 | mLineHeight.clear(); 91 | 92 | int width = getWidth(); 93 | 94 | int lineWidth = 0; 95 | int lineHeight = 0; 96 | 97 | List lineViews = new ArrayList(); 98 | 99 | int cCount = getChildCount(); 100 | 101 | for (int i = 0; i < cCount; i++) 102 | { 103 | View child = getChildAt(i); 104 | MarginLayoutParams lp = (MarginLayoutParams) child 105 | .getLayoutParams(); 106 | 107 | int childWidth = child.getMeasuredWidth(); 108 | int childHeight = child.getMeasuredHeight(); 109 | 110 | if (childWidth + lineWidth + lp.leftMargin + lp.rightMargin > width - getPaddingLeft() - getPaddingRight()) 111 | { 112 | mLineHeight.add(lineHeight); 113 | mAllViews.add(lineViews); 114 | 115 | lineWidth = 0; 116 | lineHeight = childHeight + lp.topMargin + lp.bottomMargin; 117 | lineViews = new ArrayList(); 118 | } 119 | lineWidth += childWidth + lp.leftMargin + lp.rightMargin; 120 | lineHeight = Math.max(lineHeight, childHeight + lp.topMargin 121 | + lp.bottomMargin); 122 | lineViews.add(child); 123 | 124 | } 125 | mLineHeight.add(lineHeight); 126 | mAllViews.add(lineViews); 127 | 128 | 129 | int left = getPaddingLeft(); 130 | int top = getPaddingTop(); 131 | 132 | int lineNum = mAllViews.size(); 133 | 134 | for (int i = 0; i < lineNum; i++) 135 | { 136 | lineViews = mAllViews.get(i); 137 | lineHeight = mLineHeight.get(i); 138 | 139 | for (int j = 0; j < lineViews.size(); j++) 140 | { 141 | View child = lineViews.get(j); 142 | if (child.getVisibility() == View.GONE) 143 | { 144 | continue; 145 | } 146 | 147 | MarginLayoutParams lp = (MarginLayoutParams) child 148 | .getLayoutParams(); 149 | 150 | int lc = left + lp.leftMargin; 151 | int tc = top + lp.topMargin; 152 | int rc = lc + child.getMeasuredWidth(); 153 | int bc = tc + child.getMeasuredHeight(); 154 | 155 | child.layout(lc, tc, rc, bc); 156 | 157 | left += child.getMeasuredWidth() + lp.leftMargin 158 | + lp.rightMargin; 159 | } 160 | left = getPaddingLeft() ; 161 | top += lineHeight ; 162 | } 163 | 164 | } 165 | 166 | @Override 167 | public LayoutParams generateLayoutParams(AttributeSet attrs) 168 | { 169 | return new MarginLayoutParams(getContext(), attrs); 170 | } 171 | 172 | } 173 | -------------------------------------------------------------------------------- /sample-okhttp/src/main/java/com/zhy/sample_okhttp/JsonGenericsSerializator.java: -------------------------------------------------------------------------------- 1 | package com.zhy.sample_okhttp; 2 | 3 | import com.google.gson.Gson; 4 | import com.zhy.http.okhttp.callback.IGenericsSerializator; 5 | 6 | /** 7 | * Created by JimGong on 2016/6/23. 8 | */ 9 | public class JsonGenericsSerializator implements IGenericsSerializator { 10 | Gson mGson = new Gson(); 11 | @Override 12 | public T transform(String response, Class classOfT) { 13 | return mGson.fromJson(response, classOfT); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /sample-okhttp/src/main/java/com/zhy/sample_okhttp/ListUserCallback.java: -------------------------------------------------------------------------------- 1 | package com.zhy.sample_okhttp; 2 | 3 | import com.google.gson.Gson; 4 | import com.zhy.http.okhttp.callback.Callback; 5 | 6 | import java.io.IOException; 7 | import java.util.List; 8 | 9 | import okhttp3.Response; 10 | 11 | /** 12 | * Created by zhy on 15/12/14. 13 | */ 14 | public abstract class ListUserCallback extends Callback> 15 | { 16 | 17 | @Override 18 | public List parseNetworkResponse(Response response,int id) throws IOException 19 | { 20 | String string = response.body().string(); 21 | List user = new Gson().fromJson(string, List.class); 22 | return user; 23 | } 24 | 25 | 26 | } 27 | -------------------------------------------------------------------------------- /sample-okhttp/src/main/java/com/zhy/sample_okhttp/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.zhy.sample_okhttp; 2 | 3 | import android.graphics.Bitmap; 4 | import android.os.Bundle; 5 | import android.os.Environment; 6 | import android.support.v7.app.AppCompatActivity; 7 | import android.util.Log; 8 | import android.view.View; 9 | import android.widget.ImageView; 10 | import android.widget.ProgressBar; 11 | import android.widget.TextView; 12 | import android.widget.Toast; 13 | 14 | import com.google.gson.Gson; 15 | import com.zhy.http.okhttp.OkHttpUtils; 16 | import com.zhy.http.okhttp.callback.BitmapCallback; 17 | import com.zhy.http.okhttp.callback.FileCallBack; 18 | import com.zhy.http.okhttp.callback.GenericsCallback; 19 | import com.zhy.http.okhttp.callback.StringCallback; 20 | import com.zhy.http.okhttp.cookie.CookieJarImpl; 21 | 22 | import java.io.File; 23 | import java.util.HashMap; 24 | import java.util.List; 25 | import java.util.Map; 26 | 27 | import okhttp3.Call; 28 | import okhttp3.CookieJar; 29 | import okhttp3.MediaType; 30 | import okhttp3.Request; 31 | 32 | public class MainActivity extends AppCompatActivity 33 | { 34 | 35 | private String mBaseUrl = "http://192.168.31.242:8888/okHttpServer/"; 36 | 37 | private static final String TAG = "MainActivity"; 38 | 39 | private TextView mTv; 40 | private ImageView mImageView; 41 | private ProgressBar mProgressBar; 42 | 43 | 44 | public class MyStringCallback extends StringCallback 45 | { 46 | @Override 47 | public void onBefore(Request request, int id) 48 | { 49 | setTitle("loading..."); 50 | } 51 | 52 | @Override 53 | public void onAfter(int id) 54 | { 55 | setTitle("Sample-okHttp"); 56 | } 57 | 58 | @Override 59 | public void onError(Call call, Exception e, int id) 60 | { 61 | e.printStackTrace(); 62 | mTv.setText("onError:" + e.getMessage()); 63 | } 64 | 65 | @Override 66 | public void onResponse(String response, int id) 67 | { 68 | Log.e(TAG, "onResponse:complete"); 69 | mTv.setText("onResponse:" + response); 70 | 71 | switch (id) 72 | { 73 | case 100: 74 | Toast.makeText(MainActivity.this, "http", Toast.LENGTH_SHORT).show(); 75 | break; 76 | case 101: 77 | Toast.makeText(MainActivity.this, "https", Toast.LENGTH_SHORT).show(); 78 | break; 79 | } 80 | } 81 | 82 | @Override 83 | public void inProgress(float progress, long total, int id) 84 | { 85 | Log.e(TAG, "inProgress:" + progress); 86 | mProgressBar.setProgress((int) (100 * progress)); 87 | } 88 | } 89 | 90 | 91 | @Override 92 | protected void onCreate(Bundle savedInstanceState) 93 | { 94 | 95 | 96 | super.onCreate(savedInstanceState); 97 | setContentView(R.layout.activity_main); 98 | 99 | 100 | mTv = (TextView) findViewById(R.id.id_textview); 101 | mImageView = (ImageView) findViewById(R.id.id_imageview); 102 | mProgressBar = (ProgressBar) findViewById(R.id.id_progress); 103 | mProgressBar.setMax(100); 104 | } 105 | 106 | public void getHtml(View view) 107 | { 108 | String url = "http://www.zhiyun-tech.com/App/Rider-M/changelog-zh.txt"; 109 | url="http://www.391k.com/api/xapi.ashx/info.json?key=bd_hyrzjjfb4modhj&size=10&page=1"; 110 | OkHttpUtils 111 | .get() 112 | .url(url) 113 | .id(100) 114 | .build() 115 | .execute(new MyStringCallback()); 116 | } 117 | 118 | 119 | public void postString(View view) 120 | { 121 | String url = mBaseUrl + "user!postString"; 122 | OkHttpUtils 123 | .postString() 124 | .url(url) 125 | .mediaType(MediaType.parse("application/json; charset=utf-8")) 126 | .content(new Gson().toJson(new User("zhy", "123"))) 127 | .build() 128 | .execute(new MyStringCallback()); 129 | 130 | } 131 | 132 | public void postFile(View view) 133 | { 134 | File file = new File(Environment.getExternalStorageDirectory(), "messenger_01.png"); 135 | if (!file.exists()) 136 | { 137 | Toast.makeText(MainActivity.this, "文件不存在,请修改文件路径", Toast.LENGTH_SHORT).show(); 138 | return; 139 | } 140 | String url = mBaseUrl + "user!postFile"; 141 | OkHttpUtils 142 | .postFile() 143 | .url(url) 144 | .file(file) 145 | .build() 146 | .execute(new MyStringCallback()); 147 | 148 | 149 | } 150 | 151 | public void getUser(View view) 152 | { 153 | String url = mBaseUrl + "user!getUser"; 154 | OkHttpUtils 155 | .post()// 156 | .url(url)// 157 | .addParams("username", "hyman")// 158 | .addParams("password", "123")// 159 | .build()// 160 | .execute(new GenericsCallback(new JsonGenericsSerializator()) 161 | { 162 | @Override 163 | public void onError(Call call, Exception e, int id) 164 | { 165 | mTv.setText("onError:" + e.getMessage()); 166 | } 167 | 168 | @Override 169 | public void onResponse(User response, int id) 170 | { 171 | mTv.setText("onResponse:" + response.username); 172 | } 173 | }); 174 | } 175 | 176 | 177 | public void getUsers(View view) 178 | { 179 | Map params = new HashMap(); 180 | params.put("name", "zhy"); 181 | String url = mBaseUrl + "user!getUsers"; 182 | OkHttpUtils// 183 | .post()// 184 | .url(url)// 185 | // .params(params)// 186 | .build()// 187 | .execute(new ListUserCallback()// 188 | { 189 | @Override 190 | public void onError(Call call, Exception e, int id) 191 | { 192 | mTv.setText("onError:" + e.getMessage()); 193 | } 194 | 195 | @Override 196 | public void onResponse(List response, int id) 197 | { 198 | mTv.setText("onResponse:" + response); 199 | } 200 | }); 201 | } 202 | 203 | 204 | public void getHttpsHtml(View view) 205 | { 206 | String url = "https://kyfw.12306.cn/otn/"; 207 | 208 | // "https://12 209 | // url =3.125.219.144:8443/mobileConnect/MobileConnect/authLogin.action?systemid=100009&mobile=13260284063&pipe=2&reqtime=1422986580048&ispin=2"; 210 | OkHttpUtils 211 | .get()// 212 | .url(url)// 213 | .id(101) 214 | .build()// 215 | .execute(new MyStringCallback()); 216 | 217 | } 218 | 219 | public void getImage(View view) 220 | { 221 | mTv.setText(""); 222 | String url = "http://images.csdn.net/20150817/1.jpg"; 223 | OkHttpUtils 224 | .get()// 225 | .url(url)// 226 | .tag(this)// 227 | .build()// 228 | .connTimeOut(20000) 229 | .readTimeOut(20000) 230 | .writeTimeOut(20000) 231 | .execute(new BitmapCallback() 232 | { 233 | @Override 234 | public void onError(Call call, Exception e, int id) 235 | { 236 | mTv.setText("onError:" + e.getMessage()); 237 | } 238 | 239 | @Override 240 | public void onResponse(Bitmap bitmap, int id) 241 | { 242 | Log.e("TAG", "onResponse:complete"); 243 | mImageView.setImageBitmap(bitmap); 244 | } 245 | }); 246 | } 247 | 248 | 249 | public void uploadFile(View view) 250 | { 251 | 252 | File file = new File(Environment.getExternalStorageDirectory(), "messenger_01.png"); 253 | if (!file.exists()) 254 | { 255 | Toast.makeText(MainActivity.this, "文件不存在,请修改文件路径", Toast.LENGTH_SHORT).show(); 256 | return; 257 | } 258 | Map params = new HashMap<>(); 259 | params.put("username", "张鸿洋"); 260 | params.put("password", "123"); 261 | 262 | Map headers = new HashMap<>(); 263 | headers.put("APP-Key", "APP-Secret222"); 264 | headers.put("APP-Secret", "APP-Secret111"); 265 | 266 | String url = mBaseUrl + "user!uploadFile"; 267 | 268 | OkHttpUtils.post()// 269 | .addFile("mFile", "messenger_01.png", file)// 270 | .url(url)// 271 | .params(params)// 272 | .headers(headers)// 273 | .build()// 274 | .execute(new MyStringCallback()); 275 | } 276 | 277 | 278 | public void multiFileUpload(View view) 279 | { 280 | File file = new File(Environment.getExternalStorageDirectory(), "messenger_01.png"); 281 | File file2 = new File(Environment.getExternalStorageDirectory(), "test1#.txt"); 282 | if (!file.exists()) 283 | { 284 | Toast.makeText(MainActivity.this, "文件不存在,请修改文件路径", Toast.LENGTH_SHORT).show(); 285 | return; 286 | } 287 | Map params = new HashMap<>(); 288 | params.put("username", "张鸿洋"); 289 | params.put("password", "123"); 290 | 291 | String url = mBaseUrl + "user!uploadFile"; 292 | OkHttpUtils.post()// 293 | .addFile("mFile", "messenger_01.png", file)// 294 | .addFile("mFile", "test1.txt", file2)// 295 | .url(url) 296 | .params(params)// 297 | .build()// 298 | .execute(new MyStringCallback()); 299 | } 300 | 301 | 302 | public void downloadFile(View view) 303 | { 304 | String url = "https://github.com/hongyangAndroid/okhttp-utils/blob/master/okhttputils-2_4_1.jar?raw=true"; 305 | OkHttpUtils// 306 | .get()// 307 | .url(url)// 308 | .build()// 309 | .execute(new FileCallBack(Environment.getExternalStorageDirectory().getAbsolutePath(), "gson-2.2.1.jar")// 310 | { 311 | 312 | @Override 313 | public void onBefore(Request request, int id) 314 | { 315 | } 316 | 317 | @Override 318 | public void inProgress(float progress, long total, int id) 319 | { 320 | mProgressBar.setProgress((int) (100 * progress)); 321 | Log.e(TAG, "inProgress :" + (int) (100 * progress)); 322 | } 323 | 324 | @Override 325 | public void onError(Call call, Exception e, int id) 326 | { 327 | Log.e(TAG, "onError :" + e.getMessage()); 328 | } 329 | 330 | @Override 331 | public void onResponse(File file, int id) 332 | { 333 | Log.e(TAG, "onResponse :" + file.getAbsolutePath()); 334 | } 335 | }); 336 | } 337 | 338 | 339 | public void otherRequestDemo(View view) 340 | { 341 | //also can use delete ,head , patch 342 | /* 343 | OkHttpUtils 344 | .put()// 345 | .url("http://11111.com") 346 | .requestBody 347 | ("may be something")// 348 | .build()// 349 | .execute(new MyStringCallback()); 350 | 351 | 352 | 353 | OkHttpUtils 354 | .head()// 355 | .url(url) 356 | .addParams("name", "zhy") 357 | .build() 358 | .execute(); 359 | 360 | */ 361 | 362 | 363 | } 364 | 365 | public void clearSession(View view) 366 | { 367 | CookieJar cookieJar = OkHttpUtils.getInstance().getOkHttpClient().cookieJar(); 368 | if (cookieJar instanceof CookieJarImpl) 369 | { 370 | ((CookieJarImpl) cookieJar).getCookieStore().removeAll(); 371 | } 372 | } 373 | 374 | 375 | @Override 376 | protected void onDestroy() 377 | { 378 | super.onDestroy(); 379 | OkHttpUtils.getInstance().cancelTag(this); 380 | } 381 | } 382 | -------------------------------------------------------------------------------- /sample-okhttp/src/main/java/com/zhy/sample_okhttp/MyApplication.java: -------------------------------------------------------------------------------- 1 | package com.zhy.sample_okhttp; 2 | 3 | import android.app.Application; 4 | 5 | import com.franmontiel.persistentcookiejar.ClearableCookieJar; 6 | import com.franmontiel.persistentcookiejar.PersistentCookieJar; 7 | import com.franmontiel.persistentcookiejar.cache.SetCookieCache; 8 | import com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor; 9 | import com.zhy.http.okhttp.OkHttpUtils; 10 | import com.zhy.http.okhttp.https.HttpsUtils; 11 | import com.zhy.http.okhttp.log.LoggerInterceptor; 12 | 13 | import java.util.concurrent.TimeUnit; 14 | 15 | import javax.net.ssl.HostnameVerifier; 16 | import javax.net.ssl.SSLSession; 17 | 18 | import okhttp3.OkHttpClient; 19 | 20 | /** 21 | * Created by zhy on 15/8/25. 22 | */ 23 | public class MyApplication extends Application 24 | { 25 | private String CER_12306 = "-----BEGIN CERTIFICATE-----\n" + 26 | "MIICmjCCAgOgAwIBAgIIbyZr5/jKH6QwDQYJKoZIhvcNAQEFBQAwRzELMAkGA1UEBhMCQ04xKTAn\n" + 27 | "BgNVBAoTIFNpbm9yYWlsIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MQ0wCwYDVQQDEwRTUkNBMB4X\n" + 28 | "DTA5MDUyNTA2NTYwMFoXDTI5MDUyMDA2NTYwMFowRzELMAkGA1UEBhMCQ04xKTAnBgNVBAoTIFNp\n" + 29 | "bm9yYWlsIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MQ0wCwYDVQQDEwRTUkNBMIGfMA0GCSqGSIb3\n" + 30 | "DQEBAQUAA4GNADCBiQKBgQDMpbNeb34p0GvLkZ6t72/OOba4mX2K/eZRWFfnuk8e5jKDH+9BgCb2\n" + 31 | "9bSotqPqTbxXWPxIOz8EjyUO3bfR5pQ8ovNTOlks2rS5BdMhoi4sUjCKi5ELiqtyww/XgY5iFqv6\n" + 32 | "D4Pw9QvOUcdRVSbPWo1DwMmH75It6pk/rARIFHEjWwIDAQABo4GOMIGLMB8GA1UdIwQYMBaAFHle\n" + 33 | "tne34lKDQ+3HUYhMY4UsAENYMAwGA1UdEwQFMAMBAf8wLgYDVR0fBCcwJTAjoCGgH4YdaHR0cDov\n" + 34 | "LzE5Mi4xNjguOS4xNDkvY3JsMS5jcmwwCwYDVR0PBAQDAgH+MB0GA1UdDgQWBBR5XrZ3t+JSg0Pt\n" + 35 | "x1GITGOFLABDWDANBgkqhkiG9w0BAQUFAAOBgQDGrAm2U/of1LbOnG2bnnQtgcVaBXiVJF8LKPaV\n" + 36 | "23XQ96HU8xfgSZMJS6U00WHAI7zp0q208RSUft9wDq9ee///VOhzR6Tebg9QfyPSohkBrhXQenvQ\n" + 37 | "og555S+C3eJAAVeNCTeMS3N/M5hzBRJAoffn3qoYdAO1Q8bTguOi+2849A==\n" + 38 | "-----END CERTIFICATE-----"; 39 | 40 | 41 | @Override 42 | public void onCreate() 43 | { 44 | super.onCreate(); 45 | 46 | ClearableCookieJar cookieJar1 = new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(getApplicationContext())); 47 | 48 | HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory(null, null, null); 49 | 50 | // CookieJarImpl cookieJar1 = new CookieJarImpl(new MemoryCookieStore()); 51 | OkHttpClient okHttpClient = new OkHttpClient.Builder() 52 | .connectTimeout(10000L, TimeUnit.MILLISECONDS) 53 | .readTimeout(10000L, TimeUnit.MILLISECONDS) 54 | .addInterceptor(new LoggerInterceptor("TAG")) 55 | .cookieJar(cookieJar1) 56 | .hostnameVerifier(new HostnameVerifier() 57 | { 58 | @Override 59 | public boolean verify(String hostname, SSLSession session) 60 | { 61 | return true; 62 | } 63 | }) 64 | .sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager) 65 | .build(); 66 | OkHttpUtils.initClient(okHttpClient); 67 | 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /sample-okhttp/src/main/java/com/zhy/sample_okhttp/User.java: -------------------------------------------------------------------------------- 1 | package com.zhy.sample_okhttp; 2 | 3 | public class User { 4 | 5 | public String username ; 6 | public String password ; 7 | 8 | public User() { 9 | // TODO Auto-generated constructor stub 10 | } 11 | 12 | public User(String username, String password) { 13 | this.username = username; 14 | this.password = password; 15 | } 16 | 17 | @Override 18 | public String toString() 19 | { 20 | return "User{" + 21 | "username='" + username + '\'' + 22 | ", password='" + password + '\'' + 23 | '}'; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /sample-okhttp/src/main/java/com/zhy/sample_okhttp/UserCallback.java: -------------------------------------------------------------------------------- 1 | package com.zhy.sample_okhttp; 2 | 3 | import com.google.gson.Gson; 4 | import com.zhy.http.okhttp.callback.Callback; 5 | 6 | import java.io.IOException; 7 | 8 | import okhttp3.Response; 9 | 10 | /** 11 | * Created by zhy on 15/12/14. 12 | */ 13 | public abstract class UserCallback extends Callback 14 | { 15 | @Override 16 | public User parseNetworkResponse(Response response, int id) throws IOException 17 | { 18 | String string = response.body().string(); 19 | User user = new Gson().fromJson(string, User.class); 20 | return user; 21 | } 22 | 23 | 24 | } 25 | -------------------------------------------------------------------------------- /sample-okhttp/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 11 | 12 | 15 | 16 | 17 |