├── .gitignore ├── LICENSE ├── OkHttpManager.iml ├── OkHttpPlus.iml ├── README.md ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── library ├── .gitignore ├── build.gradle ├── library.iml ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── zhy │ │ └── http │ │ └── okhttp │ │ └── ApplicationTest.java │ └── main │ ├── AndroidManifest.xml │ └── java │ └── com │ └── socks │ └── okhttp │ └── plus │ ├── Model │ └── Progress.java │ ├── OkHttpProxy.java │ ├── body │ ├── BodyWrapper.java │ ├── RequestProgressBody.java │ └── ResponseProgressBody.java │ ├── builder │ ├── GetRequestBuilder.java │ ├── PostRequestBuilder.java │ ├── RequestBuilder.java │ └── UploadRequestBuilder.java │ ├── callback │ └── OkCallback.java │ ├── handler │ ├── ProgressHandler.java │ └── UIHandler.java │ ├── listener │ ├── DownloadListener.java │ ├── ProgressListener.java │ ├── UIProgressListener.java │ └── UploadListener.java │ └── parser │ ├── OkBaseJsonParser.java │ ├── OkBaseParser.java │ ├── OkFileParser.java │ ├── OkJsonParser.java │ └── OkTextParser.java ├── sample ├── .gitignore ├── build.gradle ├── proguard-rules.pro ├── sample.iml └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── zhy │ │ └── sample │ │ └── ApplicationTest.java │ └── main │ ├── AndroidManifest.xml │ ├── assets │ ├── srca.cer │ ├── zhy_client.bks │ └── zhy_server.cer │ ├── java │ └── com │ │ └── socks │ │ └── sample │ │ └── okhttp │ │ ├── MainActivity.java │ │ ├── OkApplication.java │ │ ├── model │ │ ├── Joke.java │ │ └── User.java │ │ ├── parser │ │ └── JokeParser.java │ │ └── util │ │ ├── MyHostnameVerifier.java │ │ ├── MyTrustManager.java │ │ └── TestUrls.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 │ ├── colors.xml │ ├── dimens.xml │ ├── strings.xml │ └── styles.xml ├── server ├── user └── users └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | /.idea 2 | # Built application files 3 | *.apk 4 | *.ap_ 5 | 6 | # Files for the Dalvik VM 7 | *.dex 8 | 9 | # Java class files 10 | *.class 11 | 12 | # Generated files 13 | bin/ 14 | gen/ 15 | 16 | # Gradle files 17 | .gradle/ 18 | build/ 19 | /*/build/ 20 | 21 | # Local configuration file (sdk path, etc) 22 | local.properties 23 | 24 | # Proguard folder generated by Eclipse 25 | proguard/ 26 | 27 | # Log Files 28 | *.log 29 | /OkHttpPlus.iml 30 | /OkHttpManager.iml 31 | /sample/sample.iml 32 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /OkHttpPlus.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | #OkHttpPlus 2 | 3 | OkHttpPlus is a tool for OkHttp 4 | 5 | --- 6 | 7 | OkHttpPlus是OkHttp的一个工具类,主要对Get和Post方法进行了简单封装,所有方法的回调都在UI线程完成,内置了String、JsonObject、JsonArray数据类型的解析器,封装了对小文件下载和文件上传功能,可以实现进度监听,使之满足常见的Http需求。 8 | 9 | 如果满足不了你的需求,请发issuse。 10 | 11 | 中文文档请戳[这里](http://blog.csdn.net/zhaokaiqiang1992/article/details/50016815) 12 | 13 | ##Features 14 | 15 | - More simple use for GET and POST 16 | - CallBack run on the UI Thread 17 | - Support small size file download and upload without other library 18 | - Build in support for JSON Object and JSON Array parse 19 | 20 | ##Update 21 | 22 | - Add sync method,enqueue is Async Method,execute is Sync Method 23 | 24 | ##Sample Usage 25 | 26 | ###Init OkHttpClient 27 | First , you can init the OkHttpClient as usual 28 | 29 | ``` 30 | public class OkApplication extends Application { 31 | 32 | @Override 33 | public void onCreate() { 34 | super.onCreate(); 35 | OkHttpClient okHttpClient = OkHttpProxy.getInstance(); 36 | okHttpClient.setConnectTimeout(10, TimeUnit.SECONDS); 37 | okHttpClient.setReadTimeout(15, TimeUnit.SECONDS); 38 | okHttpClient.setWriteTimeout(15, TimeUnit.SECONDS); } 39 | } 40 | ``` 41 | 42 | ###Get JSON Object And JSON Array 43 | 44 | Use OkJsonParser ,you could get a User Object form json format string. 45 | 46 | ``` 47 | OkHttpProxy.get() 48 | .url(URL_USER) 49 | .tag(this) 50 | .enqueue(new OkCallback(new OkJsonParser() { 51 | }) { 52 | @Override 53 | public void onSuccess(int code, User user) { 54 | tv_response.setText(user.toString()); 55 | } 56 | 57 | @Override 58 | public void onFailure(Throwable e) { 59 | tv_response.setText(e.getMessage()); 60 | } 61 | }); 62 | ``` 63 | 64 | Use OkJsonParser> ,you could get a list of User Object form json format string. 65 | 66 | ``` 67 | OkHttpProxy.get() 68 | .url(URL_USER) 69 | .tag(this) 70 | .enqueue(new OkCallback>(new OkJsonParser>() { 71 | }) { 72 | @Override 73 | public void onSuccess(int code, List users) { 74 | tv_response.setText(users.toString()); 75 | } 76 | 77 | @Override 78 | public void onFailure(Throwable e) { 79 | tv_response.setText(e.getMessage()); 80 | } 81 | }); 82 | ``` 83 | 84 | ###Custom Parser 85 | 86 | By extends for OkJsonParser, you could custom your parser as following . 87 | 88 | ``` 89 | public class JokeParser extends OkJsonParser { 90 | 91 | @Nullable 92 | @Override 93 | public T parse(Response response) throws IOException { 94 | String jsonStr = response.body().string(); 95 | try { 96 | jsonStr = new JSONObject(jsonStr).getJSONArray("comments").toString(); 97 | return mGson.fromJson(jsonStr, new TypeToken>() { 98 | }.getType()); 99 | } catch (JSONException e) { 100 | e.printStackTrace(); 101 | return null; 102 | } 103 | } 104 | } 105 | 106 | ``` 107 | 108 | Then you can use as above. 109 | 110 | ``` 111 | OkHttpProxy.get() 112 | .url(Joke.getRequestUrl(1)) 113 | .tag(this).enqueue(new OkCallback>(new JokeParser()) { 114 | @Override 115 | public void onSuccess(int code, List jokes) { 116 | tv_response.setText(jokes.toString()); 117 | } 118 | 119 | @Override 120 | public void onFailure(Throwable e) { 121 | tv_response.setText(e.getMessage()); 122 | } 123 | }); 124 | ``` 125 | 126 | ###GET String 127 | 128 | Get String by useing OkTextParser. 129 | 130 | ``` 131 | OkHttpProxy.get() 132 | .url(URL_BAIDU) 133 | .tag(this) 134 | .enqueue(new OkCallback(new OkTextParser()) { 135 | @Override 136 | public void onSuccess(int code, String s) { 137 | tv_response.setText(s); 138 | } 139 | 140 | @Override 141 | public void onFailure(Throwable e) { 142 | tv_response.setText(e.getMessage()); 143 | } 144 | }); 145 | ``` 146 | 147 | ###Post 148 | 149 | Post is also very easy. 150 | 151 | ``` 152 | OkHttpProxy.post() 153 | .url(URL_USERS) 154 | .tag(this) 155 | .addParams("name", "zhaokaiqiang") 156 | .addHeader("header", "okhttp") 157 | .enqueue(new OkCallback>(new OkJsonParser>() { 158 | }) { 159 | @Override 160 | public void onSuccess(int code, ArrayList users) { 161 | tv_response.setText(users.toString()); 162 | } 163 | 164 | @Override 165 | public void onFailure(Throwable e) { 166 | tv_response.setText(e.getMessage()); 167 | } 168 | }); 169 | ``` 170 | 171 | ###Upload 172 | 173 | ``` 174 | /** 175 | * Validity period if Token is12 hours, if the Token Invalid,please create it by follow website 176 | * Token website = http://jsfiddle.net/gh/get/extjs/4.2/icattlecoder/jsfiddle/tree/master/uptoken 177 | * AK = IUy4JnOZHP6o-rx9QsGLf9jMTAKfRkL07gNssIDA 178 | * CK = DkfA7gPTNy1k4HWnQynra3qAZhrzp-wmSs15vub6 179 | * BUCKE_NAME = zhaokaiqiang 180 | */ 181 | public void uploadFile(View view) { 182 | 183 | File file = new File(Environment.getExternalStorageDirectory(), "jiandan02.jpg"); 184 | if (!file.exists()) { 185 | Toast.makeText(MainActivity.this, "File not exits!", Toast.LENGTH_SHORT).show(); 186 | return; 187 | } 188 | 189 | Map param = new HashMap<>(); 190 | param.put("token", TOKEN); 191 | Pair pair = new Pair("file", file); 192 | 193 | OkHttpProxy 194 | .upload() 195 | .url(URL_UPLOAD) 196 | .file(pair) 197 | .setParams(param) 198 | .setWriteTimeOut(20) 199 | .start(new UploadListener() { 200 | @Override 201 | public void onSuccess(Response response) { 202 | tv_response.setText("isSuccessful = " + response.isSuccessful() + "\n" + "code = " + response.code()); 203 | } 204 | 205 | @Override 206 | public void onFailure(Exception e) { 207 | tv_response.setText(e.getMessage()); 208 | } 209 | 210 | @Override 211 | public void onUIProgress(Progress progress) { 212 | int pro = (int) ((progress.getCurrentBytes() + 0.0) / progress.getTotalBytes() * 100); 213 | if (pro > 0) { 214 | pb.setProgress(pro); 215 | } 216 | KLog.d("pro = " + pro + " getCurrentBytes = " + progress.getCurrentBytes() + " getTotalBytes = " + progress.getTotalBytes()); 217 | } 218 | }); 219 | } 220 | ``` 221 | 222 | ###Download 223 | 224 | ``` 225 | String desFileDir = Environment.getExternalStorageDirectory().getAbsolutePath(); 226 | OkHttpProxy.download(URL_DOWMLOAD, new DownloadListener(desFileDir, "json.jar") { 227 | 228 | @Override 229 | public void onUIProgress(Progress progress) { 230 | // if the content length is unknow, the progress.getTotalBytes() = -1 231 | int pro = (int) (progress.getCurrentBytes() / progress.getTotalBytes() * 100); 232 | if (pro > 0) { 233 | pb.setProgress(pro); 234 | } 235 | KLog.d("pro = " + pro + " getCurrentBytes = " + progress.getCurrentBytes() + " getTotalBytes = " + progress.getTotalBytes()); 236 | } 237 | 238 | @Override 239 | public void onSuccess(File file) { 240 | tv_response.setText(file.getAbsolutePath()); 241 | } 242 | 243 | @Override 244 | public void onFailure(Exception e) { 245 | tv_response.setText(e.getMessage()); 246 | } 247 | }); 248 | ``` 249 | 250 | ##JCenter 251 | 252 | ``` 253 | compile 'com.github.zhaokaiqiang.okhttpplus:library:1.0.0' 254 | ``` 255 | 256 | 257 | ##Inspiration 258 | 259 | - [okhttp-utils](https://github.com/hongyangAndroid/okhttp-utils) 260 | - [CoreProgres](https://github.com/lizhangqu/CoreProgress) 261 | 262 | ##About me 263 | 264 | - [Android Developer](http://weibo.com/zhaokaiqiang1992) 265 | - [CSDN Blog](http://blog.csdn.net/zhaokaiqiang1992) 266 | 267 | ##License 268 | 269 | ``` 270 | Copyright 2015, 2016 ZhaoKaiQiang 271 | 272 | Licensed under the Apache License, Version 2.0 (the "License"); 273 | you may not use this file except in compliance with the License. 274 | You may obtain a copy of the License at 275 | 276 | http://www.apache.org/licenses/LICENSE-2.0 277 | 278 | Unless required by applicable law or agreed to in writing, software 279 | distributed under the License is distributed on an "AS IS" BASIS, 280 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 281 | See the License for the specific language governing permissions and 282 | limitations under the License. 283 | ``` 284 | -------------------------------------------------------------------------------- /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 | dependencies { 8 | classpath 'com.android.tools.build:gradle:1.2.3' 9 | classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.0' 10 | classpath 'com.github.dcendents:android-maven-plugin:1.2' 11 | 12 | // NOTE: Do not place your application dependencies here; they belong 13 | // in the individual module build.gradle files 14 | } 15 | } 16 | 17 | allprojects { 18 | repositories { 19 | jcenter() 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /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/ZhaoKaiQiang/OkHttpPlus/d1591644464af03332628ade2cb349af25ef5d74/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Sat Nov 07 14:53:41 GMT+08:00 2015 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.2.1-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 | -------------------------------------------------------------------------------- /library/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /library/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | apply plugin: 'com.github.dcendents.android-maven' 3 | apply plugin: 'com.jfrog.bintray' 4 | 5 | android { 6 | compileSdkVersion 23 7 | buildToolsVersion '23.0.2' 8 | defaultConfig { 9 | minSdkVersion 9 10 | targetSdkVersion 23 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 | dependencies { 23 | compile 'com.squareup.okhttp3:okhttp:3.0.0-RC1' 24 | compile 'com.google.code.gson:gson:2.4' 25 | compile 'com.squareup.okio:okio:1.5.0' 26 | } 27 | 28 | version = "1.0.0" 29 | def siteUrl = 'https://github.com/ZhaoKaiQiang/OkHttpPlus' 30 | def gitUrl = 'https://github.com/ZhaoKaiQiang/OkHttpPlus.git' 31 | group = "com.github.zhaokaiqiang.okhttpplus" 32 | install { 33 | repositories.mavenInstaller { 34 | pom { 35 | project { 36 | packaging 'aar' 37 | name 'OkHttp Tool' 38 | url siteUrl 39 | licenses { 40 | license { 41 | name 'The Apache Software License, Version 2.0' 42 | url 'http://www.apache.org/licenses/LICENSE-2.0.txt' 43 | } 44 | } 45 | developers { 46 | developer { 47 | id 'zhaokaiqiang' 48 | name 'ZhaoKaiQiang' 49 | email '419927089@qq.com' 50 | } 51 | } 52 | scm { 53 | connection gitUrl 54 | developerConnection gitUrl 55 | url siteUrl 56 | } 57 | } 58 | } 59 | } 60 | } 61 | task sourcesJar(type: Jar) { 62 | from android.sourceSets.main.java.srcDirs 63 | classifier = 'sources' 64 | } 65 | task javadoc(type: Javadoc) { 66 | source = android.sourceSets.main.java.srcDirs 67 | classpath += project.files(android.getBootClasspath().join(File.pathSeparator)) 68 | } 69 | task javadocJar(type: Jar, dependsOn: javadoc) { 70 | classifier = 'javadoc' 71 | from javadoc.destinationDir 72 | } 73 | artifacts { 74 | archives javadocJar 75 | archives sourcesJar 76 | } 77 | 78 | //create jar 79 | task clearJar(type: Delete) { 80 | delete '../okhttpplus.jar' 81 | } 82 | 83 | task makeJar(type: Copy) { 84 | from('build/intermediates/bundles/release/') 85 | into('../') 86 | include('classes.jar') 87 | rename ('classes.jar', 'okhttpplus.jar') 88 | } 89 | 90 | makeJar.dependsOn(clearJar, build) 91 | 92 | Properties properties = new Properties() 93 | properties.load(project.rootProject.file('local.properties').newDataInputStream()) 94 | bintray { 95 | user = properties.getProperty("bintray.user") 96 | key = properties.getProperty("bintray.apikey") 97 | configurations = ['archives'] 98 | pkg { 99 | repo = "maven" 100 | name = "okhttp-plus" 101 | websiteUrl = siteUrl 102 | vcsUrl = gitUrl 103 | licenses = ["Apache-2.0"] 104 | publish = true 105 | } 106 | } -------------------------------------------------------------------------------- /library/library.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 8 | 9 | 10 | 11 | 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 | -------------------------------------------------------------------------------- /library/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 | -------------------------------------------------------------------------------- /library/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 | } -------------------------------------------------------------------------------- /library/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /library/src/main/java/com/socks/okhttp/plus/Model/Progress.java: -------------------------------------------------------------------------------- 1 | package com.socks.okhttp.plus.model; 2 | 3 | import java.io.Serializable; 4 | 5 | public class Progress implements Serializable { 6 | 7 | private long currentBytes; 8 | private long totalBytes; 9 | private boolean isFinish; 10 | 11 | public Progress(long currentBytes, long totalBytes, boolean isFinish) { 12 | this.currentBytes = currentBytes; 13 | this.totalBytes = totalBytes; 14 | this.isFinish = isFinish; 15 | } 16 | 17 | public long getCurrentBytes() { 18 | return currentBytes; 19 | } 20 | 21 | public long getTotalBytes() { 22 | return totalBytes; 23 | } 24 | 25 | public boolean isFinish() { 26 | return isFinish; 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /library/src/main/java/com/socks/okhttp/plus/OkHttpProxy.java: -------------------------------------------------------------------------------- 1 | package com.socks.okhttp.plus; 2 | 3 | import com.socks.okhttp.plus.body.BodyWrapper; 4 | import com.socks.okhttp.plus.builder.GetRequestBuilder; 5 | import com.socks.okhttp.plus.builder.PostRequestBuilder; 6 | import com.socks.okhttp.plus.builder.UploadRequestBuilder; 7 | import com.socks.okhttp.plus.listener.DownloadListener; 8 | 9 | import okhttp3.Call; 10 | import okhttp3.Dispatcher; 11 | import okhttp3.OkHttpClient; 12 | import okhttp3.Request; 13 | 14 | /** 15 | * Created by zhaokaiqiang on 15/11/22. 16 | */ 17 | public class OkHttpProxy { 18 | 19 | private static OkHttpClient mHttpClient; 20 | 21 | private static OkHttpClient init() { 22 | synchronized (OkHttpProxy.class) { 23 | if (mHttpClient == null) { 24 | mHttpClient = new OkHttpClient(); 25 | } 26 | } 27 | return mHttpClient; 28 | } 29 | 30 | public static OkHttpClient getInstance() { 31 | return mHttpClient == null ? init() : mHttpClient; 32 | } 33 | 34 | public static void setInstance(OkHttpClient okHttpClient) { 35 | OkHttpProxy.mHttpClient = okHttpClient; 36 | } 37 | 38 | public static GetRequestBuilder get() { 39 | return new GetRequestBuilder(); 40 | } 41 | 42 | public static PostRequestBuilder post() { 43 | return new PostRequestBuilder(); 44 | } 45 | 46 | public static Call download(String url, DownloadListener downloadListener) { 47 | Request request = new Request.Builder().url(url).build(); 48 | Call call = BodyWrapper.addProgressResponseListener(getInstance(), downloadListener).newCall(request); 49 | call.enqueue(downloadListener); 50 | return call; 51 | } 52 | 53 | /** 54 | * default time out is 30 min 55 | */ 56 | public static UploadRequestBuilder upload() { 57 | return new UploadRequestBuilder(); 58 | } 59 | 60 | public static void cancel(Object tag) { 61 | Dispatcher dispatcher = getInstance().dispatcher(); 62 | for (Call call : dispatcher.queuedCalls()) { 63 | if (tag.equals(call.request().tag())) { 64 | call.cancel(); 65 | } 66 | } 67 | for (Call call : dispatcher.runningCalls()) { 68 | if (tag.equals(call.request().tag())) { 69 | call.cancel(); 70 | } 71 | } 72 | } 73 | 74 | 75 | } 76 | -------------------------------------------------------------------------------- /library/src/main/java/com/socks/okhttp/plus/body/BodyWrapper.java: -------------------------------------------------------------------------------- 1 | package com.socks.okhttp.plus.body; 2 | 3 | import com.socks.okhttp.plus.listener.ProgressListener; 4 | import okhttp3.Interceptor; 5 | import okhttp3.OkHttpClient; 6 | import okhttp3.RequestBody; 7 | import okhttp3.Response; 8 | 9 | import java.io.IOException; 10 | 11 | public class BodyWrapper { 12 | 13 | public static OkHttpClient addProgressResponseListener(OkHttpClient client, final ProgressListener progressListener) { 14 | return client.newBuilder() 15 | .addNetworkInterceptor(new Interceptor() { 16 | @Override 17 | public Response intercept(Chain chain) throws IOException { 18 | Response originalResponse = chain.proceed(chain.request()); 19 | return originalResponse.newBuilder() 20 | .body(new ResponseProgressBody(originalResponse.body(), progressListener)) 21 | .build(); 22 | } 23 | }).build(); 24 | } 25 | 26 | public static RequestProgressBody addProgressRequestListener(RequestBody requestBody, ProgressListener progressRequestListener) { 27 | return new RequestProgressBody(requestBody, progressRequestListener); 28 | } 29 | } -------------------------------------------------------------------------------- /library/src/main/java/com/socks/okhttp/plus/body/RequestProgressBody.java: -------------------------------------------------------------------------------- 1 | package com.socks.okhttp.plus.body; 2 | 3 | import com.socks.okhttp.plus.listener.ProgressListener; 4 | import com.socks.okhttp.plus.model.Progress; 5 | import okhttp3.MediaType; 6 | import okhttp3.RequestBody; 7 | 8 | import java.io.IOException; 9 | 10 | import okio.Buffer; 11 | import okio.BufferedSink; 12 | import okio.ForwardingSink; 13 | import okio.Okio; 14 | import okio.Sink; 15 | 16 | /** 17 | * Created by zhaokaiqiang on 15/11/23. 18 | */ 19 | public class RequestProgressBody extends RequestBody { 20 | 21 | private final RequestBody requestBody; 22 | private final ProgressListener progressListener; 23 | private BufferedSink bufferedSink; 24 | 25 | public RequestProgressBody(RequestBody requestBody, ProgressListener progressListener) { 26 | this.requestBody = requestBody; 27 | this.progressListener = progressListener; 28 | } 29 | 30 | public MediaType contentType() { 31 | return requestBody.contentType(); 32 | } 33 | 34 | @Override 35 | public long contentLength() throws IOException { 36 | return requestBody.contentLength(); 37 | } 38 | 39 | @Override 40 | public void writeTo(BufferedSink sink) throws IOException { 41 | if (bufferedSink == null) { 42 | bufferedSink = Okio.buffer(sink(sink)); 43 | } 44 | requestBody.writeTo(bufferedSink); 45 | bufferedSink.flush(); 46 | } 47 | 48 | private Sink sink(Sink sink) { 49 | return new ForwardingSink(sink) { 50 | long bytesWritten = 0L; 51 | long contentLength = 0L; 52 | 53 | @Override 54 | public void write(Buffer source, long byteCount) throws IOException { 55 | super.write(source, byteCount); 56 | if (contentLength == 0) { 57 | contentLength = contentLength(); 58 | } 59 | bytesWritten += byteCount; 60 | if (progressListener != null) { 61 | progressListener.onProgress(new Progress(bytesWritten, contentLength, bytesWritten == contentLength)); 62 | } 63 | } 64 | }; 65 | } 66 | } -------------------------------------------------------------------------------- /library/src/main/java/com/socks/okhttp/plus/body/ResponseProgressBody.java: -------------------------------------------------------------------------------- 1 | package com.socks.okhttp.plus.body; 2 | 3 | import com.socks.okhttp.plus.listener.ProgressListener; 4 | import com.socks.okhttp.plus.model.Progress; 5 | import okhttp3.MediaType; 6 | import okhttp3.ResponseBody; 7 | 8 | import java.io.IOException; 9 | 10 | import okio.Buffer; 11 | import okio.BufferedSource; 12 | import okio.ForwardingSource; 13 | import okio.Okio; 14 | import okio.Source; 15 | 16 | /** 17 | * Created by zhaokaiqiang on 15/11/23. 18 | */ 19 | public class ResponseProgressBody extends ResponseBody { 20 | 21 | private final ResponseBody mResponseBody; 22 | private final ProgressListener mProgressListener; 23 | private BufferedSource bufferedSource; 24 | 25 | public ResponseProgressBody(ResponseBody responseBody, ProgressListener progressListener) { 26 | this.mResponseBody = responseBody; 27 | this.mProgressListener = progressListener; 28 | } 29 | 30 | @Override 31 | public MediaType contentType() { 32 | return mResponseBody.contentType(); 33 | } 34 | 35 | @Override 36 | public long contentLength() { 37 | return mResponseBody.contentLength(); 38 | } 39 | 40 | @Override 41 | public BufferedSource source() { 42 | if (bufferedSource == null) { 43 | bufferedSource = Okio.buffer(source(mResponseBody.source())); 44 | } 45 | return bufferedSource; 46 | } 47 | 48 | private Source source(Source source) { 49 | 50 | return new ForwardingSource(source) { 51 | 52 | long totalBytesRead; 53 | 54 | @Override 55 | public long read(Buffer sink, long byteCount) throws IOException { 56 | long bytesRead = super.read(sink, byteCount); 57 | totalBytesRead += ((bytesRead != -1) ? bytesRead : 0); 58 | if (mProgressListener != null) { 59 | mProgressListener.onProgress(new Progress(totalBytesRead, mResponseBody.contentLength(), bytesRead == -1)); 60 | } 61 | return bytesRead; 62 | } 63 | }; 64 | } 65 | } -------------------------------------------------------------------------------- /library/src/main/java/com/socks/okhttp/plus/builder/GetRequestBuilder.java: -------------------------------------------------------------------------------- 1 | package com.socks.okhttp.plus.builder; 2 | 3 | import android.text.TextUtils; 4 | 5 | import com.socks.okhttp.plus.OkHttpProxy; 6 | import com.socks.okhttp.plus.callback.OkCallback; 7 | import okhttp3.Call; 8 | import okhttp3.Callback; 9 | import okhttp3.Request; 10 | import okhttp3.Response; 11 | 12 | import java.io.IOException; 13 | import java.util.HashMap; 14 | import java.util.Map; 15 | 16 | /** 17 | * Created by zhaokaiqiang on 15/11/24. 18 | */ 19 | public class GetRequestBuilder extends RequestBuilder { 20 | 21 | public GetRequestBuilder url(String url) { 22 | this.url = url; 23 | return this; 24 | } 25 | 26 | public GetRequestBuilder setParams(Map params) { 27 | this.params = params; 28 | return this; 29 | } 30 | 31 | public GetRequestBuilder addParams(String key, String value) { 32 | if (params == null) { 33 | params = new HashMap<>(); 34 | } 35 | params.put(key, value); 36 | return this; 37 | } 38 | 39 | public GetRequestBuilder tag(Object tag) { 40 | this.tag = tag; 41 | return this; 42 | } 43 | 44 | @Override 45 | public Call enqueue(Callback callback) { 46 | 47 | if (TextUtils.isEmpty(url)) { 48 | throw new IllegalArgumentException("url can not be null !"); 49 | } 50 | 51 | Request.Builder builder = new Request.Builder().url(url); 52 | 53 | if (tag != null) { 54 | builder.tag(tag); 55 | } 56 | 57 | if (params != null && params.size() > 0) { 58 | url = appendParams(url, params); 59 | } 60 | 61 | Request request = builder.build(); 62 | 63 | if (callback instanceof OkCallback) { 64 | ((OkCallback) callback).onStart(); 65 | } 66 | 67 | Call call = OkHttpProxy.getInstance().newCall(request); 68 | call.enqueue(callback); 69 | return call; 70 | } 71 | 72 | @Override 73 | public Response execute() throws IOException { 74 | 75 | if (TextUtils.isEmpty(url)) { 76 | throw new IllegalArgumentException("url can not be null !"); 77 | } 78 | 79 | Request.Builder builder = new Request.Builder().url(url); 80 | 81 | if (tag != null) { 82 | builder.tag(tag); 83 | } 84 | 85 | if (params != null && params.size() > 0) { 86 | url = appendParams(url, params); 87 | } 88 | 89 | Request request = builder.build(); 90 | 91 | Call call = OkHttpProxy.getInstance().newCall(request); 92 | return call.execute(); 93 | } 94 | 95 | } 96 | -------------------------------------------------------------------------------- /library/src/main/java/com/socks/okhttp/plus/builder/PostRequestBuilder.java: -------------------------------------------------------------------------------- 1 | package com.socks.okhttp.plus.builder; 2 | 3 | import android.text.TextUtils; 4 | 5 | import com.socks.okhttp.plus.OkHttpProxy; 6 | import com.socks.okhttp.plus.callback.OkCallback; 7 | import okhttp3.Call; 8 | import okhttp3.Callback; 9 | import okhttp3.FormBody; 10 | import okhttp3.FormBody.Builder; 11 | import okhttp3.Request; 12 | import okhttp3.Response; 13 | 14 | import java.io.IOException; 15 | import java.util.IdentityHashMap; 16 | import java.util.Map; 17 | 18 | /** 19 | * Created by zhaokaiqiang on 15/11/24. 20 | */ 21 | public class PostRequestBuilder extends RequestBuilder { 22 | 23 | private Map headers; 24 | 25 | public PostRequestBuilder url(String url) { 26 | this.url = url; 27 | return this; 28 | } 29 | 30 | public PostRequestBuilder setParams(Map params) { 31 | this.params = params; 32 | return this; 33 | } 34 | 35 | public PostRequestBuilder addParams(String key, String value) { 36 | if (params == null) { 37 | params = new IdentityHashMap<>(); 38 | } 39 | params.put(key, value); 40 | return this; 41 | } 42 | 43 | public PostRequestBuilder headers(Map headers) { 44 | this.headers = headers; 45 | return this; 46 | } 47 | 48 | public PostRequestBuilder addHeader(String key, String values) { 49 | if (headers == null) { 50 | headers = new IdentityHashMap<>(); 51 | } 52 | headers.put(key, values); 53 | return this; 54 | } 55 | 56 | public PostRequestBuilder tag(Object tag) { 57 | this.tag = tag; 58 | return this; 59 | } 60 | 61 | 62 | @Override 63 | public Call enqueue(Callback callback) { 64 | 65 | if (TextUtils.isEmpty(url)) { 66 | throw new IllegalArgumentException("url can not be null !"); 67 | } 68 | 69 | Request.Builder builder = new Request.Builder().url(url); 70 | if (tag != null) { 71 | builder.tag(tag); 72 | } 73 | FormBody.Builder encodingBuilder = new FormBody.Builder(); 74 | appendParams(encodingBuilder, params); 75 | appendHeaders(builder, headers); 76 | builder.post(encodingBuilder.build()); 77 | Request request = builder.build(); 78 | 79 | if (callback instanceof OkCallback) { 80 | ((OkCallback) callback).onStart(); 81 | } 82 | Call call = OkHttpProxy.getInstance().newCall(request); 83 | call.enqueue(callback); 84 | return call; 85 | } 86 | 87 | @Override 88 | public Response execute() throws IOException { 89 | if (TextUtils.isEmpty(url)) { 90 | throw new IllegalArgumentException("url can not be null !"); 91 | } 92 | 93 | Request.Builder builder = new Request.Builder().url(url); 94 | if (tag != null) { 95 | builder.tag(tag); 96 | } 97 | FormBody.Builder encodingBuilder = new FormBody.Builder(); 98 | appendParams(encodingBuilder, params); 99 | appendHeaders(builder, headers); 100 | builder.post(encodingBuilder.build()); 101 | Request request = builder.build(); 102 | 103 | Call call = OkHttpProxy.getInstance().newCall(request); 104 | return call.execute(); 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /library/src/main/java/com/socks/okhttp/plus/builder/RequestBuilder.java: -------------------------------------------------------------------------------- 1 | package com.socks.okhttp.plus.builder; 2 | 3 | import okhttp3.Call; 4 | import okhttp3.Callback; 5 | import okhttp3.FormBody; 6 | import okhttp3.FormBody.Builder; 7 | import okhttp3.Headers; 8 | import okhttp3.Request; 9 | import okhttp3.Response; 10 | 11 | import java.io.IOException; 12 | import java.util.Map; 13 | 14 | /** 15 | * Created by zhaokaiqiang on 15/11/24. 16 | */ 17 | public abstract class RequestBuilder { 18 | 19 | protected String url; 20 | protected Map params; 21 | protected Object tag; 22 | 23 | abstract Call enqueue(Callback callback); 24 | 25 | abstract Response execute() throws IOException; 26 | 27 | protected void appendHeaders(Request.Builder builder, Map headers) { 28 | Headers.Builder headerBuilder = new Headers.Builder(); 29 | if (headers == null || headers.isEmpty()) return; 30 | 31 | for (String key : headers.keySet()) { 32 | headerBuilder.add(key, headers.get(key)); 33 | } 34 | builder.headers(headerBuilder.build()); 35 | } 36 | 37 | protected void appendParams(FormBody.Builder builder, Map params) { 38 | 39 | if (params != null && !params.isEmpty()) { 40 | for (String key : params.keySet()) { 41 | builder.add(key, params.get(key)); 42 | } 43 | } 44 | } 45 | 46 | protected String appendParams(String url, Map params) { 47 | StringBuilder sb = new StringBuilder(); 48 | sb.append(url + "?"); 49 | if (params != null && !params.isEmpty()) { 50 | for (String key : params.keySet()) { 51 | sb.append(key).append("=").append(params.get(key)).append("&"); 52 | } 53 | } 54 | 55 | sb = sb.deleteCharAt(sb.length() - 1); 56 | return sb.toString(); 57 | } 58 | 59 | } 60 | -------------------------------------------------------------------------------- /library/src/main/java/com/socks/okhttp/plus/builder/UploadRequestBuilder.java: -------------------------------------------------------------------------------- 1 | package com.socks.okhttp.plus.builder; 2 | 3 | import android.util.Pair; 4 | 5 | import com.socks.okhttp.plus.OkHttpProxy; 6 | import com.socks.okhttp.plus.body.BodyWrapper; 7 | import com.socks.okhttp.plus.listener.UploadListener; 8 | import okhttp3.Call; 9 | import okhttp3.Callback; 10 | import okhttp3.Headers; 11 | import okhttp3.MediaType; 12 | import okhttp3.MultipartBody; 13 | import okhttp3.MultipartBody.Builder; 14 | import okhttp3.OkHttpClient; 15 | import okhttp3.Request; 16 | import okhttp3.RequestBody; 17 | import okhttp3.Response; 18 | 19 | import java.io.File; 20 | import java.io.IOException; 21 | import java.net.FileNameMap; 22 | import java.net.URLConnection; 23 | import java.util.IdentityHashMap; 24 | import java.util.Map; 25 | import java.util.concurrent.TimeUnit; 26 | 27 | /** 28 | * Created by zhaokaiqiang on 15/11/24. 29 | */ 30 | public class UploadRequestBuilder extends RequestBuilder { 31 | 32 | private static final int DEFAULT_TIME_OUT = 30; 33 | 34 | private int connectTimeOut; 35 | private int writeTimeOut; 36 | private int readTimeOut; 37 | private Pair file; 38 | private Map headers; 39 | 40 | public UploadRequestBuilder file(Pair file) { 41 | this.file = file; 42 | return this; 43 | } 44 | 45 | public UploadRequestBuilder url(String url) { 46 | this.url = url; 47 | return this; 48 | } 49 | 50 | public UploadRequestBuilder setParams(Map params) { 51 | this.params = params; 52 | return this; 53 | } 54 | 55 | public UploadRequestBuilder addParams(String key, String value) { 56 | if (params == null) { 57 | params = new IdentityHashMap<>(); 58 | } 59 | params.put(key, value); 60 | return this; 61 | } 62 | 63 | public UploadRequestBuilder headers(Map headers) { 64 | this.headers = headers; 65 | return this; 66 | } 67 | 68 | public UploadRequestBuilder addHeader(String key, String values) { 69 | if (headers == null) { 70 | headers = new IdentityHashMap<>(); 71 | } 72 | headers.put(key, values); 73 | return this; 74 | } 75 | 76 | public UploadRequestBuilder tag(Object tag) { 77 | this.tag = tag; 78 | return this; 79 | } 80 | 81 | /** 82 | * @param connectTimeOut unit is minute 83 | * @return 84 | */ 85 | public UploadRequestBuilder setConnectTimeOut(int connectTimeOut) { 86 | this.connectTimeOut = connectTimeOut; 87 | return this; 88 | } 89 | 90 | /** 91 | * @param writeTimeOut unit is minute 92 | * @return 93 | */ 94 | public UploadRequestBuilder setWriteTimeOut(int writeTimeOut) { 95 | this.writeTimeOut = writeTimeOut; 96 | return this; 97 | } 98 | 99 | /** 100 | * @param readTimeOut unit is minute 101 | * @return 102 | */ 103 | public UploadRequestBuilder setReadTimeOut(int readTimeOut) { 104 | this.readTimeOut = readTimeOut; 105 | return this; 106 | } 107 | 108 | public Call start(UploadListener uploadListener) { 109 | 110 | MultipartBody.Builder multipartBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM); 111 | addParams(multipartBuilder, params); 112 | addFiles(multipartBuilder, file); 113 | 114 | Request.Builder builder = new Request.Builder(); 115 | appendHeaders(builder, headers); 116 | Request request = builder.url(url).post(BodyWrapper.addProgressRequestListener(multipartBuilder.build(), uploadListener)).build(); 117 | 118 | OkHttpClient.Builder clientBuilder = OkHttpProxy.getInstance().newBuilder(); 119 | 120 | if (connectTimeOut > 0) { 121 | clientBuilder.connectTimeout(connectTimeOut, TimeUnit.MINUTES); 122 | } else { 123 | clientBuilder.connectTimeout(DEFAULT_TIME_OUT, TimeUnit.MINUTES); 124 | } 125 | 126 | if (writeTimeOut > 0) { 127 | clientBuilder.writeTimeout(writeTimeOut, TimeUnit.MINUTES); 128 | } else { 129 | clientBuilder.writeTimeout(DEFAULT_TIME_OUT, TimeUnit.MINUTES); 130 | } 131 | 132 | if (readTimeOut > 0) { 133 | clientBuilder.readTimeout(readTimeOut, TimeUnit.MINUTES); 134 | } else { 135 | clientBuilder.readTimeout(DEFAULT_TIME_OUT, TimeUnit.MINUTES); 136 | } 137 | 138 | OkHttpClient clone = clientBuilder.build(); 139 | Call call = clone.newCall(request); 140 | call.enqueue(uploadListener); 141 | return call; 142 | } 143 | 144 | 145 | private static void addParams(MultipartBody.Builder builder, Map params) { 146 | if (params != null && !params.isEmpty()) { 147 | for (String key : params.keySet()) { 148 | builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + key + "\""), 149 | RequestBody.create(null, params.get(key))); 150 | } 151 | } 152 | } 153 | 154 | private static void addFiles(MultipartBody.Builder builder, Pair... files) { 155 | if (files != null) { 156 | RequestBody fileBody; 157 | for (int i = 0; i < files.length; i++) { 158 | Pair filePair = files[i]; 159 | String fileKeyName = filePair.first; 160 | File file = filePair.second; 161 | String fileName = file.getName(); 162 | fileBody = RequestBody.create(MediaType.parse(guessMimeType(fileName)), file); 163 | builder.addPart(Headers.of("Content-Disposition", 164 | "form-data; name=\"" + fileKeyName + "\"; filename=\"" + fileName + "\""), 165 | fileBody); 166 | } 167 | } else { 168 | throw new IllegalArgumentException("File can not be null"); 169 | } 170 | } 171 | 172 | private static String guessMimeType(String path) { 173 | FileNameMap fileNameMap = URLConnection.getFileNameMap(); 174 | String contentTypeFor = fileNameMap.getContentTypeFor(path); 175 | if (contentTypeFor == null) { 176 | contentTypeFor = "application/octet-stream"; 177 | } 178 | return contentTypeFor; 179 | } 180 | 181 | @Override 182 | Call enqueue(Callback callback) { 183 | return null; 184 | } 185 | 186 | @Override 187 | Response execute() throws IOException { 188 | return null; 189 | } 190 | 191 | } 192 | -------------------------------------------------------------------------------- /library/src/main/java/com/socks/okhttp/plus/callback/OkCallback.java: -------------------------------------------------------------------------------- 1 | package com.socks.okhttp.plus.callback; 2 | 3 | import android.os.Handler; 4 | import android.os.Looper; 5 | 6 | import com.socks.okhttp.plus.parser.OkBaseParser; 7 | 8 | import java.io.IOException; 9 | 10 | import okhttp3.Callback; 11 | import okhttp3.Request; 12 | import okhttp3.Response; 13 | 14 | /** 15 | * Created by zhaokaiqiang on 15/11/22. 16 | */ 17 | public abstract class OkCallback implements Callback { 18 | 19 | private static Handler mHandler = new Handler(Looper.getMainLooper()); 20 | 21 | private OkBaseParser mParser; 22 | 23 | public OkCallback(OkBaseParser mParser) { 24 | if (mParser == null) { 25 | throw new IllegalArgumentException("Parser can't be null"); 26 | } 27 | this.mParser = mParser; 28 | } 29 | 30 | @Override 31 | public void onFailure(Request request, final IOException e) { 32 | mHandler.post(new Runnable() { 33 | @Override 34 | public void run() { 35 | onFailure(e); 36 | } 37 | }); 38 | } 39 | 40 | @Override 41 | public void onResponse(final Response response) { 42 | final int code = mParser.getCode(); 43 | try { 44 | final T t = mParser.parseResponse(response); 45 | if (response.isSuccessful() && t != null) { 46 | mHandler.post(new Runnable() { 47 | @Override 48 | public void run() { 49 | onSuccess(code, t); 50 | } 51 | }); 52 | } else { 53 | mHandler.post(new Runnable() { 54 | @Override 55 | public void run() { 56 | onFailure(new Exception(Integer.toString(code))); 57 | } 58 | }); 59 | } 60 | } catch (final Exception e) { 61 | mHandler.post(new Runnable() { 62 | @Override 63 | public void run() { 64 | onFailure(e); 65 | } 66 | }); 67 | } 68 | } 69 | 70 | public abstract void onSuccess(int code, T t); 71 | 72 | public abstract void onFailure(Throwable e); 73 | 74 | public void onStart() { 75 | } 76 | 77 | } -------------------------------------------------------------------------------- /library/src/main/java/com/socks/okhttp/plus/handler/ProgressHandler.java: -------------------------------------------------------------------------------- 1 | package com.socks.okhttp.plus.handler; 2 | 3 | import android.os.Handler; 4 | import android.os.Looper; 5 | import android.os.Message; 6 | 7 | import com.socks.okhttp.plus.listener.UIProgressListener; 8 | import com.socks.okhttp.plus.model.Progress; 9 | 10 | import java.lang.ref.WeakReference; 11 | 12 | public abstract class ProgressHandler extends Handler { 13 | 14 | public static final int UPDATE = 0x01; 15 | public static final int START = 0x02; 16 | public static final int FINISH = 0x03; 17 | 18 | private final WeakReference mListenerWeakRef; 19 | 20 | public ProgressHandler(UIProgressListener uiProgressListener) { 21 | super(Looper.getMainLooper()); 22 | mListenerWeakRef = new WeakReference<>(uiProgressListener); 23 | } 24 | 25 | @Override 26 | public void handleMessage(Message msg) { 27 | UIProgressListener listener = mListenerWeakRef.get(); 28 | switch (msg.what) { 29 | case UPDATE: 30 | if (listener != null) 31 | progress(listener, (Progress) msg.obj); 32 | break; 33 | case START: 34 | if (mListenerWeakRef.get() != null) 35 | start(listener); 36 | break; 37 | case FINISH: 38 | if (mListenerWeakRef.get() != null) 39 | finish(listener); 40 | break; 41 | default: 42 | super.handleMessage(msg); 43 | break; 44 | } 45 | } 46 | 47 | public abstract void start(UIProgressListener listener); 48 | 49 | public abstract void progress(UIProgressListener listener, Progress progress); 50 | 51 | public abstract void finish(UIProgressListener listener); 52 | } 53 | -------------------------------------------------------------------------------- /library/src/main/java/com/socks/okhttp/plus/handler/UIHandler.java: -------------------------------------------------------------------------------- 1 | package com.socks.okhttp.plus.handler; 2 | 3 | import com.socks.okhttp.plus.listener.UIProgressListener; 4 | import com.socks.okhttp.plus.model.Progress; 5 | 6 | public class UIHandler extends ProgressHandler { 7 | 8 | public UIHandler(UIProgressListener uiProgressListener) { 9 | super(uiProgressListener); 10 | } 11 | 12 | @Override 13 | public void start(UIProgressListener listener) { 14 | listener.onUIStart(); 15 | } 16 | 17 | @Override 18 | public void progress(UIProgressListener uiProgressListener, Progress progress) { 19 | uiProgressListener.onUIProgress(progress); 20 | } 21 | 22 | @Override 23 | public void finish(UIProgressListener listener) { 24 | listener.onUIFinish(); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /library/src/main/java/com/socks/okhttp/plus/listener/DownloadListener.java: -------------------------------------------------------------------------------- 1 | package com.socks.okhttp.plus.listener; 2 | 3 | import android.os.Handler; 4 | 5 | import com.socks.okhttp.plus.handler.ProgressHandler; 6 | import com.socks.okhttp.plus.handler.UIHandler; 7 | import com.socks.okhttp.plus.model.Progress; 8 | import okhttp3.Callback; 9 | import okhttp3.Request; 10 | import okhttp3.Response; 11 | 12 | import java.io.File; 13 | import java.io.FileOutputStream; 14 | import java.io.IOException; 15 | import java.io.InputStream; 16 | 17 | public abstract class DownloadListener implements ProgressListener, Callback, UIProgressListener { 18 | 19 | private final Handler mHandler = new UIHandler(this); 20 | private boolean isFirst = true; 21 | private String mDestFileDir; 22 | private String mDestFileName; 23 | 24 | public DownloadListener(String mDestFileDir, String mDestFileName) { 25 | this.mDestFileDir = mDestFileDir; 26 | this.mDestFileName = mDestFileName; 27 | } 28 | 29 | @Override 30 | public void onResponse(final Response response) { 31 | 32 | File file = null; 33 | try { 34 | file = saveFile(response); 35 | } catch (final IOException e) { 36 | mHandler.post(new Runnable() { 37 | @Override 38 | public void run() { 39 | onFailure(e); 40 | } 41 | }); 42 | } 43 | 44 | final File newFile = file; 45 | mHandler.post(new Runnable() { 46 | @Override 47 | public void run() { 48 | onSuccess(newFile); 49 | } 50 | }); 51 | } 52 | 53 | @Override 54 | public void onFailure(Request request, final IOException e) { 55 | mHandler.post(new Runnable() { 56 | @Override 57 | public void run() { 58 | onFailure(e); 59 | } 60 | }); 61 | } 62 | 63 | public abstract void onSuccess(File file); 64 | 65 | public abstract void onFailure(Exception e); 66 | 67 | public File saveFile(Response response) throws IOException { 68 | InputStream is = null; 69 | byte[] buf = new byte[2048]; 70 | int len; 71 | FileOutputStream fos = null; 72 | try { 73 | is = response.body().byteStream(); 74 | File dir = new File(mDestFileDir); 75 | if (!dir.exists()) { 76 | dir.mkdirs(); 77 | } 78 | File file = new File(dir, mDestFileName); 79 | fos = new FileOutputStream(file); 80 | while ((len = is.read(buf)) != -1) { 81 | fos.write(buf, 0, len); 82 | } 83 | fos.flush(); 84 | return file; 85 | } finally { 86 | try { 87 | if (is != null) is.close(); 88 | } catch (IOException e) { 89 | } 90 | try { 91 | if (fos != null) fos.close(); 92 | } catch (IOException e) { 93 | } 94 | } 95 | } 96 | 97 | @Override 98 | public void onProgress(Progress progress) { 99 | 100 | if (!isFirst) { 101 | isFirst = true; 102 | mHandler.obtainMessage(ProgressHandler.START, progress) 103 | .sendToTarget(); 104 | } 105 | 106 | mHandler.obtainMessage(ProgressHandler.UPDATE, 107 | progress) 108 | .sendToTarget(); 109 | 110 | if (progress.isFinish()) { 111 | mHandler.obtainMessage(ProgressHandler.FINISH, 112 | progress) 113 | .sendToTarget(); 114 | } 115 | } 116 | 117 | public abstract void onUIProgress(Progress progress); 118 | 119 | @Override 120 | public void onUIStart() { 121 | } 122 | 123 | @Override 124 | public void onUIFinish() { 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /library/src/main/java/com/socks/okhttp/plus/listener/ProgressListener.java: -------------------------------------------------------------------------------- 1 | package com.socks.okhttp.plus.listener; 2 | 3 | import com.socks.okhttp.plus.model.Progress; 4 | 5 | public interface ProgressListener { 6 | void onProgress(Progress progress); 7 | } -------------------------------------------------------------------------------- /library/src/main/java/com/socks/okhttp/plus/listener/UIProgressListener.java: -------------------------------------------------------------------------------- 1 | package com.socks.okhttp.plus.listener; 2 | 3 | import com.socks.okhttp.plus.model.Progress; 4 | 5 | /** 6 | * Created by zhaokaiqiang on 15/11/23. 7 | */ 8 | public interface UIProgressListener { 9 | 10 | void onUIProgress(Progress progress); 11 | 12 | void onUIStart(); 13 | 14 | void onUIFinish(); 15 | } 16 | -------------------------------------------------------------------------------- /library/src/main/java/com/socks/okhttp/plus/listener/UploadListener.java: -------------------------------------------------------------------------------- 1 | package com.socks.okhttp.plus.listener; 2 | 3 | import android.os.Handler; 4 | 5 | import com.socks.okhttp.plus.handler.ProgressHandler; 6 | import com.socks.okhttp.plus.handler.UIHandler; 7 | import com.socks.okhttp.plus.model.Progress; 8 | import okhttp3.Callback; 9 | import okhttp3.Request; 10 | import okhttp3.Response; 11 | 12 | import java.io.IOException; 13 | 14 | public abstract class UploadListener implements ProgressListener, Callback, UIProgressListener { 15 | 16 | private final Handler mHandler = new UIHandler(this); 17 | private boolean isFirst = true; 18 | 19 | @Override 20 | public void onResponse(final Response response) { 21 | mHandler.post(new Runnable() { 22 | @Override 23 | public void run() { 24 | onSuccess(response); 25 | } 26 | }); 27 | } 28 | 29 | @Override 30 | public void onFailure(Request request, final IOException e) { 31 | mHandler.post(new Runnable() { 32 | @Override 33 | public void run() { 34 | onFailure(e); 35 | } 36 | }); 37 | } 38 | 39 | public abstract void onSuccess(Response response); 40 | 41 | public abstract void onFailure(Exception e); 42 | 43 | @Override 44 | public void onProgress(Progress progress) { 45 | 46 | if (!isFirst) { 47 | isFirst = true; 48 | mHandler.obtainMessage(ProgressHandler.START, progress) 49 | .sendToTarget(); 50 | } 51 | 52 | mHandler.obtainMessage(ProgressHandler.UPDATE, 53 | progress) 54 | .sendToTarget(); 55 | 56 | if (progress.isFinish()) { 57 | mHandler.obtainMessage(ProgressHandler.FINISH, 58 | progress) 59 | .sendToTarget(); 60 | } 61 | } 62 | 63 | public abstract void onUIProgress(Progress progress); 64 | 65 | public void onUIStart() { 66 | } 67 | 68 | public void onUIFinish() { 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /library/src/main/java/com/socks/okhttp/plus/parser/OkBaseJsonParser.java: -------------------------------------------------------------------------------- 1 | package com.socks.okhttp.plus.parser; 2 | 3 | import com.google.gson.internal.$Gson$Types; 4 | import okhttp3.Response; 5 | 6 | import java.io.IOException; 7 | import java.lang.reflect.ParameterizedType; 8 | import java.lang.reflect.Type; 9 | 10 | /** 11 | * Created by zhaokaiqiang on 15/11/23. 12 | */ 13 | public abstract class OkBaseJsonParser extends OkBaseParser { 14 | 15 | public Type mType; 16 | 17 | public OkBaseJsonParser() { 18 | mType = getSuperclassTypeParameter(getClass()); 19 | } 20 | 21 | protected abstract T parse(Response response) throws IOException; 22 | 23 | private static Type getSuperclassTypeParameter(Class subclass) { 24 | Type superclass = subclass.getGenericSuperclass(); 25 | if (superclass instanceof Class) { 26 | throw new RuntimeException("Missing type parameter."); 27 | } 28 | ParameterizedType parameter = (ParameterizedType) superclass; 29 | return $Gson$Types.canonicalize(parameter.getActualTypeArguments()[0]); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /library/src/main/java/com/socks/okhttp/plus/parser/OkBaseParser.java: -------------------------------------------------------------------------------- 1 | package com.socks.okhttp.plus.parser; 2 | 3 | import okhttp3.Response; 4 | 5 | import java.io.IOException; 6 | 7 | /** 8 | * 负责对返回值进行解析,使用策略设计模式 9 | * Created by zhaokaiqiang on 15/11/22. 10 | */ 11 | public abstract class OkBaseParser { 12 | 13 | protected int code; 14 | 15 | protected abstract T parse(Response response) throws IOException; 16 | 17 | public T parseResponse(Response response) throws IOException { 18 | code = response.code(); 19 | return parse(response); 20 | } 21 | 22 | public int getCode() { 23 | return code; 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /library/src/main/java/com/socks/okhttp/plus/parser/OkFileParser.java: -------------------------------------------------------------------------------- 1 | package com.socks.okhttp.plus.parser; 2 | 3 | import okhttp3.Response; 4 | 5 | import java.io.File; 6 | import java.io.FileOutputStream; 7 | import java.io.IOException; 8 | import java.io.InputStream; 9 | 10 | /** 11 | * Created by zhaokaiqiang on 15/11/23. 12 | */ 13 | public class OkFileParser extends OkBaseParser { 14 | 15 | private String mDestFileDir; 16 | private String mDestFileName; 17 | 18 | public OkFileParser(String destFileDir, String destFileName) { 19 | mDestFileDir = destFileDir; 20 | mDestFileName = destFileName; 21 | } 22 | 23 | @Override 24 | protected File parse(Response response) throws IOException { 25 | return saveFile(response); 26 | } 27 | 28 | 29 | public File saveFile(Response response) throws IOException { 30 | InputStream is = null; 31 | byte[] buf = new byte[2048]; 32 | int len; 33 | FileOutputStream fos = null; 34 | try { 35 | is = response.body().byteStream(); 36 | File dir = new File(mDestFileDir); 37 | if (!dir.exists()) { 38 | dir.mkdirs(); 39 | } 40 | File file = new File(dir, mDestFileName); 41 | fos = new FileOutputStream(file); 42 | while ((len = is.read(buf)) != -1) { 43 | fos.write(buf, 0, len); 44 | } 45 | fos.flush(); 46 | return file; 47 | } finally { 48 | try { 49 | if (is != null) is.close(); 50 | } catch (IOException e) { 51 | } 52 | try { 53 | if (fos != null) fos.close(); 54 | } catch (IOException e) { 55 | } 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /library/src/main/java/com/socks/okhttp/plus/parser/OkJsonParser.java: -------------------------------------------------------------------------------- 1 | package com.socks.okhttp.plus.parser; 2 | 3 | import android.os.Build; 4 | 5 | import com.google.gson.Gson; 6 | import com.google.gson.GsonBuilder; 7 | import okhttp3.Response; 8 | 9 | import java.io.IOException; 10 | import java.lang.reflect.Modifier; 11 | 12 | /** 13 | * Created by zhaokaiqiang on 15/11/22. 14 | */ 15 | public abstract class OkJsonParser extends OkBaseJsonParser { 16 | 17 | protected Gson mGson; 18 | 19 | public OkJsonParser() { 20 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 21 | GsonBuilder gsonBuilder = new GsonBuilder() 22 | .excludeFieldsWithModifiers( 23 | Modifier.FINAL, 24 | Modifier.TRANSIENT, 25 | Modifier.STATIC); 26 | mGson = gsonBuilder.create(); 27 | } else { 28 | mGson = new Gson(); 29 | } 30 | } 31 | 32 | @Override 33 | public T parse(Response response) throws IOException { 34 | String body = response.body().string(); 35 | return mGson.fromJson(body, mType); 36 | } 37 | } -------------------------------------------------------------------------------- /library/src/main/java/com/socks/okhttp/plus/parser/OkTextParser.java: -------------------------------------------------------------------------------- 1 | package com.socks.okhttp.plus.parser; 2 | 3 | import okhttp3.Response; 4 | 5 | import java.io.IOException; 6 | 7 | /** 8 | * Created by zhaokaiqiang on 15/11/22. 9 | */ 10 | public class OkTextParser extends OkBaseParser { 11 | 12 | @Override 13 | public String parse(Response response) throws IOException { 14 | 15 | if (response.isSuccessful()) { 16 | return response.body().string(); 17 | } 18 | 19 | return null; 20 | } 21 | } -------------------------------------------------------------------------------- /sample/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /sample/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 23 5 | buildToolsVersion '23.0.2' 6 | 7 | defaultConfig { 8 | applicationId "com.socks.sample.okhttpplus" 9 | minSdkVersion 9 10 | targetSdkVersion 23 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 | dependencies { 23 | compile 'com.android.support:appcompat-v7:23.1.1' 24 | compile 'com.github.zhaokaiqiang.klog:library:1.3.0' 25 | compile 'com.github.zhaokaiqiang.okhttpplus:library:1.0.0' 26 | // compile project(':library') 27 | } -------------------------------------------------------------------------------- /sample/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 | 19 | ##---------------Begin: proguard configuration for Gson ---------- 20 | # Gson uses generic type information stored in a class file when working with fields. Proguard 21 | # removes such information by default, so configure it to keep all of it. 22 | -keepattributes Signature 23 | 24 | 25 | # Gson specific classes 26 | -keep class sun.misc.Unsafe { *; } 27 | #-keep class com.google.gson.stream.** { *; } 28 | 29 | # Application classes that will be serialized/deserialized over Gson 30 | -keep class com.google.gson.examples.android.model.** { *; } 31 | 32 | ##---------------End: proguard configuration for Gson ---------- -------------------------------------------------------------------------------- /sample/sample.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 8 | 9 | 10 | 11 | 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 | -------------------------------------------------------------------------------- /sample/src/androidTest/java/com/zhy/sample/ApplicationTest.java: -------------------------------------------------------------------------------- 1 | package com.zhy.sample; 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/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 15 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /sample/src/main/assets/srca.cer: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ZhaoKaiQiang/OkHttpPlus/d1591644464af03332628ade2cb349af25ef5d74/sample/src/main/assets/srca.cer -------------------------------------------------------------------------------- /sample/src/main/assets/zhy_client.bks: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ZhaoKaiQiang/OkHttpPlus/d1591644464af03332628ade2cb349af25ef5d74/sample/src/main/assets/zhy_client.bks -------------------------------------------------------------------------------- /sample/src/main/assets/zhy_server.cer: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ZhaoKaiQiang/OkHttpPlus/d1591644464af03332628ade2cb349af25ef5d74/sample/src/main/assets/zhy_server.cer -------------------------------------------------------------------------------- /sample/src/main/java/com/socks/sample/okhttp/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.socks.sample.okhttp; 2 | 3 | import android.content.Intent; 4 | import android.net.Uri; 5 | import android.os.Bundle; 6 | import android.os.Environment; 7 | import android.support.v7.app.AppCompatActivity; 8 | import android.util.Pair; 9 | import android.view.Menu; 10 | import android.view.MenuItem; 11 | import android.view.View; 12 | import android.widget.ProgressBar; 13 | import android.widget.TextView; 14 | import android.widget.Toast; 15 | 16 | import com.socks.library.KLog; 17 | import com.socks.okhttp.plus.OkHttpProxy; 18 | import com.socks.okhttp.plus.callback.OkCallback; 19 | import com.socks.okhttp.plus.listener.DownloadListener; 20 | import com.socks.okhttp.plus.listener.UploadListener; 21 | import com.socks.okhttp.plus.model.Progress; 22 | import com.socks.okhttp.plus.parser.OkJsonParser; 23 | import com.socks.okhttp.plus.parser.OkTextParser; 24 | import com.socks.sample.okhttp.model.Joke; 25 | import com.socks.sample.okhttp.model.User; 26 | import com.socks.sample.okhttp.parser.JokeParser; 27 | import com.socks.sample.okhttp.util.TestUrls; 28 | 29 | import java.io.File; 30 | import java.io.IOException; 31 | import java.util.ArrayList; 32 | import java.util.HashMap; 33 | import java.util.List; 34 | import java.util.Map; 35 | 36 | import okhttp3.Response; 37 | 38 | public class MainActivity extends AppCompatActivity implements TestUrls { 39 | 40 | private TextView tv_response; 41 | private ProgressBar pb; 42 | 43 | @Override 44 | protected void onCreate(Bundle savedInstanceState) { 45 | super.onCreate(savedInstanceState); 46 | setContentView(R.layout.activity_main); 47 | tv_response = (TextView) findViewById(R.id.tv_response); 48 | pb = (ProgressBar) findViewById(R.id.pb); 49 | } 50 | 51 | 52 | /////////////////////////////////////////////////////////////////////////// 53 | // Test Code 54 | /////////////////////////////////////////////////////////////////////////// 55 | 56 | public void getUser(View view) { 57 | OkHttpProxy.get() 58 | .url(URL_USER) 59 | .tag(this) 60 | .enqueue(new OkCallback(new OkJsonParser() { 61 | }) { 62 | @Override 63 | public void onSuccess(int code, User user) { 64 | tv_response.setText(user.toString()); 65 | } 66 | 67 | @Override 68 | public void onFailure(Throwable e) { 69 | tv_response.setText(e.getMessage()); 70 | } 71 | }); 72 | } 73 | 74 | public void getUserSync(View view) { 75 | 76 | new Thread(new Runnable() { 77 | @Override 78 | public void run() { 79 | try { 80 | Response response = OkHttpProxy.get() 81 | .url(URL_USER) 82 | .tag(this) 83 | .execute(); 84 | 85 | final User user = new OkJsonParser() { 86 | }.parse(response); 87 | 88 | runOnUiThread(new Runnable() { 89 | @Override 90 | public void run() { 91 | tv_response.setText(user.toString()); 92 | } 93 | }); 94 | 95 | } catch (IOException e) { 96 | e.printStackTrace(); 97 | } 98 | } 99 | }).start(); 100 | } 101 | 102 | public void getUsers(View view) { 103 | OkHttpProxy.get() 104 | .url(URL_USERS) 105 | .tag(this) 106 | .enqueue(new OkCallback>(new OkJsonParser>() { 107 | }) { 108 | @Override 109 | public void onSuccess(int code, List users) { 110 | tv_response.setText(users.toString()); 111 | } 112 | 113 | @Override 114 | public void onFailure(Throwable e) { 115 | tv_response.setText(e.getMessage()); 116 | } 117 | }); 118 | } 119 | 120 | public void getJokes(View view) { 121 | OkHttpProxy.get() 122 | .url(Joke.getRequestUrl(1)) 123 | .tag(this).enqueue(new OkCallback>(new JokeParser>()) { 124 | @Override 125 | public void onSuccess(int code, List jokes) { 126 | tv_response.setText(jokes.toString()); 127 | } 128 | 129 | @Override 130 | public void onFailure(Throwable e) { 131 | tv_response.setText(e.getMessage()); 132 | } 133 | }); 134 | } 135 | 136 | public void getHtml(View view) { 137 | OkHttpProxy.get() 138 | .url(URL_BAIDU) 139 | .tag(this) 140 | .enqueue(new OkCallback(new OkTextParser()) { 141 | @Override 142 | public void onSuccess(int code, String s) { 143 | tv_response.setText(s); 144 | } 145 | 146 | @Override 147 | public void onFailure(Throwable e) { 148 | tv_response.setText(e.getMessage()); 149 | } 150 | }); 151 | } 152 | 153 | public void getHttpsHtml(View view) { 154 | OkHttpProxy.get() 155 | .url(URL_12306) 156 | .tag(this) 157 | .enqueue(new OkCallback(new OkTextParser()) { 158 | @Override 159 | public void onSuccess(int code, String s) { 160 | tv_response.setText(s); 161 | } 162 | 163 | @Override 164 | public void onFailure(Throwable e) { 165 | tv_response.setText(e.getMessage()); 166 | } 167 | }); 168 | } 169 | 170 | public void postUsers(View view) { 171 | 172 | OkHttpProxy 173 | .post() 174 | .url(URL_USERS) 175 | .tag(this) 176 | .addParams("name", "zhaokaiqiang") 177 | .addHeader("header", "okhttp") 178 | .enqueue(new OkCallback>(new OkJsonParser>() { 179 | }) { 180 | @Override 181 | public void onSuccess(int code, ArrayList users) { 182 | tv_response.setText(users.toString()); 183 | } 184 | 185 | @Override 186 | public void onFailure(Throwable e) { 187 | tv_response.setText(e.getMessage()); 188 | } 189 | }); 190 | } 191 | 192 | 193 | /** 194 | * 采用七牛上传接口,Token有效期为12小时,若Token无效,请在下面自行获取 195 | * Token生成网址 http://jsfiddle.net/gh/get/extjs/4.2/icattlecoder/jsfiddle/tree/master/uptoken 196 | *

