├── .gitignore ├── .idea ├── compiler.xml ├── copyright │ └── profiles_settings.xml ├── encodings.xml ├── fileTemplates │ └── includes │ │ └── File Header.java ├── gradle.xml ├── markdown-navigator.xml ├── markdown-navigator │ └── profiles_settings.xml ├── misc.xml ├── modules.xml ├── runConfigurations.xml └── vcs.xml ├── LICENSE ├── README.md ├── app ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── demo195_rxjavaretrofit │ │ └── ExampleInstrumentedTest.java │ ├── main │ ├── AndroidManifest.xml │ ├── assets │ │ ├── README.md │ │ ├── img.png │ │ └── srca.cer │ ├── java │ │ └── com │ │ │ └── devin │ │ │ └── rxjava_retrofit │ │ │ ├── MainActivity.java │ │ │ ├── MyApplication.java │ │ │ ├── entity │ │ │ └── LogisticsInfo.java │ │ │ ├── http │ │ │ ├── download │ │ │ │ ├── DownloadHelper.java │ │ │ │ ├── ProgressResponseBody.java │ │ │ │ ├── info │ │ │ │ │ └── FileInfo.java │ │ │ │ ├── listener │ │ │ │ │ └── DownloadListener.java │ │ │ │ └── util │ │ │ │ │ └── FileUtils.java │ │ │ ├── okhttp │ │ │ │ ├── CertificateManager.java │ │ │ │ ├── OkHttpHelper.java │ │ │ │ ├── https │ │ │ │ │ ├── CustomHttpsTrust.java │ │ │ │ │ └── HttpsUtils.java │ │ │ │ └── interceptor │ │ │ │ │ ├── HeaderInterceptor.java │ │ │ │ │ └── LoggingInterceptor.java │ │ │ ├── result │ │ │ │ ├── HttpRespException.java │ │ │ │ ├── HttpRespResult.java │ │ │ │ └── HttpRespStatus.java │ │ │ ├── retrofit │ │ │ │ ├── RetrofitHelper.java │ │ │ │ └── converter │ │ │ │ │ └── string │ │ │ │ │ ├── StringConverterFactory.java │ │ │ │ │ ├── StringRequestBodyConverter.java │ │ │ │ │ └── StringResponseBodyConverter.java │ │ │ ├── rxjava │ │ │ │ ├── observable │ │ │ │ │ ├── DialogTransformer.java │ │ │ │ │ └── TransformerHelper.java │ │ │ │ └── observer │ │ │ │ │ ├── BaseObserver.java │ │ │ │ │ └── CommonObserver.java │ │ │ └── service │ │ │ │ ├── ApiService.java │ │ │ │ └── manager │ │ │ │ └── ServiceManager.java │ │ │ └── util │ │ │ ├── Logger.java │ │ │ └── ToastUtils.java │ └── res │ │ ├── layout │ │ └── activity_main.xml │ │ ├── mipmap-hdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-mdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ └── values │ │ ├── colors.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── test │ └── java │ └── com │ └── demo195_rxjavaretrofit │ └── ExampleUnitTest.java ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | # Built application files 2 | *.apk 3 | *.ap_ 4 | 5 | # Files for the ART/Dalvik VM 6 | *.dex 7 | 8 | # Java class files 9 | *.class 10 | 11 | # Generated files 12 | bin/ 13 | gen/ 14 | out/ 15 | 16 | # Gradle files 17 | .gradle/ 18 | build/ 19 | 20 | # Local configuration file (sdk path, etc) 21 | local.properties 22 | 23 | # Proguard folder generated by Eclipse 24 | proguard/ 25 | 26 | # Log Files 27 | *.log 28 | 29 | # Android Studio Navigation editor temp files 30 | .navigation/ 31 | 32 | # Android Studio captures folder 33 | captures/ 34 | 35 | # Intellij 36 | *.iml 37 | .idea/workspace.xml 38 | 39 | # Keystore files 40 | *.jks 41 | -------------------------------------------------------------------------------- /.idea/compiler.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /.idea/copyright/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /.idea/encodings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.idea/fileTemplates/includes/File Header.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * Description: 4 | * Company: 5 | * Email:bjxm2013@163.com 6 | * Created by Devin Sun on ${DATE}. 7 | * 8 | */ -------------------------------------------------------------------------------- /.idea/gradle.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 17 | 18 | -------------------------------------------------------------------------------- /.idea/markdown-navigator.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 33 | 34 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | -------------------------------------------------------------------------------- /.idea/markdown-navigator/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 19 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 46 | 47 | 48 | 49 | 50 | 1.8 51 | 52 | 57 | 58 | 59 | 60 | 61 | 62 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /.idea/runConfigurations.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 11 | 12 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | #### 根据 RxJava2 和 Retrofit2 进行的封装,进行网络请求更加方便。 2 | 欢迎 star 和 issue 3 | 4 | 具体使用见博客:http://www.jianshu.com/p/5c2b075584ad 5 | #### 目前实现: 6 | ###### 1, 统一风格的接口 7 | ###### 2, 不统一风格的接口 8 | ###### 3,内存泄漏问题 9 | ###### 4, 请求过程中 ProgressDialog 10 | ###### 5, 自定义证书的 Https 的封装 11 | ###### 6, 使用 okHttp 进行下载时进度回调的封装 12 | 后面将实现带进度回调的上传功能。 13 | 14 | 15 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | /*.iml -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 26 5 | buildToolsVersion '27.0.3' 6 | defaultConfig { 7 | applicationId "com.demo195.rxjava_retrofit" 8 | minSdkVersion 19 9 | targetSdkVersion 25 10 | versionCode 1 11 | versionName "1.0" 12 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 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 fileTree(include: ['*.jar'], dir: 'libs') 24 | androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { 25 | exclude group: 'com.android.support', module: 'support-annotations' 26 | exclude group: 'com.google.code.findbugs', module: 'jsr305' 27 | }) 28 | compile 'com.android.support:appcompat-v7:25.3.1' 29 | compile 'com.android.support.constraint:constraint-layout:1.0.2' 30 | testCompile 'junit:junit:4.12' 31 | compile 'io.reactivex.rxjava2:rxjava:2.0.7' 32 | compile 'io.reactivex.rxjava2:rxandroid:2.0.1' 33 | compile 'com.squareup.retrofit2:retrofit:2.2.0' 34 | compile 'com.squareup.retrofit2:converter-gson:2.2.0' 35 | compile 'com.squareup.retrofit2:adapter-rxjava2:2.2.0' 36 | compile 'com.trello.rxlifecycle2:rxlifecycle:2.0.1' 37 | // If you want to bind to Android-specific lifecycles 38 | compile 'com.trello.rxlifecycle2:rxlifecycle-android:2.0.1' 39 | // If you want pre-written Activities and Fragments you can subclass as providers 40 | compile 'com.trello.rxlifecycle2:rxlifecycle-components:2.0.1' 41 | debugCompile 'com.squareup.leakcanary:leakcanary-android:1.5' 42 | releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5' 43 | testCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5' 44 | } 45 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in D:\sdk\android-sdk-windows/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 | # Uncomment this to preserve the line number information for 20 | # debugging stack traces. 21 | #-keepattributes SourceFile,LineNumberTable 22 | 23 | # If you keep the line number information, uncomment this to 24 | # hide the original source file name. 25 | #-renamesourcefileattribute SourceFile 26 | -------------------------------------------------------------------------------- /app/src/androidTest/java/com/demo195_rxjavaretrofit/ExampleInstrumentedTest.java: -------------------------------------------------------------------------------- 1 | package com.devin.rxjava_retrofit; 2 | 3 | import android.content.Context; 4 | import android.support.test.InstrumentationRegistry; 5 | import android.support.test.runner.AndroidJUnit4; 6 | 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | 10 | import static org.junit.Assert.*; 11 | 12 | /** 13 | * Instrumentation test, which will execute on an Android device. 14 | * 15 | * @see Testing documentation 16 | */ 17 | @RunWith(AndroidJUnit4.class) 18 | public class ExampleInstrumentedTest { 19 | @Test 20 | public void useAppContext() throws Exception { 21 | // Context of the app under test. 22 | Context appContext = InstrumentationRegistry.getTargetContext(); 23 | 24 | assertEquals("com.devin.rxjava_retrofit", appContext.getPackageName()); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 9 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /app/src/main/assets/README.md: -------------------------------------------------------------------------------- 1 | OkHttp 2 | ====== 3 | 4 | An HTTP & HTTP/2 client for Android and Java applications. For more information see [the website][1] and [the wiki][2]. 5 | 6 | Download 7 | -------- 8 | 9 | Download [the latest JAR][3] or grab via Maven: 10 | ```xml 11 | 12 | com.squareup.okhttp3 13 | okhttp 14 | 3.6.0 15 | 16 | ``` 17 | or Gradle: 18 | ```groovy 19 | compile 'com.squareup.okhttp3:okhttp:3.6.0' 20 | ``` 21 | 22 | Snapshots of the development version are available in [Sonatype's `snapshots` repository][snap]. 23 | 24 | 25 | MockWebServer 26 | ------------- 27 | 28 | A library for testing HTTP, HTTPS, and HTTP/2 clients. 29 | 30 | MockWebServer coupling with OkHttp is essential for proper testing of HTTP/2 so that code can be shared. 31 | 32 | ### Download 33 | 34 | Download [the latest JAR][4] or grab via Maven: 35 | ```xml 36 | 37 | com.squareup.okhttp3 38 | mockwebserver 39 | 3.6.0 40 | test 41 | 42 | ``` 43 | or Gradle: 44 | ```groovy 45 | testCompile 'com.squareup.okhttp3:mockwebserver:3.6.0' 46 | ``` 47 | 48 | ProGuard 49 | -------- 50 | 51 | If you are using ProGuard you might need to add the following option: 52 | ``` 53 | -dontwarn okio.** 54 | ``` 55 | 56 | License 57 | ------- 58 | 59 | Licensed under the Apache License, Version 2.0 (the "License"); 60 | you may not use this file except in compliance with the License. 61 | You may obtain a copy of the License at 62 | 63 | http://www.apache.org/licenses/LICENSE-2.0 64 | 65 | Unless required by applicable law or agreed to in writing, software 66 | distributed under the License is distributed on an "AS IS" BASIS, 67 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 68 | See the License for the specific language governing permissions and 69 | limitations under the License. 70 | 71 | 72 | [1]: http://square.github.io/okhttp 73 | [2]: https://github.com/square/okhttp/wiki 74 | [3]: https://search.maven.org/remote_content?g=com.squareup.okhttp3&a=okhttp&v=LATEST 75 | [4]: https://search.maven.org/remote_content?g=com.squareup.okhttp3&a=mockwebserver&v=LATEST 76 | [snap]: https://oss.sonatype.org/content/repositories/snapshots/ 77 | -------------------------------------------------------------------------------- /app/src/main/assets/img.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sundevin/rxjava2_retrofit2/ecfa3995e64fc8cfb0e247fbf360f34bca7c0244/app/src/main/assets/img.png -------------------------------------------------------------------------------- /app/src/main/assets/srca.cer: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sundevin/rxjava2_retrofit2/ecfa3995e64fc8cfb0e247fbf360f34bca7c0244/app/src/main/assets/srca.cer -------------------------------------------------------------------------------- /app/src/main/java/com/devin/rxjava_retrofit/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.devin.rxjava_retrofit; 2 | 3 | import android.app.ProgressDialog; 4 | import android.content.DialogInterface; 5 | import android.os.Bundle; 6 | import android.view.View; 7 | import android.widget.Button; 8 | 9 | import com.devin.rxjava_retrofit.entity.LogisticsInfo; 10 | import com.devin.rxjava_retrofit.http.download.DownloadHelper; 11 | import com.devin.rxjava_retrofit.http.download.listener.DownloadListener; 12 | import com.devin.rxjava_retrofit.http.result.HttpRespResult; 13 | import com.devin.rxjava_retrofit.http.rxjava.observable.DialogTransformer; 14 | import com.devin.rxjava_retrofit.http.rxjava.observable.TransformerHelper; 15 | import com.devin.rxjava_retrofit.http.rxjava.observer.CommonObserver; 16 | import com.devin.rxjava_retrofit.http.service.manager.ServiceManager; 17 | import com.devin.rxjava_retrofit.util.Logger; 18 | import com.trello.rxlifecycle2.components.support.RxAppCompatActivity; 19 | 20 | import java.io.File; 21 | import java.util.HashMap; 22 | import java.util.List; 23 | import java.util.Map; 24 | 25 | import io.reactivex.Observer; 26 | import io.reactivex.disposables.Disposable; 27 | 28 | 29 | public class MainActivity extends RxAppCompatActivity { 30 | 31 | private Button btGet1; 32 | private Button btGet2; 33 | private Button btPost; 34 | private Button btDown; 35 | 36 | private void assignViews() { 37 | btGet1 = (Button) findViewById(R.id.bt_get_1); 38 | btGet2 = (Button) findViewById(R.id.bt_get_2); 39 | btPost = (Button) findViewById(R.id.bt_post); 40 | btDown = (Button) findViewById(R.id.bt_down); 41 | } 42 | 43 | 44 | @Override 45 | protected void onCreate(Bundle savedInstanceState) { 46 | super.onCreate(savedInstanceState); 47 | setContentView(R.layout.activity_main); 48 | assignViews(); 49 | 50 | 51 | //非标准restful 接口 52 | btGet1.setOnClickListener(new View.OnClickListener() { 53 | @Override 54 | public void onClick(View v) { 55 | ServiceManager 56 | .getApiService() 57 | .testGet1() 58 | .compose(MainActivity.this.bindToLifecycle())//绑定生命周期,防止内存泄露 59 | .compose(new DialogTransformer(MainActivity.this).showDialog())//progressDialog 60 | .subscribe(new Observer() { 61 | @Override 62 | public void onSubscribe(Disposable d) { 63 | 64 | } 65 | 66 | @Override 67 | public void onNext(String s) { 68 | Logger.e(s); 69 | } 70 | 71 | @Override 72 | public void onError(Throwable e) { 73 | Logger.e(e.toString()); 74 | } 75 | 76 | @Override 77 | public void onComplete() { 78 | 79 | } 80 | }); 81 | 82 | 83 | } 84 | }); 85 | 86 | btGet2.setOnClickListener(new View.OnClickListener() { 87 | @Override 88 | public void onClick(View v) { 89 | ServiceManager 90 | .getApiService() 91 | .testGet2() 92 | .compose(MainActivity.this.>>bindToLifecycle()) 93 | .compose(TransformerHelper.>transformer()) 94 | .compose(new DialogTransformer(MainActivity.this).>>showDialog()) 95 | .subscribe(new CommonObserver>() { 96 | @Override 97 | public void onSuccess(List strings) { 98 | Logger.e(strings.toString()); 99 | } 100 | }); 101 | 102 | 103 | } 104 | }); 105 | 106 | 107 | btPost.setOnClickListener(new View.OnClickListener() { 108 | @Override 109 | public void onClick(View v) { 110 | 111 | Map map = new HashMap<>(); 112 | map.put("logisticsid", 20); 113 | map.put("logisticsno", "1000817443587"); 114 | 115 | ServiceManager 116 | .getApiService() 117 | .getLogisticsInfo(map) 118 | .compose(MainActivity.this.>bindToLifecycle()) 119 | .compose(TransformerHelper.transformer()) 120 | .compose(new DialogTransformer(MainActivity.this).>showDialog()) 121 | .subscribe(new CommonObserver() { 122 | @Override 123 | public void onSuccess(LogisticsInfo logisticsInfo) { 124 | Logger.e(logisticsInfo.toString()); 125 | } 126 | }); 127 | } 128 | }); 129 | 130 | 131 | btDown.setOnClickListener(new View.OnClickListener() { 132 | @Override 133 | public void onClick(View v) { 134 | download(); 135 | } 136 | }); 137 | 138 | 139 | } 140 | 141 | 142 | private void download() { 143 | 144 | String url = "http://downloads.easemob.com/downloads/easemob-sdk-3.3.1_r1.zip"; 145 | String dirPath = getExternalCacheDir().getAbsolutePath(); 146 | String fileName = "download_test.zip"; 147 | 148 | 149 | final ProgressDialog progressDialog = new ProgressDialog(MainActivity.this); 150 | progressDialog.setTitle("更新"); 151 | progressDialog.setMessage("更新中,请稍候..."); 152 | progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 153 | progressDialog.setMax(100); 154 | progressDialog.setProgress(10); 155 | progressDialog.setCancelable(false); 156 | 157 | final DownloadHelper downloadHelper = new DownloadHelper(url, dirPath, fileName); 158 | 159 | downloadHelper.downloadFile(new DownloadListener() { 160 | @Override 161 | public void update(long bytesRead, long contentLength) { 162 | Logger.e("----bytesRead=" + bytesRead); 163 | Logger.e("----contentLength=" + contentLength); 164 | progressDialog.setProgress((int) ((100 * bytesRead) / contentLength)); 165 | } 166 | 167 | @Override 168 | public void onSuccess(File file) { 169 | progressDialog.cancel(); 170 | Logger.e(file.getAbsolutePath() + "----" + file.length()); 171 | } 172 | 173 | @Override 174 | public void onFailure(Throwable t) { 175 | progressDialog.cancel(); 176 | Logger.e("----" + t.toString()); 177 | } 178 | }); 179 | 180 | 181 | progressDialog.setButton3("取消下载", new DialogInterface.OnClickListener() { 182 | @Override 183 | public void onClick(DialogInterface dialog, int which) { 184 | downloadHelper.cancelDownload(); 185 | } 186 | }); 187 | 188 | progressDialog.show(); 189 | 190 | } 191 | 192 | 193 | } 194 | -------------------------------------------------------------------------------- /app/src/main/java/com/devin/rxjava_retrofit/MyApplication.java: -------------------------------------------------------------------------------- 1 | package com.devin.rxjava_retrofit; 2 | 3 | import android.app.Application; 4 | import android.content.Context; 5 | 6 | import com.squareup.leakcanary.LeakCanary; 7 | 8 | /** 9 | *