197 | * AK = IUy4JnOZHP6o-rx9QsGLf9jMTAKfRkL07gNssIDA 198 | * CK = DkfA7gPTNy1k4HWnQynra3qAZhrzp-wmSs15vub6 199 | * BUCKE_NAME = zhaokaiqiang 200 | */ 201 | public void uploadFile(View view) { 202 | 203 | File file = new File(Environment.getExternalStorageDirectory(), "jiandan02.jpg"); 204 | if (!file.exists()) { 205 | Toast.makeText(MainActivity.this, "文件不存在,请修改文件路径", Toast.LENGTH_SHORT).show(); 206 | return; 207 | } 208 | 209 | Map param = new HashMap<>(); 210 | param.put("token", TOKEN); 211 | Pair pair = new Pair("file", file); 212 | 213 | OkHttpProxy 214 | .upload() 215 | .url(URL_UPLOAD) 216 | .file(pair) 217 | .setParams(param) 218 | .setWriteTimeOut(20) 219 | .start(new UploadListener() { 220 | @Override 221 | public void onSuccess(Response response) { 222 | tv_response.setText("isSuccessful = " + response.isSuccessful() + "\n" + "code = " + response.code()); 223 | } 224 | 225 | @Override 226 | public void onFailure(Exception e) { 227 | tv_response.setText(e.getMessage()); 228 | } 229 | 230 | @Override 231 | public void onUIProgress(Progress progress) { 232 | int pro = (int) ((progress.getCurrentBytes() + 0.0) / progress.getTotalBytes() * 100); 233 | if (pro > 0) { 234 | pb.setProgress(pro); 235 | } 236 | KLog.d("pro = " + pro + " getCurrentBytes = " + progress.getCurrentBytes() + " getTotalBytes = " + progress.getTotalBytes()); 237 | } 238 | }); 239 | } 240 | 241 | public void downloadFile(View view) { 242 | 243 | String desFileDir = Environment.getExternalStorageDirectory().getAbsolutePath(); 244 | OkHttpProxy.download(URL_DOWMLOAD, new DownloadListener(desFileDir, "json.jar") { 245 | 246 | @Override 247 | public void onUIProgress(Progress progress) { 248 | //当下载资源长度不可知时,progress.getTotalBytes()为-1,此时不能显示下载进度 249 | int pro = (int) (progress.getCurrentBytes() / progress.getTotalBytes() * 100); 250 | if (pro > 0) { 251 | pb.setProgress(pro); 252 | } 253 | KLog.d("pro = " + pro + " getCurrentBytes = " + progress.getCurrentBytes() + " getTotalBytes = " + progress.getTotalBytes()); 254 | } 255 | 256 | @Override 257 | public void onSuccess(File file) { 258 | tv_response.setText(file.getAbsolutePath()); 259 | } 260 | 261 | @Override 262 | public void onFailure(Exception e) { 263 | tv_response.setText(e.getMessage()); 264 | } 265 | }); 266 | } 267 | 268 | @Override 269 | protected void onDestroy() { 270 | super.onDestroy(); 271 | OkHttpProxy.cancel(this); 272 | } 273 | 274 | /////////////////////////////////////////////////////////////////////////// 275 | // MENU 276 | /////////////////////////////////////////////////////////////////////////// 277 | 278 | @Override 279 | public boolean onCreateOptionsMenu(Menu menu) { 280 | getMenuInflater().inflate(R.menu.menu_main, menu); 281 | return true; 282 | } 283 | 284 | @Override 285 | public boolean onOptionsItemSelected(MenuItem item) { 286 | 287 | switch (item.getItemId()) { 288 | case R.id.action_github: 289 | startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/ZhaoKaiQiang/OkHttpPlus"))); 290 | break; 291 | case R.id.action_csdn: 292 | startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://blog.csdn.net/zhaokaiqiang1992"))); 293 | break; 294 | } 295 | 296 | return super.onOptionsItemSelected(item); 297 | } 298 | 299 | } -------------------------------------------------------------------------------- /sample/src/main/java/com/socks/sample/okhttp/OkApplication.java: -------------------------------------------------------------------------------- 1 | package com.socks.sample.okhttp; 2 | 3 | import android.app.Application; 4 | 5 | import com.socks.okhttp.plus.OkHttpProxy; 6 | import com.socks.sample.okhttp.util.MyHostnameVerifier; 7 | import com.socks.sample.okhttp.util.MyTrustManager; 8 | 9 | import java.security.KeyManagementException; 10 | import java.security.NoSuchAlgorithmException; 11 | import java.security.SecureRandom; 12 | import java.util.concurrent.TimeUnit; 13 | 14 | import javax.net.ssl.SSLContext; 15 | import javax.net.ssl.TrustManager; 16 | 17 | import okhttp3.OkHttpClient; 18 | 19 | /** 20 | * Created by zhaokaiqiang on 15/11/23. 21 | */ 22 | public class OkApplication extends Application { 23 | 24 | @Override 25 | public void onCreate() { 26 | super.onCreate(); 27 | 28 | OkHttpClient.Builder builder = OkHttpProxy.getInstance().newBuilder() 29 | .connectTimeout(10, TimeUnit.SECONDS) 30 | .readTimeout(15, TimeUnit.SECONDS) 31 | .writeTimeout(15, TimeUnit.SECONDS); 32 | 33 | //ignore HTTPS Authentication 34 | builder.hostnameVerifier(new MyHostnameVerifier()); 35 | try { 36 | SSLContext sc = SSLContext.getInstance("TLS"); 37 | sc.init(null, new TrustManager[]{new MyTrustManager()}, new SecureRandom()); 38 | builder.sslSocketFactory(sc.getSocketFactory()); 39 | } catch (NoSuchAlgorithmException e) { 40 | e.printStackTrace(); 41 | } catch (KeyManagementException e) { 42 | e.printStackTrace(); 43 | } 44 | 45 | OkHttpProxy.setInstance(builder.build()); 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /sample/src/main/java/com/socks/sample/okhttp/model/Joke.java: -------------------------------------------------------------------------------- 1 | package com.socks.sample.okhttp.model; 2 | 3 | import java.io.Serializable; 4 | 5 | public class Joke implements Serializable { 6 | 7 | public static final String URL_JOKE = "http://jandan.net/?oxwlxojflwblxbsapi=jandan" + 8 | ".get_duan_comments&page="; 9 | 10 | private String comment_ID; 11 | private String comment_post_ID; 12 | private String comment_author; 13 | private String comment_author_email; 14 | private String comment_author_url; 15 | private String comment_author_IP; 16 | private String comment_date; 17 | private String comment_date_gmt; 18 | private String comment_content; 19 | private String text_content; 20 | private String comment_agent; 21 | private String vote_positive; 22 | private String vote_negative; 23 | 24 | public Joke() { 25 | } 26 | 27 | public static String getRequestUrl(int page) { 28 | return URL_JOKE + page; 29 | } 30 | 31 | @Override 32 | public String toString() { 33 | return "Joke{" + 34 | "comment_ID='" + comment_ID + '\'' + 35 | ", comment_post_ID='" + comment_post_ID + '\'' + 36 | ", comment_author='" + comment_author + '\'' + 37 | ", comment_author_email='" + comment_author_email + '\'' + 38 | ", comment_author_url='" + comment_author_url + '\'' + 39 | ", comment_author_IP='" + comment_author_IP + '\'' + 40 | ", comment_date='" + comment_date + '\'' + 41 | ", comment_date_gmt='" + comment_date_gmt + '\'' + 42 | ", comment_content='" + comment_content + '\'' + 43 | ", text_content='" + text_content + '\'' + 44 | ", comment_agent='" + comment_agent + '\'' + 45 | ", vote_positive='" + vote_positive + '\'' + 46 | ", vote_negative='" + vote_negative + '\'' + 47 | '}'; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /sample/src/main/java/com/socks/sample/okhttp/model/User.java: -------------------------------------------------------------------------------- 1 | package com.socks.sample.okhttp.model; 2 | 3 | public class User { 4 | 5 | public String name; 6 | public int age; 7 | public String blog; 8 | 9 | public User() { 10 | } 11 | 12 | public User(String name, int age, String blog) { 13 | this.name = name; 14 | this.age = age; 15 | this.blog = blog; 16 | } 17 | 18 | public String getName() { 19 | return name; 20 | } 21 | 22 | public void setName(String name) { 23 | this.name = name; 24 | } 25 | 26 | public int getAge() { 27 | return age; 28 | } 29 | 30 | public void setAge(int age) { 31 | this.age = age; 32 | } 33 | 34 | public String getBlog() { 35 | return blog; 36 | } 37 | 38 | public void setBlog(String blog) { 39 | this.blog = blog; 40 | } 41 | 42 | @Override 43 | public String toString() { 44 | return "User{" + 45 | "name='" + name + '\'' + 46 | ", age=" + age + 47 | ", blog='" + blog + '\'' + 48 | '}'; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /sample/src/main/java/com/socks/sample/okhttp/parser/JokeParser.java: -------------------------------------------------------------------------------- 1 | package com.socks.sample.okhttp.parser; 2 | 3 | import android.support.annotation.Nullable; 4 | import android.util.Log; 5 | 6 | import com.google.gson.reflect.TypeToken; 7 | import com.socks.okhttp.plus.parser.OkJsonParser; 8 | import com.socks.sample.okhttp.model.Joke; 9 | 10 | import org.json.JSONException; 11 | import org.json.JSONObject; 12 | 13 | import java.io.IOException; 14 | import java.util.ArrayList; 15 | 16 | import okhttp3.Response; 17 | 18 | /** 19 | * Created by zhaokaiqiang on 15/11/23. 20 | */ 21 | public class JokeParser extends OkJsonParser { 22 | 23 | @Nullable 24 | @Override 25 | public T parse(Response response) throws IOException { 26 | String jsonStr = response.body().string(); 27 | try { 28 | Log.d("OkCallback",Thread.currentThread().getName()); 29 | jsonStr = new JSONObject(jsonStr).getJSONArray("comments").toString(); 30 | return mGson.fromJson(jsonStr, new TypeToken>() { 31 | }.getType()); 32 | } catch (JSONException e) { 33 | e.printStackTrace(); 34 | return null; 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /sample/src/main/java/com/socks/sample/okhttp/util/MyHostnameVerifier.java: -------------------------------------------------------------------------------- 1 | package com.socks.sample.okhttp.util; 2 | 3 | import javax.net.ssl.HostnameVerifier; 4 | import javax.net.ssl.SSLSession; 5 | 6 | /** 7 | * Created by zhaokaiqiang on 15/11/23. 8 | */ 9 | public class MyHostnameVerifier implements HostnameVerifier { 10 | @Override 11 | public boolean verify(String hostname, SSLSession session) { 12 | return true; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /sample/src/main/java/com/socks/sample/okhttp/util/MyTrustManager.java: -------------------------------------------------------------------------------- 1 | package com.socks.sample.okhttp.util; 2 | 3 | import java.security.cert.CertificateException; 4 | import java.security.cert.X509Certificate; 5 | 6 | import javax.net.ssl.X509TrustManager; 7 | 8 | /** 9 | * Created by zhaokaiqiang on 15/11/23. 10 | */ 11 | public class MyTrustManager implements X509TrustManager { 12 | @Override 13 | public void checkClientTrusted(X509Certificate[] chain, String authType) 14 | throws CertificateException { 15 | } 16 | 17 | @Override 18 | public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { 19 | } 20 | 21 | @Override 22 | public X509Certificate[] getAcceptedIssuers() { 23 | return null; 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /sample/src/main/java/com/socks/sample/okhttp/util/TestUrls.java: -------------------------------------------------------------------------------- 1 | package com.socks.sample.okhttp.util; 2 | 3 | /** 4 | * Created by zhaokaiqiang on 15/11/16. 5 | */ 6 | public interface TestUrls { 7 | 8 | String URL_USER = "https://raw.githubusercontent.com/ZhaoKaiQiang/OkHttpPlus/master/server/user"; 9 | String URL_USERS = "https://raw.githubusercontent.com/ZhaoKaiQiang/OkHttpPlus/master/server/users"; 10 | String URL_BAIDU = "http://www.baidu.com"; 11 | String URL_12306 = "https://kyfw.12306.cn/otn/"; 12 | String URL_DOWMLOAD = "https://github.com/ZhaoKaiQiang/OkHttpPlus/blob/master/library/libs/gson-2.2.1.jar?raw=true"; 13 | 14 | String TOKEN = "IUy4JnOZHP6o-rx9QsGLf9jMTAKfRkL07gNssIDA:fpDq4cNJ-YwTYWXNK443dX57G9o=:eyJzY29wZSI6InpoYW9rYWlxaWFuZyIsImRlYWRsaW5lIjoxNDQ4MzU4NjcwfQ=="; 15 | String URL_UPLOAD = "http://upload.qiniu.com/"; 16 | } 17 | -------------------------------------------------------------------------------- /sample/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 11 | 12 | 15 | 16 | 20 | 21 |