Description: 10 | * 11 | *

Created by Devin Sun on 2017/3/28. 12 | */ 13 | 14 | public class MyApplication extends Application { 15 | 16 | private static MyApplication myApplication; 17 | 18 | public static MyApplication getInstance(){ 19 | return myApplication; 20 | } 21 | 22 | 23 | @Override 24 | protected void attachBaseContext(Context base) { 25 | super.attachBaseContext(base); 26 | myApplication= this; 27 | } 28 | 29 | @Override 30 | public void onCreate() { 31 | super.onCreate(); 32 | LeakCanary.install(this); 33 | } 34 | 35 | 36 | } 37 | -------------------------------------------------------------------------------- /app/src/main/java/com/devin/rxjava_retrofit/entity/LogisticsInfo.java: -------------------------------------------------------------------------------- 1 | package com.devin.rxjava_retrofit.entity; 2 | 3 | import java.util.List; 4 | 5 | /** 6 | * Description: 7 | * Company: 8 | * Email:bjxm2013@163.com 9 | * Created by Devin Sun on 2017/4/21. 10 | */ 11 | public class LogisticsInfo { 12 | 13 | private String message; 14 | private String id; 15 | private int num; 16 | private String order; 17 | private int status; 18 | private String updateTime; 19 | private String name; 20 | private int errCode; 21 | private List data; 22 | 23 | public void setMessage(String message) { 24 | this.message = message; 25 | } 26 | 27 | public void setId(String id) { 28 | this.id = id; 29 | } 30 | 31 | public void setNum(int num) { 32 | this.num = num; 33 | } 34 | 35 | public void setOrder(String order) { 36 | this.order = order; 37 | } 38 | 39 | public void setStatus(int status) { 40 | this.status = status; 41 | } 42 | 43 | public void setUpdateTime(String updateTime) { 44 | this.updateTime = updateTime; 45 | } 46 | 47 | public void setName(String name) { 48 | this.name = name; 49 | } 50 | 51 | public void setErrCode(int errCode) { 52 | this.errCode = errCode; 53 | } 54 | 55 | public void setData(List data) { 56 | this.data = data; 57 | } 58 | 59 | public String getMessage() { 60 | return message; 61 | } 62 | 63 | public String getId() { 64 | return id; 65 | } 66 | 67 | public int getNum() { 68 | return num; 69 | } 70 | 71 | public String getOrder() { 72 | return order; 73 | } 74 | 75 | public int getStatus() { 76 | return status; 77 | } 78 | 79 | public String getUpdateTime() { 80 | return updateTime; 81 | } 82 | 83 | public String getName() { 84 | return name; 85 | } 86 | 87 | public int getErrCode() { 88 | return errCode; 89 | } 90 | 91 | public List getData() { 92 | return data; 93 | } 94 | 95 | public static class DataBean { 96 | 97 | 98 | private String content; 99 | private String time; 100 | 101 | public void setContent(String content) { 102 | this.content = content; 103 | } 104 | 105 | public void setTime(String time) { 106 | this.time = time; 107 | } 108 | 109 | public String getContent() { 110 | return content; 111 | } 112 | 113 | public String getTime() { 114 | return time; 115 | } 116 | 117 | @Override 118 | public String toString() { 119 | return "DataBean{" + 120 | "content='" + content + '\'' + 121 | ", time='" + time + '\'' + 122 | '}'; 123 | } 124 | } 125 | 126 | @Override 127 | public String toString() { 128 | return "LogisticsInfo{" + 129 | "message='" + message + '\'' + 130 | ", id='" + id + '\'' + 131 | ", num=" + num + 132 | ", order='" + order + '\'' + 133 | ", status=" + status + 134 | ", updateTime='" + updateTime + '\'' + 135 | ", name='" + name + '\'' + 136 | ", errCode=" + errCode + 137 | ", data=" + data + 138 | '}'; 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /app/src/main/java/com/devin/rxjava_retrofit/http/download/DownloadHelper.java: -------------------------------------------------------------------------------- 1 | package com.devin.rxjava_retrofit.http.download; 2 | 3 | import java.io.File; 4 | import java.io.IOException; 5 | 6 | import com.devin.rxjava_retrofit.http.download.listener.DownloadListener; 7 | import com.devin.rxjava_retrofit.http.download.util.FileUtils; 8 | import io.reactivex.Observable; 9 | import io.reactivex.android.schedulers.AndroidSchedulers; 10 | import io.reactivex.annotations.NonNull; 11 | import io.reactivex.functions.Consumer; 12 | import io.reactivex.schedulers.Schedulers; 13 | import okhttp3.Call; 14 | import okhttp3.Interceptor; 15 | import okhttp3.OkHttpClient; 16 | import okhttp3.Request; 17 | import okhttp3.Response; 18 | 19 | /** 20 | * Description: 21 | * Company: 22 | * Email:bjxm2013@163.com 23 | * Created by Devin Sun on 2017/4/3. 24 | */ 25 | public class DownloadHelper { 26 | 27 | private Call call; 28 | 29 | private String url; 30 | private String dirPath; 31 | private String fileName; 32 | 33 | 34 | public DownloadHelper(String url, String dirPath, String fileName) { 35 | this.url = url; 36 | this.dirPath = dirPath; 37 | this.fileName = fileName; 38 | } 39 | 40 | public void downloadFile(final DownloadListener downloadListener) { 41 | 42 | Request request = new Request.Builder().url(url).build(); 43 | call = initClient(downloadListener).newCall(request); 44 | 45 | 46 | Observable.just(call) 47 | .subscribeOn(Schedulers.io()) 48 | .observeOn(Schedulers.io()) 49 | .subscribe(new Consumer() { 50 | @Override 51 | public void accept(@NonNull Call call) throws Exception { 52 | Response response = call.execute(); 53 | 54 | if (!response.isSuccessful()) { 55 | throw new IOException("Unexpected code " + response); 56 | } else { 57 | FileUtils.saveFile(dirPath, fileName, response.body().byteStream()); 58 | response.close(); 59 | 60 | if (downloadListener != null) { 61 | Observable.just(new File(dirPath, fileName)).subscribeOn(Schedulers.io()) 62 | .observeOn(AndroidSchedulers.mainThread()) 63 | .subscribe(new Consumer() { 64 | @Override 65 | public void accept(@NonNull File file) throws Exception { 66 | downloadListener.onSuccess(file); 67 | } 68 | }); 69 | } 70 | } 71 | } 72 | 73 | }, new Consumer() { 74 | @Override 75 | public void accept(@NonNull Throwable throwable) { 76 | Observable.just(throwable).subscribeOn(Schedulers.io()) 77 | .observeOn(AndroidSchedulers.mainThread()) 78 | .subscribe(new Consumer() { 79 | @Override 80 | public void accept(@NonNull Throwable throwable) throws Exception { 81 | if (downloadListener != null) { 82 | downloadListener.onFailure(throwable); 83 | } 84 | } 85 | }); 86 | } 87 | }); 88 | 89 | } 90 | 91 | 92 | public void cancelDownload() { 93 | if (call != null && !call.isCanceled()) { 94 | call.cancel(); 95 | } 96 | } 97 | 98 | private OkHttpClient initClient(final DownloadListener downloadListener) { 99 | 100 | return new OkHttpClient.Builder(). 101 | addInterceptor(new Interceptor() { 102 | @Override 103 | public Response intercept(Chain chain) throws IOException { 104 | Request request = chain.request().newBuilder().addHeader("Accept-Encoding", "identity").build(); 105 | return chain.proceed(request); 106 | } 107 | }).addNetworkInterceptor(new Interceptor() { 108 | @Override 109 | public Response intercept(Chain chain) throws IOException { 110 | Response originalResponse = chain.proceed(chain.request()); 111 | return originalResponse.newBuilder() 112 | .body(new ProgressResponseBody(originalResponse.body(), downloadListener)).build(); 113 | } 114 | }).build(); 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /app/src/main/java/com/devin/rxjava_retrofit/http/download/ProgressResponseBody.java: -------------------------------------------------------------------------------- 1 | package com.devin.rxjava_retrofit.http.download; 2 | 3 | import java.io.IOException; 4 | 5 | import com.devin.rxjava_retrofit.http.download.listener.DownloadListener; 6 | import io.reactivex.Observable; 7 | import io.reactivex.android.schedulers.AndroidSchedulers; 8 | import io.reactivex.annotations.NonNull; 9 | import io.reactivex.functions.Consumer; 10 | import io.reactivex.schedulers.Schedulers; 11 | import okhttp3.MediaType; 12 | import okhttp3.ResponseBody; 13 | import okio.Buffer; 14 | import okio.BufferedSource; 15 | import okio.ForwardingSource; 16 | import okio.Okio; 17 | import okio.Source; 18 | 19 | /** 20 | * Description: 21 | * Company: 22 | * Email:bjxm2013@163.com 23 | * Created by Devin Sun on 2017/4/3. 24 | */ 25 | public class ProgressResponseBody extends ResponseBody { 26 | 27 | private long contentLength ; 28 | 29 | private final ResponseBody responseBody; 30 | private final DownloadListener downloadListener; 31 | private BufferedSource bufferedSource; 32 | 33 | public ProgressResponseBody(ResponseBody responseBody, DownloadListener downloadListener) { 34 | this.responseBody = responseBody; 35 | this.downloadListener = downloadListener; 36 | contentLength=responseBody.contentLength(); 37 | } 38 | 39 | @Override 40 | public MediaType contentType() { 41 | return responseBody.contentType(); 42 | } 43 | 44 | @Override 45 | public long contentLength() { 46 | return responseBody.contentLength(); 47 | } 48 | 49 | @Override 50 | public BufferedSource source() { 51 | if (bufferedSource == null) { 52 | bufferedSource = Okio.buffer(source(responseBody.source())); 53 | } 54 | return bufferedSource; 55 | } 56 | 57 | private Source source(Source source) { 58 | return new ForwardingSource(source) { 59 | long currentTotalBytesRead = 0L; 60 | 61 | @Override 62 | public long read(Buffer sink, long byteCount) throws IOException { 63 | long bytesRead = super.read(sink, byteCount); 64 | // read() returns the number of bytes read, or -1 if this source is exhausted. 65 | currentTotalBytesRead += bytesRead != -1 ? bytesRead : 0; 66 | if (downloadListener != null) { 67 | Observable.just(currentTotalBytesRead) 68 | .subscribeOn(Schedulers.io()) 69 | .observeOn(AndroidSchedulers.mainThread()) 70 | .subscribe(new Consumer() { 71 | @Override 72 | public void accept(@NonNull Long aLong) throws Exception { 73 | downloadListener.update(currentTotalBytesRead, contentLength); 74 | } 75 | }); 76 | 77 | } 78 | return bytesRead; 79 | } 80 | }; 81 | } 82 | 83 | } 84 | -------------------------------------------------------------------------------- /app/src/main/java/com/devin/rxjava_retrofit/http/download/info/FileInfo.java: -------------------------------------------------------------------------------- 1 | package com.devin.rxjava_retrofit.http.download.info; 2 | 3 | /** 4 | * Description: 5 | * Company: 6 | * Email:bjxm2013@163.com 7 | * Created by Devin Sun on 2017/4/3. 8 | */ 9 | public class FileInfo { 10 | public String fileName; 11 | public String parentPath; 12 | public long fileTotalSize; 13 | public long fileCurrentSize; 14 | public boolean done; 15 | 16 | @Override 17 | public String toString() { 18 | return "FileInfo{" + 19 | "fileName='" + fileName + '\'' + 20 | ", parentPath='" + parentPath + '\'' + 21 | ", fileTotalSize=" + fileTotalSize + 22 | ", fileCurrentSize=" + fileCurrentSize + 23 | ", done=" + done + 24 | '}'; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /app/src/main/java/com/devin/rxjava_retrofit/http/download/listener/DownloadListener.java: -------------------------------------------------------------------------------- 1 | package com.devin.rxjava_retrofit.http.download.listener; 2 | 3 | import java.io.File; 4 | 5 | /** 6 | * Description: 7 | * Company: 8 | * Email:bjxm2013@163.com 9 | * Created by Devin Sun on 2017/4/3. 10 | */ 11 | public interface DownloadListener { 12 | 13 | void update(long bytesRead, long contentLength); 14 | 15 | void onSuccess(File file); 16 | 17 | void onFailure(Throwable t); 18 | } 19 | -------------------------------------------------------------------------------- /app/src/main/java/com/devin/rxjava_retrofit/http/download/util/FileUtils.java: -------------------------------------------------------------------------------- 1 | package com.devin.rxjava_retrofit.http.download.util; 2 | 3 | import java.io.File; 4 | import java.io.FileOutputStream; 5 | import java.io.IOException; 6 | import java.io.InputStream; 7 | 8 | /** 9 | * Description: 10 | * Company: 11 | * Email:bjxm2013@163.com 12 | * Created by Devin Sun on 2017/4/20. 13 | */ 14 | public class FileUtils { 15 | /** 16 | * @param dirPath 文件夹路径 17 | * @param fileName 文件名 18 | * @param inputStream 输入流 19 | */ 20 | public static void saveFile(String dirPath, String fileName, InputStream inputStream) throws IOException { 21 | 22 | File dir = new File(dirPath); 23 | if (!dir.exists()) { 24 | dir.mkdirs(); 25 | } 26 | File file = new File(dir, fileName); 27 | if (file.exists()) { 28 | file.delete(); 29 | } 30 | 31 | byte[] buf = new byte[3072]; 32 | int len; 33 | FileOutputStream fos = new FileOutputStream(file); 34 | while ((len = inputStream.read(buf)) != -1) { 35 | fos.write(buf, 0, len); 36 | } 37 | inputStream.close(); 38 | fos.flush(); 39 | 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /app/src/main/java/com/devin/rxjava_retrofit/http/okhttp/CertificateManager.java: -------------------------------------------------------------------------------- 1 | package com.devin.rxjava_retrofit.http.okhttp; 2 | 3 | import java.io.IOException; 4 | import java.io.InputStream; 5 | 6 | import com.devin.rxjava_retrofit.MyApplication; 7 | import okio.Buffer; 8 | 9 | /** 10 | * Description: 11 | * Company: 12 | * Email:bjxm2013@163.com 13 | * Created by Devin Sun on 2017/4/1. 14 | */ 15 | public class CertificateManager { 16 | 17 | 18 | public static final String CER_12306_CONTENT = "" + 19 | "-----BEGIN CERTIFICATE-----\n" + 20 | "MIICmjCCAgOgAwIBAgIIbyZr5/jKH6QwDQYJKoZIhvcNAQEFBQAwRzELMAkGA1UEBhMCQ04xKTAn\n" + 21 | "BgNVBAoTIFNpbm9yYWlsIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MQ0wCwYDVQQDEwRTUkNBMB4X\n" + 22 | "DTA5MDUyNTA2NTYwMFoXDTI5MDUyMDA2NTYwMFowRzELMAkGA1UEBhMCQ04xKTAnBgNVBAoTIFNp\n" + 23 | "bm9yYWlsIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MQ0wCwYDVQQDEwRTUkNBMIGfMA0GCSqGSIb3\n" + 24 | "DQEBAQUAA4GNADCBiQKBgQDMpbNeb34p0GvLkZ6t72/OOba4mX2K/eZRWFfnuk8e5jKDH+9BgCb2\n" + 25 | "9bSotqPqTbxXWPxIOz8EjyUO3bfR5pQ8ovNTOlks2rS5BdMhoi4sUjCKi5ELiqtyww/XgY5iFqv6\n" + 26 | "D4Pw9QvOUcdRVSbPWo1DwMmH75It6pk/rARIFHEjWwIDAQABo4GOMIGLMB8GA1UdIwQYMBaAFHle\n" + 27 | "tne34lKDQ+3HUYhMY4UsAENYMAwGA1UdEwQFMAMBAf8wLgYDVR0fBCcwJTAjoCGgH4YdaHR0cDov\n" + 28 | "LzE5Mi4xNjguOS4xNDkvY3JsMS5jcmwwCwYDVR0PBAQDAgH+MB0GA1UdDgQWBBR5XrZ3t+JSg0Pt\n" + 29 | "x1GITGOFLABDWDANBgkqhkiG9w0BAQUFAAOBgQDGrAm2U/of1LbOnG2bnnQtgcVaBXiVJF8LKPaV\n" + 30 | "23XQ96HU8xfgSZMJS6U00WHAI7zp0q208RSUft9wDq9ee///VOhzR6Tebg9QfyPSohkBrhXQenvQ\n" + 31 | "og555S+C3eJAAVeNCTeMS3N/M5hzBRJAoffn3qoYdAO1Q8bTguOi+2849A==\n" + 32 | "-----END CERTIFICATE-----"; 33 | 34 | 35 | public static InputStream[] trustedCertificatesInputStream(String[] str) { 36 | 37 | InputStream[] inputStream = new InputStream[str.length]; 38 | for (int i = 0; i < str.length; i++) { 39 | inputStream[i] = new Buffer() 40 | .writeUtf8(str[i]) 41 | .inputStream(); 42 | } 43 | return inputStream; 44 | } 45 | 46 | 47 | public static InputStream[] trustedCertificatesInputStream() { 48 | 49 | InputStream[] inputStream = new InputStream[1]; 50 | try { 51 | inputStream[0] = MyApplication.getInstance().getAssets().open("srca.cer"); 52 | } catch (IOException e) { 53 | e.printStackTrace(); 54 | } 55 | return inputStream; 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /app/src/main/java/com/devin/rxjava_retrofit/http/okhttp/OkHttpHelper.java: -------------------------------------------------------------------------------- 1 | package com.devin.rxjava_retrofit.http.okhttp; 2 | 3 | import com.devin.rxjava_retrofit.http.okhttp.https.CustomHttpsTrust; 4 | import com.devin.rxjava_retrofit.http.okhttp.interceptor.LoggingInterceptor; 5 | 6 | import java.util.concurrent.TimeUnit; 7 | 8 | import okhttp3.OkHttpClient; 9 | 10 | /** 11 | *

Description: 12 | *

13 | *

Created by Devin Sun on 2017/3/24. 14 | */ 15 | 16 | public class OkHttpHelper { 17 | 18 | private static OkHttpClient okHttpClient; 19 | 20 | /** 21 | * 连接超时 22 | */ 23 | private static final int CONNECT_TIMEOUT = 10; 24 | /** 25 | * 读取超时 26 | */ 27 | private static final int READ_TIMEOUT = 25; 28 | /** 29 | * 写入超时 30 | */ 31 | private static final int WRITE_TIMEOUT = 25; 32 | 33 | 34 | private OkHttpHelper() { 35 | } 36 | 37 | static { 38 | 39 | CustomHttpsTrust customHttpsTrust = new CustomHttpsTrust(CertificateManager.trustedCertificatesInputStream()); 40 | 41 | okHttpClient = new OkHttpClient.Builder() 42 | .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS) 43 | .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS) 44 | .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS) 45 | // .addInterceptor(new HeaderInterceptor()) //添加 header 46 | .addInterceptor(new LoggingInterceptor()) //请求信息的打印 ,可在 release 时关闭 47 | // .sslSocketFactory(customHttpsTrust.sSLSocketFactory, customHttpsTrust.x509TrustManager)// https 配置 48 | .build(); 49 | } 50 | 51 | public static OkHttpClient getClient() { 52 | return okHttpClient; 53 | } 54 | 55 | } 56 | -------------------------------------------------------------------------------- /app/src/main/java/com/devin/rxjava_retrofit/http/okhttp/https/CustomHttpsTrust.java: -------------------------------------------------------------------------------- 1 | package com.devin.rxjava_retrofit.http.okhttp.https; 2 | 3 | import java.io.InputStream; 4 | import java.security.KeyStore; 5 | import java.security.cert.CertificateException; 6 | import java.security.cert.CertificateFactory; 7 | import java.security.cert.X509Certificate; 8 | 9 | import javax.net.ssl.KeyManager; 10 | import javax.net.ssl.KeyManagerFactory; 11 | import javax.net.ssl.SSLContext; 12 | import javax.net.ssl.SSLSocketFactory; 13 | import javax.net.ssl.TrustManager; 14 | import javax.net.ssl.TrustManagerFactory; 15 | import javax.net.ssl.X509TrustManager; 16 | 17 | public class CustomHttpsTrust { 18 | 19 | public SSLSocketFactory sSLSocketFactory; 20 | public X509TrustManager x509TrustManager; 21 | 22 | /** 23 | * 信任全部https 24 | */ 25 | public CustomHttpsTrust() { 26 | this(null); 27 | } 28 | 29 | /** 30 | * 信任指定证书的https 31 | * 32 | * @param certificates 33 | */ 34 | public CustomHttpsTrust(InputStream[] certificates) { 35 | this(certificates, null, null); 36 | } 37 | 38 | /** 39 | * 双向证书的验证,极少数的应用需要双向证书验证,比如银行、金融类 40 | * 41 | * @param certificates 42 | * @param bksFile 43 | * @param password 44 | */ 45 | public CustomHttpsTrust(InputStream[] certificates, InputStream bksFile, String password) { 46 | 47 | try { 48 | TrustManager[] trustManagers = prepareTrustManager(certificates); 49 | KeyManager[] keyManagers = prepareKeyManager(bksFile, password); 50 | if (trustManagers == null) { 51 | x509TrustManager = new UnSafeTrustManager(); 52 | } else { 53 | for (TrustManager trustManager : 54 | trustManagers) { 55 | if (trustManager instanceof X509TrustManager) { 56 | x509TrustManager = (X509TrustManager) trustManager; 57 | break; 58 | } 59 | } 60 | } 61 | SSLContext sslContext = SSLContext.getInstance("TLS"); 62 | sslContext.init(keyManagers, new TrustManager[]{x509TrustManager}, null); 63 | sSLSocketFactory = sslContext.getSocketFactory(); 64 | } catch (Exception e) { 65 | e.printStackTrace(); 66 | } 67 | } 68 | 69 | 70 | private static TrustManager[] prepareTrustManager(InputStream[] inputStreams) { 71 | 72 | if (inputStreams == null || inputStreams.length == 0) { 73 | return null; 74 | } 75 | try { 76 | CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); 77 | KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); 78 | keyStore.load(null); 79 | 80 | int index = 0; 81 | for (InputStream stream : inputStreams) { 82 | String certificateAlias = Integer.toString(index++); 83 | keyStore.setCertificateEntry(certificateAlias, certificateFactory.generateCertificate(stream)); 84 | if (stream != null) 85 | stream.close(); 86 | 87 | } 88 | 89 | TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance( 90 | TrustManagerFactory.getDefaultAlgorithm()); 91 | 92 | trustManagerFactory.init(keyStore); 93 | return trustManagerFactory.getTrustManagers(); 94 | 95 | } catch (Exception e) { 96 | e.printStackTrace(); 97 | } 98 | 99 | return null; 100 | } 101 | 102 | 103 | private static KeyManager[] prepareKeyManager(InputStream bksFile, String password) { 104 | 105 | if (bksFile == null || password == null) { 106 | return null; 107 | } 108 | 109 | KeyStore clientKeyStore; 110 | try { 111 | clientKeyStore = KeyStore.getInstance("BKS"); 112 | clientKeyStore.load(bksFile, password.toCharArray()); 113 | KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); 114 | keyManagerFactory.init(clientKeyStore, password.toCharArray()); 115 | return keyManagerFactory.getKeyManagers(); 116 | } catch (Exception e) { 117 | e.printStackTrace(); 118 | } 119 | return null; 120 | } 121 | 122 | private class UnSafeTrustManager implements X509TrustManager { 123 | 124 | @Override 125 | public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { 126 | } 127 | @Override 128 | public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { 129 | } 130 | 131 | @Override 132 | public X509Certificate[] getAcceptedIssuers() { 133 | return new X509Certificate[0]; 134 | } 135 | } 136 | } 137 | -------------------------------------------------------------------------------- /app/src/main/java/com/devin/rxjava_retrofit/http/okhttp/https/HttpsUtils.java: -------------------------------------------------------------------------------- 1 | package com.devin.rxjava_retrofit.http.okhttp.https; 2 | 3 | import java.io.IOException; 4 | import java.io.InputStream; 5 | import java.security.KeyManagementException; 6 | import java.security.KeyStore; 7 | import java.security.KeyStoreException; 8 | import java.security.NoSuchAlgorithmException; 9 | import java.security.cert.CertificateException; 10 | import java.security.cert.CertificateFactory; 11 | import java.security.cert.X509Certificate; 12 | 13 | import javax.net.ssl.HostnameVerifier; 14 | import javax.net.ssl.KeyManager; 15 | import javax.net.ssl.KeyManagerFactory; 16 | import javax.net.ssl.SSLContext; 17 | import javax.net.ssl.SSLSession; 18 | import javax.net.ssl.SSLSocketFactory; 19 | import javax.net.ssl.TrustManager; 20 | import javax.net.ssl.TrustManagerFactory; 21 | import javax.net.ssl.X509TrustManager; 22 | 23 | 24 | public class HttpsUtils { 25 | public static class SSLParams { 26 | public SSLSocketFactory sSLSocketFactory; 27 | public X509TrustManager trustManager; 28 | } 29 | 30 | public static SSLParams getSslSocketFactory(InputStream[] certificates, InputStream bksFile, String password) { 31 | SSLParams sslParams = new SSLParams(); 32 | try { 33 | TrustManager[] trustManagers = prepareTrustManager(certificates); 34 | KeyManager[] keyManagers = prepareKeyManager(bksFile, password); 35 | SSLContext sslContext = SSLContext.getInstance("TLS"); 36 | X509TrustManager trustManager = null; 37 | if (trustManagers != null) { 38 | trustManager = new MyTrustManager(chooseTrustManager(trustManagers)); 39 | } else { 40 | trustManager = new UnSafeTrustManager(); 41 | } 42 | sslContext.init(keyManagers, new TrustManager[]{trustManager}, null); 43 | sslParams.sSLSocketFactory = sslContext.getSocketFactory(); 44 | sslParams.trustManager = trustManager; 45 | return sslParams; 46 | } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) { 47 | throw new AssertionError(e); 48 | } 49 | } 50 | 51 | private class UnSafeHostnameVerifier implements HostnameVerifier { 52 | @Override 53 | public boolean verify(String hostname, SSLSession session) { 54 | return true; 55 | } 56 | } 57 | 58 | private static class UnSafeTrustManager implements X509TrustManager { 59 | @Override 60 | public void checkClientTrusted(X509Certificate[] chain, String authType) 61 | throws CertificateException { 62 | } 63 | 64 | @Override 65 | public void checkServerTrusted(X509Certificate[] chain, String authType) 66 | throws CertificateException { 67 | } 68 | 69 | @Override 70 | public X509Certificate[] getAcceptedIssuers() { 71 | return new X509Certificate[]{}; 72 | } 73 | } 74 | 75 | private static TrustManager[] prepareTrustManager(InputStream... certificates) { 76 | if (certificates == null || certificates.length <= 0) return null; 77 | try { 78 | 79 | CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); 80 | KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); 81 | keyStore.load(null); 82 | int index = 0; 83 | for (InputStream certificate : certificates) { 84 | String certificateAlias = Integer.toString(index++); 85 | keyStore.setCertificateEntry(certificateAlias, certificateFactory.generateCertificate(certificate)); 86 | try { 87 | if (certificate != null) 88 | certificate.close(); 89 | } catch (IOException e) 90 | { 91 | } 92 | } 93 | TrustManagerFactory trustManagerFactory = TrustManagerFactory. 94 | getInstance(TrustManagerFactory.getDefaultAlgorithm()); 95 | trustManagerFactory.init(keyStore); 96 | return trustManagerFactory.getTrustManagers(); 97 | } catch (Exception e) { 98 | e.printStackTrace(); 99 | } 100 | return null; 101 | 102 | } 103 | 104 | private static KeyManager[] prepareKeyManager(InputStream bksFile, String password) { 105 | try { 106 | if (bksFile == null || password == null) return null; 107 | 108 | KeyStore clientKeyStore = KeyStore.getInstance("BKS"); 109 | clientKeyStore.load(bksFile, password.toCharArray()); 110 | KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); 111 | keyManagerFactory.init(clientKeyStore, password.toCharArray()); 112 | return keyManagerFactory.getKeyManagers(); 113 | 114 | } catch (Exception e) { 115 | e.printStackTrace(); 116 | } 117 | return null; 118 | } 119 | 120 | private static X509TrustManager chooseTrustManager(TrustManager[] trustManagers) { 121 | for (TrustManager trustManager : trustManagers) { 122 | if (trustManager instanceof X509TrustManager) { 123 | return (X509TrustManager) trustManager; 124 | } 125 | } 126 | return null; 127 | } 128 | 129 | 130 | private static class MyTrustManager implements X509TrustManager { 131 | private X509TrustManager defaultTrustManager; 132 | private X509TrustManager localTrustManager; 133 | 134 | public MyTrustManager(X509TrustManager localTrustManager) throws NoSuchAlgorithmException, KeyStoreException { 135 | TrustManagerFactory var4 = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); 136 | var4.init((KeyStore) null); 137 | defaultTrustManager = chooseTrustManager(var4.getTrustManagers()); 138 | this.localTrustManager = localTrustManager; 139 | } 140 | 141 | 142 | @Override 143 | public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { 144 | 145 | } 146 | 147 | @Override 148 | public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { 149 | try { 150 | defaultTrustManager.checkServerTrusted(chain, authType); 151 | } catch (CertificateException ce) { 152 | localTrustManager.checkServerTrusted(chain, authType); 153 | } 154 | } 155 | 156 | 157 | @Override 158 | public X509Certificate[] getAcceptedIssuers() { 159 | return new X509Certificate[0]; 160 | } 161 | } 162 | } 163 | -------------------------------------------------------------------------------- /app/src/main/java/com/devin/rxjava_retrofit/http/okhttp/interceptor/HeaderInterceptor.java: -------------------------------------------------------------------------------- 1 | package com.devin.rxjava_retrofit.http.okhttp.interceptor; 2 | 3 | 4 | import java.io.IOException; 5 | 6 | import okhttp3.Interceptor; 7 | import okhttp3.Request; 8 | import okhttp3.Response; 9 | 10 | /** 11 | *

Description: 12 | *

Created by Devin Sun on 2017/3/29. 13 | */ 14 | 15 | public class HeaderInterceptor implements Interceptor { 16 | @Override 17 | public Response intercept(Chain chain) throws IOException { 18 | 19 | Request request = chain.request().newBuilder() 20 | // .addHeader() 21 | // add header... 22 | .build(); 23 | 24 | return chain.proceed(request); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /app/src/main/java/com/devin/rxjava_retrofit/http/okhttp/interceptor/LoggingInterceptor.java: -------------------------------------------------------------------------------- 1 | package com.devin.rxjava_retrofit.http.okhttp.interceptor; 2 | 3 | import java.io.IOException; 4 | import java.net.URLDecoder; 5 | 6 | import com.devin.rxjava_retrofit.util.Logger; 7 | import okhttp3.Headers; 8 | import okhttp3.Interceptor; 9 | import okhttp3.MediaType; 10 | import okhttp3.Request; 11 | import okhttp3.RequestBody; 12 | import okhttp3.Response; 13 | import okhttp3.ResponseBody; 14 | import okio.Buffer; 15 | 16 | /** 17 | * Description: 18 | * Company: 19 | * Email:bjxm2013@163.com 20 | * Created by Devin Sun on 2017/3/31. 21 | */ 22 | public class LoggingInterceptor implements Interceptor { 23 | @Override 24 | public Response intercept(Chain chain) throws IOException { 25 | 26 | Request request = chain.request(); 27 | printlnRequestInfo(request); 28 | 29 | Response response = chain.proceed(request); 30 | 31 | return printlnResponseInfo(response); 32 | } 33 | 34 | /** 35 | * 打印Request info 36 | * 37 | * @param request 38 | */ 39 | private void printlnRequestInfo(Request request) { 40 | 41 | StringBuilder stringBuilder = new StringBuilder(); 42 | stringBuilder.append("======request's log begin======\n"); 43 | 44 | String url = request.url().toString(); 45 | stringBuilder.append("url: ").append(url).append("\n"); 46 | stringBuilder.append("method: ").append(request.method()).append("\n"); 47 | 48 | Headers headers = request.headers(); 49 | if (headers != null) { 50 | stringBuilder.append("headers: ").append("\n").append(headers.toString()).append("\n"); 51 | } else { 52 | stringBuilder.append("headers:headers is null !\n"); 53 | } 54 | 55 | RequestBody requestBody = request.body(); 56 | if (requestBody != null) { 57 | MediaType mediaType = requestBody.contentType(); 58 | if (mediaType != null) { 59 | stringBuilder.append("request mediaType: ").append(mediaType.toString()).append("\n"); 60 | if (isTextMediaType(mediaType)) { 61 | stringBuilder.append("requestBody's content: \n").append(requestBodyToStr(request)).append("\n"); 62 | } else { 63 | stringBuilder.append("requestBody's content : maybe [file part], ignored print !\n"); 64 | } 65 | } else { 66 | stringBuilder.append("request mediaType:mediaType is null !\n"); 67 | } 68 | } else { 69 | stringBuilder.append("requestBody:requestBody is null !\n"); 70 | } 71 | stringBuilder.append("======request's log end======"); 72 | Logger.d(stringBuilder.toString()); 73 | } 74 | 75 | /** 76 | * print Response info 77 | * @param response 78 | * @return newResponse 79 | */ 80 | private Response printlnResponseInfo(Response response) { 81 | 82 | Response newResponse=response; 83 | 84 | StringBuilder stringBuilder = new StringBuilder(); 85 | stringBuilder.append("======response's log begin======\n"); 86 | 87 | String url = response.request().url().toString(); 88 | stringBuilder.append("url: ").append(url).append("\n"); 89 | stringBuilder.append("method: ").append(response.request().method()).append("\n"); 90 | stringBuilder.append("protocol: ").append(response.protocol()).append("\n"); 91 | stringBuilder.append("code: ").append(response.code()).append("\n"); 92 | stringBuilder.append("message: ").append(response.message()).append("\n"); 93 | 94 | ResponseBody responseBody = response.body(); 95 | if (responseBody != null) { 96 | MediaType mediaType = responseBody.contentType(); 97 | if (mediaType != null) { 98 | stringBuilder.append("response mediaType: ").append(mediaType.toString()).append("\n"); 99 | if (isTextMediaType(mediaType)) { 100 | try { 101 | String str=responseBody.string(); 102 | stringBuilder.append("responseBody's content: \n").append(str).append("\n"); 103 | newResponse=response.newBuilder().body(ResponseBody.create(mediaType,str)).build(); 104 | } catch (IOException e) { 105 | stringBuilder.append("responseBody's content: print error !!! ").append(e.getMessage()).append("\n"); 106 | } 107 | } else { 108 | stringBuilder.append("responseBody's content: maybe [file part] , ignored print !\n"); 109 | } 110 | } else { 111 | stringBuilder.append("response mediaType: mediaType is null !\n"); 112 | } 113 | } else { 114 | stringBuilder.append("responseBody: responseBody is null !\n"); 115 | } 116 | 117 | stringBuilder.append("======response's log end======"); 118 | Logger.d(stringBuilder.toString()); 119 | 120 | return newResponse; 121 | } 122 | 123 | 124 | private boolean isTextMediaType(MediaType mediaType) { 125 | if (mediaType.type().equals("text")) { 126 | return true; 127 | } 128 | if (mediaType.subtype() != null) { 129 | if (mediaType.subtype().equals("json") 130 | || mediaType.subtype().equals("xml") 131 | || mediaType.subtype().equals("html") 132 | || mediaType.subtype().equals("x-www-form-urlencoded") 133 | || mediaType.subtype().equals("webviewhtml") 134 | ) 135 | return true; 136 | } 137 | return false; 138 | } 139 | 140 | 141 | private String requestBodyToStr(Request request) { 142 | 143 | try { 144 | Request copy = request.newBuilder().build(); 145 | Buffer buffer = new Buffer(); 146 | copy.body().writeTo(buffer); 147 | return URLDecoder.decode(buffer.readUtf8(),"utf-8"); 148 | } catch (final IOException e) { 149 | return "something error when show requestBody:" + e.getMessage(); 150 | } 151 | 152 | } 153 | 154 | 155 | } 156 | -------------------------------------------------------------------------------- /app/src/main/java/com/devin/rxjava_retrofit/http/result/HttpRespException.java: -------------------------------------------------------------------------------- 1 | package com.devin.rxjava_retrofit.http.result; 2 | 3 | /** 4 | *

Description: 5 | *

6 | *

Created by Devin Sun on 2017/3/25. 7 | */ 8 | 9 | public class HttpRespException extends RuntimeException { 10 | 11 | private int httpStatus; 12 | private int code; 13 | 14 | public HttpRespException(String message, int httpStatus, int code) { 15 | super(message); 16 | this.httpStatus = httpStatus; 17 | this.code = code; 18 | } 19 | 20 | public int getCode() { 21 | return code; 22 | } 23 | 24 | public int getHttpStatus() { 25 | return httpStatus; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /app/src/main/java/com/devin/rxjava_retrofit/http/result/HttpRespResult.java: -------------------------------------------------------------------------------- 1 | package com.devin.rxjava_retrofit.http.result; 2 | 3 | /** 4 | *

Description: 5 | * 6 | *

Created by Devin Sun on 2017/3/25. 7 | */ 8 | 9 | public class HttpRespResult { 10 | 11 | private static final int SUCCESS_STATUS = 1; 12 | 13 | private String msg; 14 | private Integer state; 15 | private T result; 16 | 17 | public boolean isSuccess() { 18 | return state != null && state == SUCCESS_STATUS; 19 | } 20 | 21 | public String getMsg() { 22 | return msg; 23 | } 24 | 25 | public Integer getState() { 26 | return state; 27 | } 28 | 29 | public T getResult() { 30 | return result; 31 | } 32 | 33 | @Override 34 | public String toString() { 35 | return "HttpResponse{" + 36 | "msg='" + msg + '\'' + 37 | ", state=" + state + 38 | ", result=" + result + 39 | '}'; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /app/src/main/java/com/devin/rxjava_retrofit/http/result/HttpRespStatus.java: -------------------------------------------------------------------------------- 1 | package com.devin.rxjava_retrofit.http.result; 2 | 3 | /** 4 | * Description: 5 | * Company: 6 | * Email:bjxm2013@163.com 7 | * Created by Devin Sun on 2017/4/2. 8 | */ 9 | public interface HttpRespStatus { 10 | 11 | 12 | int NETWORK_ERROR = 0; 13 | String NETWORK_ERROR_MSG = "网络异常,请重试"; 14 | 15 | int DEFAULT_ERROR_CODE = -1024; 16 | String DEFAULT_ERROR_MSG = "数据处理异常,请重试"; 17 | 18 | 19 | int HTTP_RESP_SUCCESS_CODE = 200; 20 | String HTTP_RESP_SUCCESS_MSG = "请求成功"; 21 | 22 | 23 | int BAD_REQUEST_RESPONSE_CODE = 400; 24 | String BAD_REQUEST_RESPONSE_MSG = "参数错误"; 25 | 26 | int UNAUTHORIZED_RESPONSE_CODE = 401; 27 | String UNAUTHORIZED_RESPONSE_MSG = "用户权限非法"; 28 | 29 | int FORBIDDEN_RESPONSE_CODE = 403; 30 | String FORBIDDEN_RESPONSE_MSG = "禁止访问"; 31 | 32 | int NOT_FOUND_RESPONSE_CODE = 404; 33 | String NOT_FOUND_RESPONSE_MSG = "地址未找到"; 34 | 35 | int METHOD_NOT_ALLOWED_RESPONSE_CODE = 405; 36 | String METHOD_NOT_ALLOWED_RESPONSE_MSG = "请求方式错误"; 37 | 38 | int REQUEST_TIMEOUT_RESPONSE_CODE = 408; 39 | String EQUEST_TIMEOUT_RESPONSE_MSG = "请求超时"; 40 | 41 | int INTERNAL_SERVER_ERROR_RESPONSE_CODE = 500; 42 | String INTERNAL_SERVER_ERROR_RESPONSE_MSG = "内部服务器错误"; 43 | 44 | int BAD_GATEWAY_RESPONSE_CODE = 502; 45 | String BAD_GATEWAY_RESPONSE_MSG = "网关错误"; 46 | 47 | int SERVICE_UNAVAILABLE_RESPONSE_CODE = 503; 48 | String SERVICE_UNAVAILABLE_RESPONSE_MSG = "临时的服务器维护"; 49 | 50 | int GATEWAY_TIMEOUT_RESPONSE_CODE = 504; 51 | String GATEWAY_TIMEOUT_RESPONSE_MSG = "网关超时"; 52 | 53 | } 54 | -------------------------------------------------------------------------------- /app/src/main/java/com/devin/rxjava_retrofit/http/retrofit/RetrofitHelper.java: -------------------------------------------------------------------------------- 1 | package com.devin.rxjava_retrofit.http.retrofit; 2 | 3 | import com.devin.rxjava_retrofit.http.okhttp.OkHttpHelper; 4 | import com.devin.rxjava_retrofit.http.retrofit.converter.string.StringConverterFactory; 5 | import com.devin.rxjava_retrofit.http.service.ApiService; 6 | import retrofit2.Retrofit; 7 | import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; 8 | import retrofit2.converter.gson.GsonConverterFactory; 9 | 10 | /** 11 | *

Description: 12 | *

13 | *

Created by Devin Sun on 2017/3/24. 14 | */ 15 | 16 | public class RetrofitHelper { 17 | 18 | private static Retrofit retrofit; 19 | private RetrofitHelper() { 20 | } 21 | 22 | static { 23 | retrofit = new Retrofit.Builder() 24 | .baseUrl(ApiService.BASE_URL) 25 | .client(OkHttpHelper.getClient()) 26 | .addConverterFactory(StringConverterFactory.create()) //String 转换 27 | .addConverterFactory(GsonConverterFactory.create()) 28 | .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) 29 | .validateEagerly(true) 30 | .build(); 31 | } 32 | 33 | public static Retrofit getRetrofit() { 34 | return retrofit; 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /app/src/main/java/com/devin/rxjava_retrofit/http/retrofit/converter/string/StringConverterFactory.java: -------------------------------------------------------------------------------- 1 | package com.devin.rxjava_retrofit.http.retrofit.converter.string; 2 | 3 | import java.lang.annotation.Annotation; 4 | import java.lang.reflect.Type; 5 | 6 | import okhttp3.RequestBody; 7 | import okhttp3.ResponseBody; 8 | import retrofit2.Converter; 9 | import retrofit2.Retrofit; 10 | 11 | /** 12 | *

Description: 13 | * 14 | *

Created by Devin Sun on 2017/3/28. 15 | */ 16 | 17 | public final class StringConverterFactory extends Converter.Factory { 18 | 19 | public static StringConverterFactory create() { 20 | return new StringConverterFactory(); 21 | } 22 | 23 | @Override 24 | public Converter responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) { 25 | 26 | if (!String.class.equals(type)) { 27 | return null; 28 | } 29 | return new StringResponseBodyConverter(); 30 | } 31 | 32 | @Override 33 | public Converter requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) { 34 | 35 | if (!String.class.equals(type)) { 36 | return null; 37 | } 38 | return new StringRequestBodyConverter(); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /app/src/main/java/com/devin/rxjava_retrofit/http/retrofit/converter/string/StringRequestBodyConverter.java: -------------------------------------------------------------------------------- 1 | package com.devin.rxjava_retrofit.http.retrofit.converter.string; 2 | 3 | import java.io.IOException; 4 | import java.io.OutputStreamWriter; 5 | import java.io.Writer; 6 | import java.nio.charset.Charset; 7 | 8 | import okhttp3.MediaType; 9 | import okhttp3.RequestBody; 10 | import okio.Buffer; 11 | import retrofit2.Converter; 12 | 13 | /** 14 | *

Description: 15 | * 16 | *

Created by Devin Sun on 2017/3/28. 17 | */ 18 | 19 | public final class StringRequestBodyConverter implements Converter { 20 | 21 | private static final MediaType MEDIA_TYPE = MediaType.parse("application/json; charset=UTF-8"); 22 | private static final Charset UTF_8 = Charset.forName("UTF-8"); 23 | 24 | 25 | @Override 26 | public RequestBody convert(String value) throws IOException { 27 | 28 | Buffer buffer = new Buffer(); 29 | Writer writer = new OutputStreamWriter(buffer.outputStream(), UTF_8); 30 | writer.write(value); 31 | writer.close(); 32 | return RequestBody.create(MEDIA_TYPE, buffer.readByteString()); 33 | 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /app/src/main/java/com/devin/rxjava_retrofit/http/retrofit/converter/string/StringResponseBodyConverter.java: -------------------------------------------------------------------------------- 1 | package com.devin.rxjava_retrofit.http.retrofit.converter.string; 2 | 3 | import java.io.IOException; 4 | 5 | import okhttp3.ResponseBody; 6 | import retrofit2.Converter; 7 | 8 | /** 9 | *

Description: 10 | *

Created by Devin Sun on 2017/3/28. 11 | */ 12 | 13 | public final class StringResponseBodyConverter implements Converter { 14 | @Override 15 | public String convert(ResponseBody value) throws IOException { 16 | 17 | try { 18 | return value.string(); 19 | } finally { 20 | value.close(); 21 | } 22 | 23 | 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /app/src/main/java/com/devin/rxjava_retrofit/http/rxjava/observable/DialogTransformer.java: -------------------------------------------------------------------------------- 1 | package com.devin.rxjava_retrofit.http.rxjava.observable; 2 | 3 | import android.app.Activity; 4 | import android.app.ProgressDialog; 5 | import android.content.DialogInterface; 6 | 7 | import io.reactivex.Observable; 8 | import io.reactivex.ObservableSource; 9 | import io.reactivex.ObservableTransformer; 10 | import io.reactivex.annotations.NonNull; 11 | import io.reactivex.disposables.Disposable; 12 | import io.reactivex.functions.Action; 13 | import io.reactivex.functions.Consumer; 14 | 15 | /** 16 | * Description: 17 | * Company: 18 | * Email:bjxm2013@163.com 19 | * Created by Devin Sun on 2017/4/3. 20 | */ 21 | public class DialogTransformer { 22 | 23 | private static final String DEFAULT_MSG = "数据加载中..."; 24 | 25 | private Activity activity; 26 | private String msg; 27 | private boolean cancelable; 28 | 29 | public DialogTransformer(Activity activity) { 30 | this(activity, DEFAULT_MSG); 31 | } 32 | 33 | public DialogTransformer(Activity activity, String msg) { 34 | this(activity, msg, false); 35 | } 36 | 37 | public DialogTransformer(Activity activity, String msg, boolean cancelable) { 38 | this.activity = activity; 39 | this.msg = msg; 40 | this.cancelable = cancelable; 41 | } 42 | 43 | public ObservableTransformer showDialog() { 44 | return new ObservableTransformer() { 45 | private ProgressDialog progressDialog; 46 | @Override 47 | public ObservableSource apply(final Observable upstream) { 48 | 49 | return upstream.doOnSubscribe(new Consumer() { 50 | @Override 51 | public void accept(@NonNull final Disposable disposable) throws Exception { 52 | progressDialog = ProgressDialog.show(activity, null, msg, true, cancelable); 53 | if (cancelable) { 54 | progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { 55 | @Override 56 | public void onCancel(DialogInterface dialog) { 57 | disposable.dispose(); 58 | } 59 | }); 60 | } 61 | } 62 | }).doOnTerminate(new Action() { 63 | @Override 64 | public void run() throws Exception { 65 | if (progressDialog.isShowing()) { 66 | progressDialog.cancel(); 67 | } 68 | } 69 | }); 70 | } 71 | }; 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /app/src/main/java/com/devin/rxjava_retrofit/http/rxjava/observable/TransformerHelper.java: -------------------------------------------------------------------------------- 1 | package com.devin.rxjava_retrofit.http.rxjava.observable; 2 | 3 | import com.devin.rxjava_retrofit.http.result.HttpRespException; 4 | import com.devin.rxjava_retrofit.http.result.HttpRespResult; 5 | import com.devin.rxjava_retrofit.http.result.HttpRespStatus; 6 | 7 | import io.reactivex.Observable; 8 | import io.reactivex.ObservableSource; 9 | import io.reactivex.ObservableTransformer; 10 | import io.reactivex.android.schedulers.AndroidSchedulers; 11 | import io.reactivex.functions.Function; 12 | import io.reactivex.schedulers.Schedulers; 13 | 14 | /** 15 | *

Description: 16 | *

17 | *

Created by Devin Sun on 2017/3/29. 18 | */ 19 | 20 | public class TransformerHelper { 21 | 22 | 23 | public static ObservableTransformer, HttpRespResult> transformer() { 24 | return new ObservableTransformer, HttpRespResult>() { 25 | @Override 26 | public ObservableSource> apply(Observable> upstream) { 27 | return upstream.concatMap(TransformerHelper.checkCode()) 28 | .compose(TransformerHelper.>schedulerTransf()); 29 | } 30 | }; 31 | } 32 | 33 | /** 34 | * 根据HttpRespResult对象的code 判断是否为业务成功 35 | * 36 | * @param 37 | * @return 38 | */ 39 | public static Function, ObservableSource>> checkCode() { 40 | return new Function, ObservableSource>>() { 41 | @Override 42 | public ObservableSource> apply(HttpRespResult tHttpRespResult) throws Exception { 43 | if (tHttpRespResult.isSuccess()) { 44 | return Observable.just(tHttpRespResult); 45 | } else { 46 | return Observable.error(new HttpRespException(tHttpRespResult.getMsg(), HttpRespStatus.HTTP_RESP_SUCCESS_CODE, tHttpRespResult.getState())); 47 | } 48 | } 49 | }; 50 | } 51 | 52 | /** 53 | * 切换线程 54 | * 55 | * @param 56 | * @return 57 | */ 58 | public static ObservableTransformer schedulerTransf() { 59 | return new ObservableTransformer() { 60 | @Override 61 | public ObservableSource apply(Observable upstream) { 62 | return upstream 63 | .subscribeOn(Schedulers.io()) 64 | .observeOn(AndroidSchedulers.mainThread()); 65 | } 66 | }; 67 | } 68 | 69 | 70 | 71 | } 72 | -------------------------------------------------------------------------------- /app/src/main/java/com/devin/rxjava_retrofit/http/rxjava/observer/BaseObserver.java: -------------------------------------------------------------------------------- 1 | package com.devin.rxjava_retrofit.http.rxjava.observer; 2 | 3 | 4 | import com.devin.rxjava_retrofit.http.result.HttpRespException; 5 | import com.devin.rxjava_retrofit.http.result.HttpRespResult; 6 | import com.devin.rxjava_retrofit.http.result.HttpRespStatus; 7 | 8 | import io.reactivex.Observer; 9 | import io.reactivex.disposables.Disposable; 10 | import retrofit2.HttpException; 11 | 12 | /** 13 | *

Description: 14 | * Created by Devin Sun on 2017/4/3. 15 | */ 16 | public class BaseObserver implements Observer> { 17 | 18 | HttpRespException responseException; 19 | 20 | @Override 21 | public void onSubscribe(Disposable d) { 22 | 23 | } 24 | 25 | @Override 26 | public void onNext(HttpRespResult tHttpRespResult) { 27 | 28 | } 29 | 30 | @Override 31 | public void onError(Throwable e) { 32 | 33 | if (e instanceof HttpException) { 34 | HttpException httpException = (HttpException) e; 35 | responseException = new HttpRespException(HttpRespStatus.DEFAULT_ERROR_MSG, httpException.code(), HttpRespStatus.DEFAULT_ERROR_CODE); 36 | } else if (e instanceof HttpRespException) { 37 | responseException = (HttpRespException) e; 38 | } else {//其他或者没网会走这里 39 | responseException = new HttpRespException(HttpRespStatus.NETWORK_ERROR_MSG, HttpRespStatus.NETWORK_ERROR, HttpRespStatus.DEFAULT_ERROR_CODE); 40 | } 41 | 42 | } 43 | 44 | @Override 45 | public void onComplete() { 46 | 47 | } 48 | 49 | 50 | } 51 | -------------------------------------------------------------------------------- /app/src/main/java/com/devin/rxjava_retrofit/http/rxjava/observer/CommonObserver.java: -------------------------------------------------------------------------------- 1 | package com.devin.rxjava_retrofit.http.rxjava.observer; 2 | 3 | import com.devin.rxjava_retrofit.http.result.HttpRespException; 4 | import com.devin.rxjava_retrofit.http.result.HttpRespResult; 5 | import com.devin.rxjava_retrofit.util.ToastUtils; 6 | 7 | /** 8 | *

Description: 9 | * Created by Devin Sun on 2017/4/3. 10 | */ 11 | public abstract class CommonObserver extends BaseObserver { 12 | 13 | 14 | @Override 15 | public final void onNext(HttpRespResult tHttpRespResult) { 16 | onSuccess(tHttpRespResult.getResult()); 17 | } 18 | 19 | @Override 20 | public final void onError(Throwable e) { 21 | super.onError(e); 22 | onFailed(responseException); 23 | } 24 | 25 | public abstract void onSuccess(T t); 26 | 27 | public void onFailed(HttpRespException responseException) { 28 | ToastUtils.show(responseException.getMessage() + "(" + responseException.getHttpStatus() + "," + responseException.getCode() + ")"); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /app/src/main/java/com/devin/rxjava_retrofit/http/service/ApiService.java: -------------------------------------------------------------------------------- 1 | package com.devin.rxjava_retrofit.http.service; 2 | 3 | 4 | import com.devin.rxjava_retrofit.entity.LogisticsInfo; 5 | import com.devin.rxjava_retrofit.http.result.HttpRespResult; 6 | 7 | import java.util.List; 8 | import java.util.Map; 9 | 10 | import io.reactivex.Observable; 11 | import retrofit2.http.Body; 12 | import retrofit2.http.GET; 13 | import retrofit2.http.POST; 14 | 15 | /** 16 | *

Description: 17 | *

18 | *

Created by Devin Sun on 2017/3/25. 19 | */ 20 | 21 | public interface ApiService { 22 | 23 | 24 | 25 | String BASE_URL = "http://182.92.98.18"; 26 | 27 | String CHANEL = "test" + "/"; 28 | 29 | 30 | /** 31 | * 12306 32 | * 33 | * @return 34 | */ 35 | @GET("https://kyfw.12306.cn/otn/") 36 | Observable huoche(); 37 | 38 | 39 | /** 40 | * testGet1 41 | * 42 | * @return 43 | */ 44 | @GET("https://publicobject.com/helloworld.txt") 45 | Observable testGet1(); 46 | 47 | /** 48 | *testGet2 49 | * @return 50 | */ 51 | @GET("/muses-rest/java/rest/hotkeywordsearch/"+CHANEL) 52 | Observable>> testGet2(); 53 | 54 | 55 | /** 56 | * post test 57 | * 58 | * @param map 59 | * @return 60 | */ 61 | @POST("/muses-rest/java/rest/viewlogistics/"+CHANEL) 62 | Observable> getLogisticsInfo(@Body Map map); 63 | 64 | 65 | } 66 | -------------------------------------------------------------------------------- /app/src/main/java/com/devin/rxjava_retrofit/http/service/manager/ServiceManager.java: -------------------------------------------------------------------------------- 1 | package com.devin.rxjava_retrofit.http.service.manager; 2 | 3 | 4 | import com.devin.rxjava_retrofit.http.retrofit.RetrofitHelper; 5 | import com.devin.rxjava_retrofit.http.service.ApiService; 6 | 7 | /** 8 | *

Description: 9 | *

10 | *

Created by Devin Sun on 2017/3/29. 11 | */ 12 | 13 | public class ServiceManager { 14 | 15 | public static ApiService getApiService() { 16 | return RetrofitHelper.getRetrofit().create(ApiService.class); 17 | } 18 | 19 | 20 | public static T getService(Class service) { 21 | return RetrofitHelper.getRetrofit().create(service); 22 | } 23 | 24 | 25 | } 26 | -------------------------------------------------------------------------------- /app/src/main/java/com/devin/rxjava_retrofit/util/Logger.java: -------------------------------------------------------------------------------- 1 | package com.devin.rxjava_retrofit.util; 2 | 3 | import android.support.annotation.IntDef; 4 | import android.util.Log; 5 | 6 | import java.lang.annotation.Retention; 7 | import java.lang.annotation.RetentionPolicy; 8 | import java.util.ArrayList; 9 | import java.util.List; 10 | 11 | public class Logger { 12 | 13 | public static boolean log_enabled = true; 14 | private static final String DEFAULT_TAG = "----------"; 15 | 16 | private static final int DEBUG = 1; 17 | private static final int ERROR = 2; 18 | 19 | @IntDef({DEBUG, ERROR}) 20 | @Retention(RetentionPolicy.SOURCE) 21 | private @interface LogPriority { 22 | } 23 | 24 | private static final int MSG_MAX_LENGTH = 800; 25 | 26 | 27 | 28 | public static void d(String msg) { 29 | d(DEFAULT_TAG, msg); 30 | } 31 | 32 | public static void d(String tag, String msg) { 33 | d(tag, msg, null); 34 | } 35 | 36 | 37 | public static void d(String tag, String msg, Throwable tr) { 38 | printLog(tag,msg,tr,DEBUG); 39 | } 40 | 41 | 42 | public static void e(String msg) { 43 | e(DEFAULT_TAG, msg); 44 | } 45 | 46 | public static void e(String tag, String msg) { 47 | e(tag, msg, null); 48 | } 49 | 50 | public static void e(String tag, String msg, Throwable tr) { 51 | printLog(tag, msg, tr, ERROR); 52 | } 53 | 54 | /** 55 | * 打印最终的日志 56 | * 57 | * @param tag tag 58 | * @param msg msg 59 | * @param tr Throwable 60 | * @param logPriority logPriority 61 | */ 62 | private static void printLog(String tag, String msg, Throwable tr, @LogPriority int logPriority) { 63 | if (!log_enabled) return; 64 | if (logPriority == DEBUG) { 65 | Log.d(tag, "__________________________________"); 66 | } else { 67 | Log.e(tag, "__________________________________"); 68 | } 69 | printLogLocation(tag); 70 | 71 | for (String str : splitLargeMsg(msg)) { 72 | if (logPriority == DEBUG) { 73 | Log.d(tag, str+"\t"); 74 | } else { 75 | Log.e(tag, str+"\t"); 76 | } 77 | } 78 | 79 | if (tr != null) { 80 | if (logPriority == DEBUG) { 81 | Log.d(tag, "", tr); 82 | } else { 83 | Log.e(tag, "", tr); 84 | } 85 | } 86 | 87 | if (logPriority == DEBUG) { 88 | Log.d(tag, "===================================="); 89 | } else { 90 | Log.e(tag, "===================================="); 91 | } 92 | } 93 | 94 | 95 | /** 96 | * 将比较长的msg 分割为 string list 97 | * 98 | * @param msg msg 99 | * @return string list 100 | */ 101 | private static List splitLargeMsg(String msg) { 102 | List stringList = new ArrayList<>(); 103 | int msgLength = msg.length(); 104 | int beginIndex = 0; 105 | while (beginIndex < msgLength) { 106 | int endIndex = Math.min(msgLength, beginIndex + MSG_MAX_LENGTH); 107 | stringList.add(msg.substring(beginIndex, endIndex)); 108 | beginIndex = endIndex; 109 | } 110 | return stringList; 111 | } 112 | 113 | 114 | 115 | /** 116 | * 打印log 的调用地址 117 | * 118 | * @param tag tag 119 | */ 120 | private static void printLogLocation(String tag) { 121 | StackTraceElement stackTraceElement = getTargetStackTraceElement(); 122 | Log.e(tag, "log location →(" + stackTraceElement.getFileName() + ":" + stackTraceElement.getLineNumber() + ")"); 123 | } 124 | 125 | 126 | /** 127 | * 因为我们的入口是Logger的方法,所以,我们直接遍历,Logger类相关的下一个非Logger类的栈帧信息就是具体调用的方法。 128 | * 129 | * @return StackTraceElement 130 | */ 131 | private static StackTraceElement getTargetStackTraceElement() { 132 | // find the target invoked method 133 | StackTraceElement targetStackTrace = null; 134 | boolean shouldTrace = false; 135 | StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); 136 | for (StackTraceElement stackTraceElement : stackTrace) { 137 | boolean isLogMethod = stackTraceElement.getClassName().equals(Logger.class.getName()); 138 | if (shouldTrace && !isLogMethod) { 139 | targetStackTrace = stackTraceElement; 140 | break; 141 | } 142 | shouldTrace = isLogMethod; 143 | } 144 | return targetStackTrace; 145 | } 146 | } 147 | -------------------------------------------------------------------------------- /app/src/main/java/com/devin/rxjava_retrofit/util/ToastUtils.java: -------------------------------------------------------------------------------- 1 | package com.devin.rxjava_retrofit.util; 2 | 3 | import android.support.annotation.StringRes; 4 | import android.view.Gravity; 5 | import android.widget.Toast; 6 | 7 | import com.devin.rxjava_retrofit.MyApplication; 8 | 9 | 10 | public class ToastUtils { 11 | 12 | private static Toast toast; 13 | 14 | public static void show(String text) { 15 | if (toast == null) { 16 | toast = Toast.makeText(MyApplication.getInstance(), "", Toast.LENGTH_SHORT); 17 | toast.setGravity(Gravity.CENTER, 0, 0); 18 | } 19 | toast.setText(text); 20 | toast.show(); 21 | } 22 | 23 | public static void show(@StringRes int resId) { 24 | show(MyApplication.getInstance().getResources().getString(resId)); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 10 |