Repository: amitshekhariitbhu/AndroidNetworking Branch: master Commit: 508e7c5b4338 Files: 203 Total size: 1.0 MB Directory structure: gitextract_9srekgqo/ ├── .gitignore ├── .travis.yml ├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── android-networking/ │ ├── .gitignore │ ├── build.gradle │ ├── proguard-rules.pro │ └── src/ │ ├── androidTest/ │ │ ├── AndroidManifest.xml │ │ └── java/ │ │ └── com/ │ │ └── androidnetworking/ │ │ ├── GetJSONApiTest.java │ │ ├── GetObjectApiTest.java │ │ ├── GetStringApiTest.java │ │ ├── MultipartJSONApiTest.java │ │ ├── MultipartObjectApiTest.java │ │ ├── MultipartStringApiTest.java │ │ ├── PostJSONApiTest.java │ │ ├── PostObjectApiTest.java │ │ ├── PostStringApiTest.java │ │ └── model/ │ │ └── User.java │ ├── main/ │ │ ├── AndroidManifest.xml │ │ ├── java/ │ │ │ └── com/ │ │ │ └── androidnetworking/ │ │ │ ├── AndroidNetworking.java │ │ │ ├── cache/ │ │ │ │ ├── LruBitmapCache.java │ │ │ │ └── LruCache.java │ │ │ ├── common/ │ │ │ │ ├── ANConstants.java │ │ │ │ ├── ANRequest.java │ │ │ │ ├── ANResponse.java │ │ │ │ ├── ConnectionClassManager.java │ │ │ │ ├── ConnectionQuality.java │ │ │ │ ├── Method.java │ │ │ │ ├── Priority.java │ │ │ │ ├── RequestBuilder.java │ │ │ │ ├── RequestType.java │ │ │ │ └── ResponseType.java │ │ │ ├── core/ │ │ │ │ ├── ANExecutor.java │ │ │ │ ├── Core.java │ │ │ │ ├── DefaultExecutorSupplier.java │ │ │ │ ├── ExecutorSupplier.java │ │ │ │ ├── MainThreadExecutor.java │ │ │ │ └── PriorityThreadFactory.java │ │ │ ├── error/ │ │ │ │ └── ANError.java │ │ │ ├── gsonparserfactory/ │ │ │ │ ├── GsonParserFactory.java │ │ │ │ ├── GsonRequestBodyParser.java │ │ │ │ └── GsonResponseBodyParser.java │ │ │ ├── interceptors/ │ │ │ │ ├── GzipRequestInterceptor.java │ │ │ │ └── HttpLoggingInterceptor.java │ │ │ ├── interfaces/ │ │ │ │ ├── AnalyticsListener.java │ │ │ │ ├── BitmapRequestListener.java │ │ │ │ ├── ConnectionQualityChangeListener.java │ │ │ │ ├── DownloadListener.java │ │ │ │ ├── DownloadProgressListener.java │ │ │ │ ├── JSONArrayRequestListener.java │ │ │ │ ├── JSONObjectRequestListener.java │ │ │ │ ├── OkHttpResponseAndBitmapRequestListener.java │ │ │ │ ├── OkHttpResponseAndJSONArrayRequestListener.java │ │ │ │ ├── OkHttpResponseAndJSONObjectRequestListener.java │ │ │ │ ├── OkHttpResponseAndParsedRequestListener.java │ │ │ │ ├── OkHttpResponseAndStringRequestListener.java │ │ │ │ ├── OkHttpResponseListener.java │ │ │ │ ├── ParsedRequestListener.java │ │ │ │ ├── Parser.java │ │ │ │ ├── StringRequestListener.java │ │ │ │ └── UploadProgressListener.java │ │ │ ├── internal/ │ │ │ │ ├── ANImageLoader.java │ │ │ │ ├── ANRequestQueue.java │ │ │ │ ├── DownloadProgressHandler.java │ │ │ │ ├── InternalNetworking.java │ │ │ │ ├── InternalRunnable.java │ │ │ │ ├── RequestProgressBody.java │ │ │ │ ├── ResponseProgressBody.java │ │ │ │ ├── SynchronousCall.java │ │ │ │ └── UploadProgressHandler.java │ │ │ ├── model/ │ │ │ │ ├── MultipartFileBody.java │ │ │ │ ├── MultipartStringBody.java │ │ │ │ └── Progress.java │ │ │ ├── utils/ │ │ │ │ ├── ParseUtil.java │ │ │ │ ├── SourceCloseUtil.java │ │ │ │ └── Utils.java │ │ │ └── widget/ │ │ │ └── ANImageView.java │ │ └── res/ │ │ └── values/ │ │ └── strings.xml │ └── test/ │ └── java/ │ └── com/ │ └── androidnetworking/ │ └── ExampleUnitTest.java ├── app/ │ ├── .gitignore │ ├── build.gradle │ ├── proguard-rules.pro │ └── src/ │ ├── androidTest/ │ │ └── java/ │ │ └── com/ │ │ └── androidnetworking/ │ │ └── ApplicationTest.java │ ├── main/ │ │ ├── AndroidManifest.xml │ │ ├── java/ │ │ │ └── com/ │ │ │ └── networking/ │ │ │ ├── ApiEndPoint.java │ │ │ ├── ApiTestActivity.java │ │ │ ├── ImageGridActivity.java │ │ │ ├── MainActivity.java │ │ │ ├── MyApplication.java │ │ │ ├── OkHttpResponseTestActivity.java │ │ │ ├── WebSocketActivity.java │ │ │ ├── fragments/ │ │ │ │ └── ImageGridFragment.java │ │ │ ├── model/ │ │ │ │ └── User.java │ │ │ ├── provider/ │ │ │ │ └── Images.java │ │ │ └── utils/ │ │ │ └── Utils.java │ │ └── res/ │ │ ├── drawable/ │ │ │ └── photogrid_list_selector.xml │ │ ├── layout/ │ │ │ ├── activity_api_test.xml │ │ │ ├── activity_main.xml │ │ │ ├── activity_web_socket.xml │ │ │ └── image_grid_fragment.xml │ │ ├── values/ │ │ │ ├── colors.xml │ │ │ ├── dimens.xml │ │ │ ├── strings.xml │ │ │ └── styles.xml │ │ └── values-w820dp/ │ │ └── dimens.xml │ └── test/ │ └── java/ │ └── com/ │ └── androidnetworking/ │ └── ExampleUnitTest.java ├── build.gradle ├── gradle/ │ └── wrapper/ │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradle.properties ├── gradlew ├── gradlew.bat ├── jackson-android-networking/ │ ├── .gitignore │ ├── build.gradle │ ├── proguard-rules.pro │ └── src/ │ ├── androidTest/ │ │ ├── AndroidManifest.xml │ │ └── java/ │ │ └── com/ │ │ └── jacksonandroidnetworking/ │ │ ├── JacksonGetObjectApiTest.java │ │ ├── JacksonPostObjectApiTest.java │ │ └── model/ │ │ └── User.java │ ├── main/ │ │ ├── AndroidManifest.xml │ │ ├── java/ │ │ │ └── com/ │ │ │ └── jacksonandroidnetworking/ │ │ │ ├── JacksonParserFactory.java │ │ │ ├── JacksonRequestBodyParser.java │ │ │ └── JacksonResponseBodyParser.java │ │ └── res/ │ │ └── values/ │ │ └── strings.xml │ └── test/ │ └── java/ │ └── com/ │ └── jacksonandroidnetworking/ │ └── ExampleUnitTest.java ├── rx-android-networking/ │ ├── .gitignore │ ├── build.gradle │ ├── proguard-rules.pro │ └── src/ │ ├── androidTest/ │ │ └── java/ │ │ └── com/ │ │ └── rxandroidnetworking/ │ │ └── ApplicationTest.java │ ├── main/ │ │ ├── AndroidManifest.xml │ │ ├── java/ │ │ │ └── com/ │ │ │ └── rxandroidnetworking/ │ │ │ ├── RxANRequest.java │ │ │ ├── RxAndroidNetworking.java │ │ │ └── RxInternalNetworking.java │ │ └── res/ │ │ └── values/ │ │ └── strings.xml │ └── test/ │ └── java/ │ └── com/ │ └── rxandroidnetworking/ │ └── ExampleUnitTest.java ├── rx2-android-networking/ │ ├── .gitignore │ ├── build.gradle │ ├── proguard-rules.pro │ └── src/ │ ├── androidTest/ │ │ ├── AndroidManifest.xml │ │ └── java/ │ │ └── com/ │ │ └── rx2androidnetworking/ │ │ ├── Rx2GetJSONApiTest.java │ │ ├── Rx2GetObjectApiTest.java │ │ ├── Rx2GetStringApiTest.java │ │ ├── Rx2MultipartJSONApiTest.java │ │ ├── Rx2MultipartObjectApiTest.java │ │ ├── Rx2MultipartStringApiTest.java │ │ ├── Rx2PostJSONApiTest.java │ │ ├── Rx2PostObjectApiTest.java │ │ ├── Rx2PostStringApiTest.java │ │ └── model/ │ │ └── User.java │ ├── main/ │ │ ├── AndroidManifest.xml │ │ ├── java/ │ │ │ └── com/ │ │ │ └── rx2androidnetworking/ │ │ │ ├── Rx2ANRequest.java │ │ │ ├── Rx2AndroidNetworking.java │ │ │ └── Rx2InternalNetworking.java │ │ └── res/ │ │ └── values/ │ │ └── strings.xml │ └── test/ │ └── java/ │ └── com/ │ └── rx2androidnetworking/ │ └── ExampleUnitTest.java ├── rx2sampleapp/ │ ├── .gitignore │ ├── build.gradle │ ├── proguard-rules.pro │ └── src/ │ ├── androidTest/ │ │ └── java/ │ │ └── com/ │ │ └── rx2sampleapp/ │ │ └── ExampleInstrumentedTest.java │ ├── main/ │ │ ├── AndroidManifest.xml │ │ ├── java/ │ │ │ └── com/ │ │ │ └── rx2sampleapp/ │ │ │ ├── ApiEndPoint.java │ │ │ ├── Rx2ApiTestActivity.java │ │ │ ├── Rx2MyApplication.java │ │ │ ├── Rx2OperatorExampleActivity.java │ │ │ ├── SubscriptionActivity.java │ │ │ ├── model/ │ │ │ │ ├── ApiUser.java │ │ │ │ ├── User.java │ │ │ │ └── UserDetail.java │ │ │ └── utils/ │ │ │ └── Utils.java │ │ └── res/ │ │ ├── layout/ │ │ │ ├── activity_rx_api_test.xml │ │ │ ├── activity_rx_operator_example.xml │ │ │ └── activity_subscription.xml │ │ ├── values/ │ │ │ ├── colors.xml │ │ │ ├── dimens.xml │ │ │ ├── strings.xml │ │ │ └── styles.xml │ │ └── values-w820dp/ │ │ └── dimens.xml │ └── test/ │ └── java/ │ └── com/ │ └── rx2sampleapp/ │ └── ExampleUnitTest.java ├── rxsampleapp/ │ ├── .gitignore │ ├── build.gradle │ ├── proguard-rules.pro │ └── src/ │ ├── androidTest/ │ │ └── java/ │ │ └── com/ │ │ └── rxsampleapp/ │ │ └── ApplicationTest.java │ ├── main/ │ │ ├── AndroidManifest.xml │ │ ├── java/ │ │ │ └── com/ │ │ │ └── rxsampleapp/ │ │ │ ├── ApiEndPoint.java │ │ │ ├── RxApiTestActivity.java │ │ │ ├── RxMyApplication.java │ │ │ ├── RxOperatorExampleActivity.java │ │ │ ├── SubscriptionActivity.java │ │ │ ├── model/ │ │ │ │ ├── ApiUser.java │ │ │ │ ├── User.java │ │ │ │ └── UserDetail.java │ │ │ └── utils/ │ │ │ └── Utils.java │ │ └── res/ │ │ ├── layout/ │ │ │ ├── activity_rx_api_test.xml │ │ │ ├── activity_rx_operator_example.xml │ │ │ └── activity_subscription.xml │ │ └── values/ │ │ ├── colors.xml │ │ ├── dimens.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── test/ │ └── java/ │ └── com/ │ └── rxsampleapp/ │ └── ExampleUnitTest.java └── settings.gradle ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ *.iml .gradle /local.properties /.idea/workspace.xml /.idea/libraries .DS_Store /build /captures /.idea ================================================ FILE: .travis.yml ================================================ language: android env: global: - ADB_INSTALL_TIMEOUT=30 # Using the new Container-Based Infrastructure - sudo: false # Turning off caching to avoid caching Issues - cache: false # Initiating clean Gradle output - TERM=dumb # Giving even more memory to Gradle JVM - GRADLE_OPTS="-Xmx2048m -XX:MaxPermSize=1024m" android: components: - tools - platform-tools - build-tools-27.0.3 - android-27 - android-24 - android-23 - android-22 - extra-google-google_play_services - extra-google-m2repository - extra-android-m2repository - sys-img-armeabi-v7a-android-22 # Emulator Management: Create, Start and Wait before_script: - echo no | android create avd --force -n test -t android-22 --abi armeabi-v7a -c 32M - emulator -avd test -no-audio -no-window & - android-wait-for-emulator - sleep 180 - adb devices - adb shell input keyevent 82 & script: - ./gradlew connectedAndroidTest ================================================ FILE: CHANGELOG.md ================================================ Change Log ========== Version 1.0.2 *(2018-07-10)* ---------------------------- * New: Add support for multiple file upload with same key * New: Add support for multi contentType in multipart * Bump OkHttp Version to 3.10.0 * Bump other dependencies Version 1.0.1 *(2017-12-20)* ---------------------------- * New: Add support for `Single`, `Completable`, `Flowable`, `Maybe` Observable * New: Add support for OPTIONS request * Bump OkHttp Version to 3.9.1 * Bump other dependencies * New: Add support for specifying request method dynamically * New: Add API to check isRequestRunning * Fix: Add more than one values for one key in header and query * Merge pull requests Version 1.0.0 *(2017-03-19)* ---------------------------- * Fix: Progress bug for large files download * Merge pull requests * New: Add new API * Bump OkHttp Version to 3.6.0 * New: Add config options for BitmapDecode * New: Add Consumer Proguard Version 0.4.0 *(2017-02-01)* ---------------------------- * New: RxJava2 Support [link](https://amitshekhariitbhu.github.io/Fast-Android-Networking/rxjava2_support.html) * New: Add Java Object directly in any request [link](https://amitshekhariitbhu.github.io/Fast-Android-Networking/post_request.html) * New: Java Object is supported for query parameter, headers also * Update OkHttp to 3.5.0 * Fix: Allow all Map implementations * New: Add better logging of request * New: Get parsed error body [link](https://amitshekhariitbhu.github.io/Fast-Android-Networking/error_code_handling.html) * Merged pull requests Version 0.3.0 *(2016-11-07)* ---------------------------- * Fix: Few minor bug fixes * Remove unwanted tags from manifest file Version 0.2.0 *(2016-09-16)* ---------------------------- * New: Jackson Parser Support * New: Making Synchronous Request - [Check Here](https://amitshekhariitbhu.github.io/Fast-Android-Networking/synchronous_request.html) * New: setContentType("application/json; charset=utf-8") in POST and Multipart request. * New: Getting OkHttpResponse in Response to access headers - [Check Here](https://amitshekhariitbhu.github.io/Fast-Android-Networking/getting_okhttpresponse.html) * Bug fixes : As always we are squashing bugs. * New: Few other features which are request by the fans of Fast Android Networking. Version 0.1.0 *(2016-07-31)* ---------------------------- * New: RxJava Support For Fast-Android-Networking * New: Now RxJava can be used with Fast-Android-Networking * New: Operators like `flatMap`, `filter`, `map`, `zip`, etc can be used easily with Fast-Android-Networking. * New: Chaining of Requests can be done. * New: Requests can be bind with Activity-Lifecycle. * New: Java Object Parsing Support Version 0.0.1 *(2016-06-03)* ---------------------------- Initial release. ================================================ FILE: CONTRIBUTING.md ================================================ # Contributing 1. Fork it! 2. Checkout the development branch: `git checkout development` 3. Create your feature branch: `git checkout -b my-new-feature` 4. Add your changes to the index: `git add .` 5. Commit your changes: `git commit -m 'Add some feature'` 6. Push to the branch: `git push origin my-new-feature` 7. Submit a pull request against the `development` branch ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: README.md ================================================ # Fast Android Networking Library ### About Fast Android Networking Library Fast Android Networking Library is a powerful library for doing any type of networking in Android applications which is made on top of [OkHttp Networking Layer](http://square.github.io/okhttp/). Fast Android Networking Library takes care of each and everything. So you don't have to do anything, just make request and listen for the response. ### Why use Fast Android Networking ? * Recent removal of HttpClient in Android Marshmallow(Android M) made other networking libraries obsolete. * No other single library does each and everything like making request, downloading any type of file, uploading file, loading image from network in ImageView, etc. There are some libraries but they are outdated. * No other library provides simple interface for doing all types of things in networking like setting priority, cancelling, etc. * As it uses [Okio](https://github.com/square/okio) , No more GC overhead in android applications. [Okio](https://github.com/square/okio) is made to handle GC overhead while allocating memory. [Okio](https://github.com/square/okio) does some clever things to save CPU and memory. * It uses [OkHttp](http://square.github.io/okhttp/) , more importantly it supports HTTP/2. ## About me Hi, I am Amit Shekhar, Founder @ [Outcome School](https://outcomeschool.com) • IIT 2010-14 • I have taught and mentored many developers, and their efforts landed them high-paying tech jobs, helped many tech companies in solving their unique problems, and created many open-source libraries being used by top companies. I am passionate about sharing knowledge through open-source, blogs, and videos. ### Follow Amit Shekhar - [X/Twitter](https://twitter.com/amitiitbhu) - [LinkedIn](https://www.linkedin.com/in/amit-shekhar-iitbhu) - [GitHub](https://github.com/amitshekhariitbhu) ### Follow Outcome School - [YouTube](https://youtube.com/@OutcomeSchool) - [X/Twitter](https://x.com/outcome_school) - [LinkedIn](https://www.linkedin.com/company/outcomeschool) - [GitHub](http://github.com/OutcomeSchool) ## I teach at Outcome School - [AI and Machine Learning](https://outcomeschool.com/program/ai-and-machine-learning) - [Android](https://outcomeschool.com/program/android) Join Outcome School and get a high-paying tech job: [Outcome School](https://outcomeschool.com) ## [Outcome School Blog](https://outcomeschool.com/blog) - High-quality content to learn Android concepts. ### RxJava2 Support, [check here](https://amitshekhariitbhu.github.io/Fast-Android-Networking/rxjava2_support.html). ### Find this project useful ? :heart: * Support it by clicking the :star: button on the upper right of this page. :v: For full details, visit the documentation on our web site : ## Requirements Fast Android Networking Library can be included in any Android application. Fast Android Networking Library supports Android 2.3 (Gingerbread) and later. ## Using Fast Android Networking Library in your application Add this in your `settings.gradle`: ```groovy maven { url 'https://jitpack.io' } ``` If you are using `settings.gradle.kts`, add the following: ```kotlin maven { setUrl("https://jitpack.io") } ``` Add this in your `build.gradle` ```groovy implementation 'com.github.amitshekhariitbhu.Fast-Android-Networking:android-networking:1.0.4' ``` If you are using `build.gradle.kts`, add the following: ```kotlin implementation("com.github.amitshekhariitbhu.Fast-Android-Networking:android-networking:1.0.4") ``` Do not forget to add internet permission in manifest if already not present ```xml ``` Then initialize it in onCreate() Method of application class : ```java AndroidNetworking.initialize(getApplicationContext()); ``` Initializing it with some customization , as it uses [OkHttp](http://square.github.io/okhttp/) as networking layer, you can pass custom okHttpClient while initializing it. ```java // Adding an Network Interceptor for Debugging purpose : OkHttpClient okHttpClient = new OkHttpClient() .newBuilder() .addNetworkInterceptor(new StethoInterceptor()) .build(); AndroidNetworking.initialize(getApplicationContext(),okHttpClient); ``` Using the Fast Android Networking with Jackson Parser Add this in your `build.gradle` ```groovy implementation 'com.github.amitshekhariitbhu.Fast-Android-Networking:jackson-android-networking:1.0.4' ``` If you are using `build.gradle.kts`, add the following: ```kotlin implementation("com.github.amitshekhariitbhu.Fast-Android-Networking:jackson-android-networking:1.0.4") ``` ```java // Then set the JacksonParserFactory like below AndroidNetworking.setParserFactory(new JacksonParserFactory()); ``` Using the Fast Android Networking with RxJava2 Add this in your `build.gradle` ```groovy implementation 'com.github.amitshekhariitbhu.Fast-Android-Networking:rx2-android-networking:1.0.4' ``` If you are using `build.gradle.kts`, add the following: ```kotlin implementation("com.github.amitshekhariitbhu.Fast-Android-Networking:rx2-android-networking:1.0.4") ``` Using the Fast Android Networking with RxJava Add this in your `build.gradle` ```groovy implementation 'com.github.amitshekhariitbhu.Fast-Android-Networking:rx-android-networking:1.0.4' ``` If you are using `build.gradle.kts`, add the following: ```kotlin implementation("com.github.amitshekhariitbhu.Fast-Android-Networking:rx-android-networking:1.0.4") ``` ### Making a GET Request ```java AndroidNetworking.get("https://fierce-cove-29863.herokuapp.com/getAllUsers/{pageNumber}") .addPathParameter("pageNumber", "0") .addQueryParameter("limit", "3") .addHeaders("token", "1234") .setTag("test") .setPriority(Priority.LOW) .build() .getAsJSONArray(new JSONArrayRequestListener() { @Override public void onResponse(JSONArray response) { // do anything with response } @Override public void onError(ANError error) { // handle error } }); ``` ### Making a POST Request ```java AndroidNetworking.post("https://fierce-cove-29863.herokuapp.com/createAnUser") .addBodyParameter("firstname", "Amit") .addBodyParameter("lastname", "Shekhar") .setTag("test") .setPriority(Priority.MEDIUM) .build() .getAsJSONObject(new JSONObjectRequestListener() { @Override public void onResponse(JSONObject response) { // do anything with response } @Override public void onError(ANError error) { // handle error } }); ``` You can also post java object, json, file, etc in POST request like this. ```java User user = new User(); user.firstname = "Amit"; user.lastname = "Shekhar"; AndroidNetworking.post("https://fierce-cove-29863.herokuapp.com/createUser") .addBodyParameter(user) // posting java object .setTag("test") .setPriority(Priority.MEDIUM) .build() .getAsJSONArray(new JSONArrayRequestListener() { @Override public void onResponse(JSONArray response) { // do anything with response } @Override public void onError(ANError error) { // handle error } }); JSONObject jsonObject = new JSONObject(); try { jsonObject.put("firstname", "Amit"); jsonObject.put("lastname", "Shekhar"); } catch (JSONException e) { e.printStackTrace(); } AndroidNetworking.post("https://fierce-cove-29863.herokuapp.com/createUser") .addJSONObjectBody(jsonObject) // posting json .setTag("test") .setPriority(Priority.MEDIUM) .build() .getAsJSONArray(new JSONArrayRequestListener() { @Override public void onResponse(JSONArray response) { // do anything with response } @Override public void onError(ANError error) { // handle error } }); AndroidNetworking.post("https://fierce-cove-29863.herokuapp.com/postFile") .addFileBody(file) // posting any type of file .setTag("test") .setPriority(Priority.MEDIUM) .build() .getAsJSONObject(new JSONObjectRequestListener() { @Override public void onResponse(JSONObject response) { // do anything with response } @Override public void onError(ANError error) { // handle error } }); ``` ### Using it with your own JAVA Object - JSON Parser ```java /*--------------Example One -> Getting the userList----------------*/ AndroidNetworking.get("https://fierce-cove-29863.herokuapp.com/getAllUsers/{pageNumber}") .addPathParameter("pageNumber", "0") .addQueryParameter("limit", "3") .setTag(this) .setPriority(Priority.LOW) .build() .getAsObjectList(User.class, new ParsedRequestListener>() { @Override public void onResponse(List users) { // do anything with response Log.d(TAG, "userList size : " + users.size()); for (User user : users) { Log.d(TAG, "id : " + user.id); Log.d(TAG, "firstname : " + user.firstname); Log.d(TAG, "lastname : " + user.lastname); } } @Override public void onError(ANError anError) { // handle error } }); /*--------------Example Two -> Getting an user----------------*/ AndroidNetworking.get("https://fierce-cove-29863.herokuapp.com/getAnUserDetail/{userId}") .addPathParameter("userId", "1") .setTag(this) .setPriority(Priority.LOW) .build() .getAsObject(User.class, new ParsedRequestListener() { @Override public void onResponse(User user) { // do anything with response Log.d(TAG, "id : " + user.id); Log.d(TAG, "firstname : " + user.firstname); Log.d(TAG, "lastname : " + user.lastname); } @Override public void onError(ANError anError) { // handle error } }); /*-- Note : YourObject.class, getAsObject and getAsObjectList are important here --*/ ``` ### Downloading a file from server ```java AndroidNetworking.download(url,dirPath,fileName) .setTag("downloadTest") .setPriority(Priority.MEDIUM) .build() .setDownloadProgressListener(new DownloadProgressListener() { @Override public void onProgress(long bytesDownloaded, long totalBytes) { // do anything with progress } }) .startDownload(new DownloadListener() { @Override public void onDownloadComplete() { // do anything after completion } @Override public void onError(ANError error) { // handle error } }); ``` ### Uploading a file to server ```java AndroidNetworking.upload(url) .addMultipartFile("image",file) .addMultipartParameter("key","value") .setTag("uploadTest") .setPriority(Priority.HIGH) .build() .setUploadProgressListener(new UploadProgressListener() { @Override public void onProgress(long bytesUploaded, long totalBytes) { // do anything with progress } }) .getAsJSONObject(new JSONObjectRequestListener() { @Override public void onResponse(JSONObject response) { // do anything with response } @Override public void onError(ANError error) { // handle error } }); ``` ### Getting Response and completion in an another thread executor (Note : Error and Progress will always be returned in main thread of application) ```java AndroidNetworking.upload(url) .addMultipartFile("image",file) .addMultipartParameter("key","value") .setTag("uploadTest") .setPriority(Priority.HIGH) .build() .setExecutor(Executors.newSingleThreadExecutor()) // setting an executor to get response or completion on that executor thread .setUploadProgressListener(new UploadProgressListener() { @Override public void onProgress(long bytesUploaded, long totalBytes) { // do anything with progress } }) .getAsJSONObject(new JSONObjectRequestListener() { @Override public void onResponse(JSONObject response) { // below code will be executed in the executor provided // do anything with response } @Override public void onError(ANError error) { // handle error } }); ``` ### Setting a Percentage Threshold For Not Cancelling the request if it has completed the given threshold ```java AndroidNetworking.download(url,dirPath,fileName) .setTag("downloadTest") .setPriority(Priority.MEDIUM) .setPercentageThresholdForCancelling(50) // even if at the time of cancelling it will not cancel if 50% .build() // downloading is done.But can be cancalled with forceCancel. .setDownloadProgressListener(new DownloadProgressListener() { @Override public void onProgress(long bytesDownloaded, long totalBytes) { // do anything with progress } }) .startDownload(new DownloadListener() { @Override public void onDownloadComplete() { // do anything after completion } @Override public void onError(ANError error) { // handle error } }); ``` ### Cancelling a request. Any request with a given tag can be cancelled. Just do like this. ```java AndroidNetworking.cancel("tag"); // All the requests with the given tag will be cancelled. AndroidNetworking.forceCancel("tag"); // All the requests with the given tag will be cancelled , even if any percent threshold is // set , it will be cancelled forcefully. AndroidNetworking.cancelAll(); // All the requests will be cancelled. AndroidNetworking.forceCancelAll(); // All the requests will be cancelled , even if any percent threshold is // set , it will be cancelled forcefully. ``` ### Loading image from network into ImageView ```xml imageView.setDefaultImageResId(R.drawable.default); imageView.setErrorImageResId(R.drawable.error); imageView.setImageUrl(imageUrl); ``` ### Getting Bitmap from url with some specified parameters ```java AndroidNetworking.get(imageUrl) .setTag("imageRequestTag") .setPriority(Priority.MEDIUM) .setBitmapMaxHeight(100) .setBitmapMaxWidth(100) .setBitmapConfig(Bitmap.Config.ARGB_8888) .build() .getAsBitmap(new BitmapRequestListener() { @Override public void onResponse(Bitmap bitmap) { // do anything with bitmap } @Override public void onError(ANError error) { // handle error } }); ``` ### Error Code Handling ```java public void onError(ANError error) { if (error.getErrorCode() != 0) { // received error from server // error.getErrorCode() - the error code from server // error.getErrorBody() - the error body from server // error.getErrorDetail() - just an error detail Log.d(TAG, "onError errorCode : " + error.getErrorCode()); Log.d(TAG, "onError errorBody : " + error.getErrorBody()); Log.d(TAG, "onError errorDetail : " + error.getErrorDetail()); // get parsed error object (If ApiError is your class) ApiError apiError = error.getErrorAsObject(ApiError.class); } else { // error.getErrorDetail() : connectionError, parseError, requestCancelledError Log.d(TAG, "onError errorDetail : " + error.getErrorDetail()); } } ``` ### Remove Bitmap from cache or clear cache ```java AndroidNetworking.evictBitmap(key); // remove a bitmap with key from LruCache AndroidNetworking.evictAllBitmap(); // clear LruCache ``` ### Prefetch a request (so that it can return from cache when required at instant) ```java AndroidNetworking.get("https://fierce-cove-29863.herokuapp.com/getAllUsers/{pageNumber}") .addPathParameter("pageNumber", "0") .addQueryParameter("limit", "30") .setTag(this) .setPriority(Priority.LOW) .build() .prefetch(); ``` ### Customizing OkHttpClient for a particular request ```java OkHttpClient okHttpClient = new OkHttpClient().newBuilder() .addInterceptor(new GzipRequestInterceptor()) .build(); AndroidNetworking.get("https://fierce-cove-29863.herokuapp.com/getAllUsers/{pageNumber}") .addPathParameter("pageNumber", "0") .addQueryParameter("limit", "3") .addHeaders("token", "1234") .setTag("test") .setPriority(Priority.LOW) .setOkHttpClient(okHttpClient) // passing a custom okHttpClient .build() .getAsJSONArray(new JSONArrayRequestListener() { @Override public void onResponse(JSONArray response) { // do anything with response } @Override public void onError(ANError error) { // handle error } }); ``` ### Making a conditional request (Building a request) ```java ANRequest.GetRequestBuilder getRequestBuilder = new ANRequest.GetRequestBuilder(ApiEndPoint.BASE_URL + ApiEndPoint.CHECK_FOR_HEADER); if(isHeaderRequired){ getRequestBuilder.addHeaders("token", "1234"); } if(executorRequired){ getRequestBuilder.setExecutor(Executors.newSingleThreadExecutor()); } ANRequest anRequest = getRequestBuilder.build(); anRequest.getAsJSONObject(new JSONObjectRequestListener() { @Override public void onResponse(JSONObject response) { // do anything with response } @Override public void onError(ANError error) { // handle error } }); ``` ### ConnectionClass Listener to get current network quality and bandwidth ```java // Adding Listener AndroidNetworking.setConnectionQualityChangeListener(new ConnectionQualityChangeListener() { @Override public void onChange(ConnectionQuality currentConnectionQuality, int currentBandwidth) { // do something on change in connectionQuality } }); // Removing Listener AndroidNetworking.removeConnectionQualityChangeListener(); // Getting current ConnectionQuality ConnectionQuality connectionQuality = AndroidNetworking.getCurrentConnectionQuality(); if(connectionQuality == ConnectionQuality.EXCELLENT) { // do something } else if (connectionQuality == ConnectionQuality.POOR) { // do something } else if (connectionQuality == ConnectionQuality.UNKNOWN) { // do something } // Getting current bandwidth int currentBandwidth = AndroidNetworking.getCurrentBandwidth(); // Note : if (currentBandwidth == 0) : means UNKNOWN ``` ### Getting Analytics of a request by setting AnalyticsListener on that ```java AndroidNetworking.download(url,dirPath,fileName) .setTag("downloadTest") .setPriority(Priority.MEDIUM) .build() .setAnalyticsListener(new AnalyticsListener() { @Override public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) { Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis); Log.d(TAG, " bytesSent : " + bytesSent); Log.d(TAG, " bytesReceived : " + bytesReceived); Log.d(TAG, " isFromCache : " + isFromCache); } }) .setDownloadProgressListener(new DownloadProgressListener() { @Override public void onProgress(long bytesDownloaded, long totalBytes) { // do anything with progress } }) .startDownload(new DownloadListener() { @Override public void onDownloadComplete() { // do anything after completion } @Override public void onError(ANError error) { // handle error } }); Note : If bytesSent or bytesReceived is -1 , it means it is unknown ``` ### Getting OkHttpResponse in Response ```java AndroidNetworking.get("https://fierce-cove-29863.herokuapp.com/getAnUserDetail/{userId}") .addPathParameter("userId", "1") .setTag(this) .setPriority(Priority.LOW) .setUserAgent("getAnUser") .build() .getAsOkHttpResponseAndParsed(new TypeToken() { }, new OkHttpResponseAndParsedRequestListener() { @Override public void onResponse(Response okHttpResponse, User user) { // do anything with okHttpResponse and user } @Override public void onError(ANError anError) { // handle error } }); ``` ### Making Synchronous Request ```java ANRequest request = AndroidNetworking.get("https://fierce-cove-29863.herokuapp.com/getAllUsers/{pageNumber}") .addPathParameter("pageNumber", "0") .addQueryParameter("limit", "3") .build(); ANResponse> response = request.executeForObjectList(User.class); if (response.isSuccess()) { List users = responseTwo.getResult(); } else { //handle error } ``` ### How caching works ? * First of all the server must send cache-control in header so that is starts working. * Response will be cached on the basis of cache-control max-age,max-stale. * If internet is connected and the age is NOT expired it will return from cache. * If internet is connected and the age is expired and if server returns 304(NOT MODIFIED) it will return from cache. * If internet is NOT connected if you are using getResponseOnlyIfCached() - it will return from cache even it date is expired. * If internet is NOT connected , if you are NOT using getResponseOnlyIfCached() - it will NOT return anything. * If you are using getResponseOnlyFromNetwork() , it will only return response after validation from server. * If cache-control is set, it will work according to the max-age,max-stale returned from server. * If internet is NOT connected only way to get cache Response is by using getResponseOnlyIfCached(). ### Enabling Logging ```java AndroidNetworking.enableLogging(); // simply enable logging AndroidNetworking.enableLogging(LEVEL.HEADERS); // enabling logging with level ``` ### Enabling GZIP From Client to Server ```java // Enabling GZIP for Request (Not needed if your server doesn't support GZIP Compression), anyway responses // from server are automatically unGzipped if required. So enable it only if you need your request to be // Gzipped before sending to server(Make sure your server support GZIP Compression). OkHttpClient okHttpClient = new OkHttpClient().newBuilder() .addInterceptor(new GzipRequestInterceptor()) .build(); AndroidNetworking.initialize(getApplicationContext(),okHttpClient); ``` ### IMPORTANT NOTE * Use IMMEDIATE Priority with caution - use is at appropriate place only when 1 or 2 (at max 2)IMMEDIATE request is required at instant.Otherwise use HIGH Priority. * Known Bug : As present if you are using GZIP Interceptor from client to server, Upload progress is not working perfectly in Multipart. If you are using Proguard with Gradle build system (which is usually the case), you don't have to do anything. The appropriate Proguard rules will be automatically applied. If you still need the rules applied in `proguard-rules.pro`, it is as follows: ``` -dontwarn okio.** ``` ### Fast Android Networking Library supports * Fast Android Networking Library supports all types of HTTP/HTTPS request like GET, POST, DELETE, HEAD, PUT, PATCH * Fast Android Networking Library supports downloading any type of file * Fast Android Networking Library supports uploading any type of file (supports multipart upload) * Fast Android Networking Library supports cancelling a request * Fast Android Networking Library supports setting priority to any request (LOW, MEDIUM, HIGH, IMMEDIATE) * Fast Android Networking Library supports [RxJava](https://amitshekhariitbhu.github.io/Fast-Android-Networking/rxjava2_support.html) As it uses [OkHttp](http://square.github.io/okhttp/) as a networking layer, it supports: * Fast Android Networking Library supports HTTP/2 support allows all requests to the same host to share a socket * Fast Android Networking Library uses connection pooling which reduces request latency (if HTTP/2 isn’t available) * Transparent GZIP shrinks download sizes * Fast Android Networking Library supports response caching which avoids the network completely for repeat requests ### Difference over other Networking Library * In Fast Android Networking Library, OkHttpClient can be customized for every request easily — like timeout customization, etc. for each request. * As Fast Android Networking Library uses [OkHttp](http://square.github.io/okhttp/) and [Okio](https://github.com/square/okio), it is faster. * Single library for all type of networking. * Supports RxJava, RxJava2 -> [Check here](https://amitshekhariitbhu.github.io/Fast-Android-Networking/rxjava2_support.html) * Current bandwidth and connection quality can be obtained to decide logic of code. * Executor can be passed to any request to get the response in another thread. * Complete analytics of any request can be obtained. * All types of customization are possible. * Immediate Request really is immediate now. * Prefetching of any request can be done so that it gives instant data when required from the cache. * Proper request canceling. * Prevents cancellation of a request if it’s completed more than a specific threshold percentage. * A simple interface to make any type of request. * Proper Response Caching — which leads to reduced bandwidth usage. ### TODO * Integration with other library * And of course many many features and bug fixes ### CREDITS * [Square](https://square.github.io/) - As both [OkHttp](http://square.github.io/okhttp/) and [Okio](https://github.com/square/okio) used by Fast Android Networking is developed by [Square](https://square.github.io/). * [Volley](https://android.googlesource.com/platform/frameworks/volley/) - As Fast Android Networking uses ImageLoader that is developed by [Volley](https://android.googlesource.com/platform/frameworks/volley/). * [Prashant Gupta](https://github.com/PrashantGupta17) - For RxJava, RxJava2 Support - [RxJava Support](https://github.com/amitshekhariitbhu/Fast-Android-Networking/wiki/Using-Fast-Android-Networking-Library-With-RxJava) ### Contact - Let's become friend - [Twitter](https://twitter.com/amitiitbhu) - [Github](https://github.com/amitshekhariitbhu) - [Medium](https://medium.com/@amitshekhar) - [Facebook](https://www.facebook.com/amit.shekhar.iitbhu) ### License ``` Copyright (C) 2024 Amit Shekhar Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ``` ### Contributing to Fast Android Networking All pull requests are welcome, make sure to follow the [contribution guidelines](CONTRIBUTING.md) when you submit pull request. ================================================ FILE: android-networking/.gitignore ================================================ /build ================================================ FILE: android-networking/build.gradle ================================================ /* * Copyright (C) 2016 Amit Shekhar * Copyright (C) 2011 Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ apply plugin: 'com.android.library' android { compileSdkVersion rootProject.ext.compileSdkVersion buildToolsVersion rootProject.ext.buildToolsVersion defaultConfig { minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion versionCode 1 versionName "1.0" consumerProguardFiles 'proguard-rules.pro' } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } lintOptions { abortOnError false } } dependencies { api fileTree(dir: 'libs', include: ['*.jar']) testImplementation "junit:junit:$rootProject.ext.jUnitVersion" androidTestImplementation "com.squareup.okhttp3:mockwebserver:$rootProject.ext.mockWebServerVersion" api "com.squareup.okhttp3:okhttp:$rootProject.ext.okHttp3Version" api "com.google.code.gson:gson:$rootProject.ext.gsonVersion" implementation "com.android.support:appcompat-v7:$rootProject.ext.supportAppCompatVersion" } ================================================ FILE: android-networking/proguard-rules.pro ================================================ # Add project specific ProGuard rules here. # By default, the flags in this file are appended to flags specified # in /Users/amitshekhar/Library/Android/sdk/tools/proguard/proguard-android.txt # You can edit the include path and order by changing the proguardFiles # directive in build.gradle. # # For more details, see # http://developer.android.com/guide/developing/tools/proguard.html # Add any project specific keep options here: # If your project uses WebView with JS, uncomment the following # and specify the fully qualified class name to the JavaScript interface # class: #-keepclassmembers class fqcn.of.javascript.interface.for.webview { # public *; #} # For OkHttp -dontwarn okio.** ================================================ FILE: android-networking/src/androidTest/AndroidManifest.xml ================================================ ================================================ FILE: android-networking/src/androidTest/java/com/androidnetworking/GetJSONApiTest.java ================================================ /* * * * Copyright (C) 2016 Amit Shekhar * * Copyright (C) 2011 Android Open Source Project * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * */ package com.androidnetworking; import android.app.Application; import android.test.ApplicationTestCase; import com.androidnetworking.common.ANConstants; import com.androidnetworking.common.ANRequest; import com.androidnetworking.common.ANResponse; import com.androidnetworking.error.ANError; import com.androidnetworking.interfaces.JSONArrayRequestListener; import com.androidnetworking.interfaces.JSONObjectRequestListener; import com.androidnetworking.interfaces.OkHttpResponseAndJSONArrayRequestListener; import com.androidnetworking.interfaces.OkHttpResponseAndJSONObjectRequestListener; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.junit.Rule; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicReference; import okhttp3.Response; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import static java.util.concurrent.TimeUnit.SECONDS; /** * Created by amitshekhar on 03/04/17. */ public class GetJSONApiTest extends ApplicationTestCase { @Rule public final MockWebServer server = new MockWebServer(); public GetJSONApiTest() { super(Application.class); } @Override public void setUp() throws Exception { super.setUp(); createApplication(); } public void testJSONObjectGetRequest() throws InterruptedException { server.enqueue(new MockResponse().setBody("{\"firstName\":\"Amit\", \"lastName\":\"Shekhar\"}")); final AtomicReference firstNameRef = new AtomicReference<>(); final AtomicReference lastNameRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.get(server.url("/").toString()) .build() .getAsJSONObject(new JSONObjectRequestListener() { @Override public void onResponse(JSONObject response) { try { firstNameRef.set(response.getString("firstName")); lastNameRef.set(response.getString("lastName")); latch.countDown(); } catch (JSONException e) { assertTrue(false); } } @Override public void onError(ANError anError) { assertTrue(false); } }); assertTrue(latch.await(2, SECONDS)); assertEquals("Amit", firstNameRef.get()); assertEquals("Shekhar", lastNameRef.get()); } public void testJSONObjectGetRequest404() throws InterruptedException { server.enqueue(new MockResponse().setResponseCode(404).setBody("data")); final AtomicReference errorDetailRef = new AtomicReference<>(); final AtomicReference errorBodyRef = new AtomicReference<>(); final AtomicReference errorCodeRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.get(server.url("/").toString()) .build() .getAsJSONObject(new JSONObjectRequestListener() { @Override public void onResponse(JSONObject response) { assertTrue(false); } @Override public void onError(ANError anError) { errorBodyRef.set(anError.getErrorBody()); errorDetailRef.set(anError.getErrorDetail()); errorCodeRef.set(anError.getErrorCode()); latch.countDown(); } }); assertTrue(latch.await(2, SECONDS)); assertEquals(ANConstants.RESPONSE_FROM_SERVER_ERROR, errorDetailRef.get()); assertEquals("data", errorBodyRef.get()); assertEquals(404, errorCodeRef.get().intValue()); } public void testJSONArrayGetRequest() throws InterruptedException { server.enqueue(new MockResponse().setBody("[{\"firstName\":\"Amit\", \"lastName\":\"Shekhar\"}]")); final AtomicReference firstNameRef = new AtomicReference<>(); final AtomicReference lastNameRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.get(server.url("/").toString()) .build() .getAsJSONArray(new JSONArrayRequestListener() { @Override public void onResponse(JSONArray response) { try { JSONObject jsonObject = response.getJSONObject(0); firstNameRef.set(jsonObject.getString("firstName")); lastNameRef.set(jsonObject.getString("lastName")); latch.countDown(); } catch (JSONException e) { assertTrue(false); } } @Override public void onError(ANError anError) { assertTrue(false); } }); assertTrue(latch.await(2, SECONDS)); assertEquals("Amit", firstNameRef.get()); assertEquals("Shekhar", lastNameRef.get()); } public void testJSONArrayGetRequest404() throws InterruptedException { server.enqueue(new MockResponse().setResponseCode(404).setBody("data")); final AtomicReference errorDetailRef = new AtomicReference<>(); final AtomicReference errorBodyRef = new AtomicReference<>(); final AtomicReference errorCodeRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.get(server.url("/").toString()) .build() .getAsJSONArray(new JSONArrayRequestListener() { @Override public void onResponse(JSONArray response) { assertTrue(false); } @Override public void onError(ANError anError) { errorBodyRef.set(anError.getErrorBody()); errorDetailRef.set(anError.getErrorDetail()); errorCodeRef.set(anError.getErrorCode()); latch.countDown(); } }); assertTrue(latch.await(2, SECONDS)); assertEquals(ANConstants.RESPONSE_FROM_SERVER_ERROR, errorDetailRef.get()); assertEquals("data", errorBodyRef.get()); assertEquals(404, errorCodeRef.get().intValue()); } @SuppressWarnings("unchecked") public void testSynchronousJSONObjectGetRequest() throws InterruptedException, JSONException { server.enqueue(new MockResponse().setBody("{\"firstName\":\"Amit\", \"lastName\":\"Shekhar\"}")); ANRequest request = AndroidNetworking.get(server.url("/").toString()).build(); ANResponse response = request.executeForJSONObject(); assertEquals("Amit", response.getResult().getString("firstName")); assertEquals("Shekhar", response.getResult().getString("lastName")); } @SuppressWarnings("unchecked") public void testSynchronousJSONObjectGetRequest404() throws InterruptedException { server.enqueue(new MockResponse().setResponseCode(404).setBody("data")); ANRequest request = AndroidNetworking.get(server.url("/").toString()).build(); ANResponse response = request.executeForJSONObject(); ANError error = response.getError(); assertEquals("data", error.getErrorBody()); assertEquals(ANConstants.RESPONSE_FROM_SERVER_ERROR, error.getErrorDetail()); assertEquals(404, error.getErrorCode()); } @SuppressWarnings("unchecked") public void testSynchronousJSONArrayGetRequest() throws InterruptedException, JSONException { server.enqueue(new MockResponse().setBody("[{\"firstName\":\"Amit\", \"lastName\":\"Shekhar\"}]")); ANRequest request = AndroidNetworking.get(server.url("/").toString()).build(); ANResponse response = request.executeForJSONArray(); JSONObject jsonObject = response.getResult().getJSONObject(0); assertEquals("Amit", jsonObject.getString("firstName")); assertEquals("Shekhar", jsonObject.getString("lastName")); } @SuppressWarnings("unchecked") public void testSynchronousJSONArrayGetRequest404() throws InterruptedException { server.enqueue(new MockResponse().setResponseCode(404).setBody("data")); ANRequest request = AndroidNetworking.get(server.url("/").toString()).build(); ANResponse response = request.executeForJSONArray(); ANError error = response.getError(); assertEquals("data", error.getErrorBody()); assertEquals(ANConstants.RESPONSE_FROM_SERVER_ERROR, error.getErrorDetail()); assertEquals(404, error.getErrorCode()); } public void testResponseBodyAndJSONObjectGet() throws InterruptedException { server.enqueue(new MockResponse().setBody("{\"firstName\":\"Amit\", \"lastName\":\"Shekhar\"}")); final AtomicReference firstNameRef = new AtomicReference<>(); final AtomicReference lastNameRef = new AtomicReference<>(); final AtomicReference responseBodySuccess = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.get(server.url("/").toString()) .setExecutor(Executors.newSingleThreadExecutor()) .build() .getAsOkHttpResponseAndJSONObject(new OkHttpResponseAndJSONObjectRequestListener() { @Override public void onResponse(Response okHttpResponse, JSONObject response) { try { firstNameRef.set(response.getString("firstName")); lastNameRef.set(response.getString("lastName")); responseBodySuccess.set(okHttpResponse.isSuccessful()); latch.countDown(); } catch (JSONException e) { assertTrue(false); } } @Override public void onError(ANError anError) { assertTrue(false); } }); assertTrue(latch.await(2, SECONDS)); assertTrue(responseBodySuccess.get()); assertEquals("Amit", firstNameRef.get()); assertEquals("Shekhar", lastNameRef.get()); } public void testResponseBodyAndJSONObjectGet404() throws InterruptedException { server.enqueue(new MockResponse().setResponseCode(404).setBody("data")); final AtomicReference errorBodyRef = new AtomicReference<>(); final AtomicReference errorCodeRef = new AtomicReference<>(); final AtomicReference errorDetailRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.get(server.url("/").toString()) .setExecutor(Executors.newSingleThreadExecutor()) .build() .getAsOkHttpResponseAndJSONObject(new OkHttpResponseAndJSONObjectRequestListener() { @Override public void onResponse(Response okHttpResponse, JSONObject response) { assertTrue(false); } @Override public void onError(ANError anError) { errorBodyRef.set(anError.getErrorBody()); errorDetailRef.set(anError.getErrorDetail()); errorCodeRef.set(anError.getErrorCode()); latch.countDown(); } }); assertTrue(latch.await(2, SECONDS)); assertEquals(ANConstants.RESPONSE_FROM_SERVER_ERROR, errorDetailRef.get()); assertEquals("data", errorBodyRef.get()); assertEquals(404, errorCodeRef.get().intValue()); } public void testResponseBodyAndJSONArrayGet() throws InterruptedException { server.enqueue(new MockResponse().setBody("[{\"firstName\":\"Amit\", \"lastName\":\"Shekhar\"}]")); final AtomicReference firstNameRef = new AtomicReference<>(); final AtomicReference lastNameRef = new AtomicReference<>(); final AtomicReference responseBodySuccess = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.get(server.url("/").toString()) .setExecutor(Executors.newSingleThreadExecutor()) .build() .getAsOkHttpResponseAndJSONArray(new OkHttpResponseAndJSONArrayRequestListener() { @Override public void onResponse(Response okHttpResponse, JSONArray response) { try { JSONObject jsonObject = response.getJSONObject(0); firstNameRef.set(jsonObject.getString("firstName")); lastNameRef.set(jsonObject.getString("lastName")); responseBodySuccess.set(okHttpResponse.isSuccessful()); latch.countDown(); } catch (JSONException e) { assertTrue(false); } } @Override public void onError(ANError anError) { assertTrue(false); } }); assertTrue(latch.await(2, SECONDS)); assertTrue(responseBodySuccess.get()); assertEquals("Amit", firstNameRef.get()); assertEquals("Shekhar", lastNameRef.get()); } public void testResponseBodyAndJSONArrayGet404() throws InterruptedException { server.enqueue(new MockResponse().setResponseCode(404).setBody("data")); final AtomicReference errorBodyRef = new AtomicReference<>(); final AtomicReference errorCodeRef = new AtomicReference<>(); final AtomicReference errorDetailRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.get(server.url("/").toString()) .setExecutor(Executors.newSingleThreadExecutor()) .build() .getAsOkHttpResponseAndJSONArray(new OkHttpResponseAndJSONArrayRequestListener() { @Override public void onResponse(Response okHttpResponse, JSONArray response) { assertTrue(false); } @Override public void onError(ANError anError) { errorBodyRef.set(anError.getErrorBody()); errorDetailRef.set(anError.getErrorDetail()); errorCodeRef.set(anError.getErrorCode()); latch.countDown(); } }); assertTrue(latch.await(2, SECONDS)); assertEquals(ANConstants.RESPONSE_FROM_SERVER_ERROR, errorDetailRef.get()); assertEquals("data", errorBodyRef.get()); assertEquals(404, errorCodeRef.get().intValue()); } public void testHeaderGetRequest() throws InterruptedException { server.enqueue(new MockResponse().setBody("{\"firstName\":\"Amit\", \"lastName\":\"Shekhar\"}")); final AtomicReference firstNameRef = new AtomicReference<>(); final AtomicReference lastNameRef = new AtomicReference<>(); final AtomicReference headerRef = new AtomicReference<>(); final AtomicReference responseBodySuccess = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.get(server.url("/").toString()) .addHeaders("headerKey", "headerValue") .setExecutor(Executors.newSingleThreadExecutor()) .build() .getAsOkHttpResponseAndJSONObject(new OkHttpResponseAndJSONObjectRequestListener() { @Override public void onResponse(Response okHttpResponse, JSONObject response) { try { firstNameRef.set(response.getString("firstName")); lastNameRef.set(response.getString("lastName")); responseBodySuccess.set(okHttpResponse.isSuccessful()); headerRef.set(okHttpResponse.request().header("headerKey")); latch.countDown(); } catch (JSONException e) { assertTrue(false); } } @Override public void onError(ANError anError) { assertTrue(false); } }); assertTrue(latch.await(2, SECONDS)); assertTrue(responseBodySuccess.get()); assertEquals("Amit", firstNameRef.get()); assertEquals("Shekhar", lastNameRef.get()); assertEquals("headerValue", headerRef.get()); } } ================================================ FILE: android-networking/src/androidTest/java/com/androidnetworking/GetObjectApiTest.java ================================================ /* * * * Copyright (C) 2016 Amit Shekhar * * Copyright (C) 2011 Android Open Source Project * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * */ package com.androidnetworking; import android.app.Application; import android.test.ApplicationTestCase; import com.androidnetworking.common.ANConstants; import com.androidnetworking.common.ANRequest; import com.androidnetworking.common.ANResponse; import com.androidnetworking.error.ANError; import com.androidnetworking.interfaces.OkHttpResponseAndParsedRequestListener; import com.androidnetworking.interfaces.ParsedRequestListener; import com.androidnetworking.model.User; import org.json.JSONException; import org.junit.Rule; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicReference; import okhttp3.Response; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import static java.util.concurrent.TimeUnit.SECONDS; /** * Created by amitshekhar on 10/04/17. */ public class GetObjectApiTest extends ApplicationTestCase { @Rule public final MockWebServer server = new MockWebServer(); public GetObjectApiTest() { super(Application.class); } @Override public void setUp() throws Exception { super.setUp(); createApplication(); } public void testObjectGetRequest() throws InterruptedException { server.enqueue(new MockResponse().setBody("{\"firstName\":\"Amit\", \"lastName\":\"Shekhar\"}")); final AtomicReference firstNameRef = new AtomicReference<>(); final AtomicReference lastNameRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.get(server.url("/").toString()) .build() .getAsObject(User.class, new ParsedRequestListener() { @Override public void onResponse(User user) { firstNameRef.set(user.firstName); lastNameRef.set(user.lastName); latch.countDown(); } @Override public void onError(ANError anError) { assertTrue(false); } }); assertTrue(latch.await(2, SECONDS)); assertEquals("Amit", firstNameRef.get()); assertEquals("Shekhar", lastNameRef.get()); } public void testObjectGetRequest404() throws InterruptedException { server.enqueue(new MockResponse().setResponseCode(404).setBody("data")); final AtomicReference errorDetailRef = new AtomicReference<>(); final AtomicReference errorBodyRef = new AtomicReference<>(); final AtomicReference errorCodeRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.get(server.url("/").toString()) .build() .getAsObject(User.class, new ParsedRequestListener() { @Override public void onResponse(User user) { assertTrue(false); } @Override public void onError(ANError anError) { errorBodyRef.set(anError.getErrorBody()); errorDetailRef.set(anError.getErrorDetail()); errorCodeRef.set(anError.getErrorCode()); latch.countDown(); } }); assertTrue(latch.await(2, SECONDS)); assertEquals(ANConstants.RESPONSE_FROM_SERVER_ERROR, errorDetailRef.get()); assertEquals("data", errorBodyRef.get()); assertEquals(404, errorCodeRef.get().intValue()); } public void testObjectListGetRequest() throws InterruptedException { server.enqueue(new MockResponse().setBody("[{\"firstName\":\"Amit\", \"lastName\":\"Shekhar\"}]")); final AtomicReference firstNameRef = new AtomicReference<>(); final AtomicReference lastNameRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.get(server.url("/").toString()) .build() .getAsObjectList(User.class, new ParsedRequestListener>() { @Override public void onResponse(List userList) { firstNameRef.set(userList.get(0).firstName); lastNameRef.set(userList.get(0).lastName); latch.countDown(); } @Override public void onError(ANError anError) { assertTrue(false); } }); assertTrue(latch.await(2, SECONDS)); assertEquals("Amit", firstNameRef.get()); assertEquals("Shekhar", lastNameRef.get()); } public void testObjectListGetRequest404() throws InterruptedException { server.enqueue(new MockResponse().setResponseCode(404).setBody("data")); final AtomicReference errorDetailRef = new AtomicReference<>(); final AtomicReference errorBodyRef = new AtomicReference<>(); final AtomicReference errorCodeRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.get(server.url("/").toString()) .build() .getAsObjectList(User.class, new ParsedRequestListener>() { @Override public void onResponse(List userList) { assertTrue(false); } @Override public void onError(ANError anError) { errorBodyRef.set(anError.getErrorBody()); errorDetailRef.set(anError.getErrorDetail()); errorCodeRef.set(anError.getErrorCode()); latch.countDown(); } }); assertTrue(latch.await(2, SECONDS)); assertEquals(ANConstants.RESPONSE_FROM_SERVER_ERROR, errorDetailRef.get()); assertEquals("data", errorBodyRef.get()); assertEquals(404, errorCodeRef.get().intValue()); } @SuppressWarnings("unchecked") public void testSynchronousObjectGetRequest() throws InterruptedException, JSONException { server.enqueue(new MockResponse().setBody("{\"firstName\":\"Amit\", \"lastName\":\"Shekhar\"}")); ANRequest request = AndroidNetworking.get(server.url("/").toString()).build(); ANResponse response = request.executeForObject(User.class); assertEquals("Amit", response.getResult().firstName); assertEquals("Shekhar", response.getResult().lastName); } @SuppressWarnings("unchecked") public void testSynchronousObjectGetRequest404() throws InterruptedException { server.enqueue(new MockResponse().setResponseCode(404).setBody("data")); ANRequest request = AndroidNetworking.get(server.url("/").toString()).build(); ANResponse response = request.executeForObject(User.class); ANError error = response.getError(); assertEquals("data", error.getErrorBody()); assertEquals(ANConstants.RESPONSE_FROM_SERVER_ERROR, error.getErrorDetail()); assertEquals(404, error.getErrorCode()); } @SuppressWarnings("unchecked") public void testSynchronousObjectListGetRequest() throws InterruptedException, JSONException { server.enqueue(new MockResponse().setBody("[{\"firstName\":\"Amit\", \"lastName\":\"Shekhar\"}]")); ANRequest request = AndroidNetworking.get(server.url("/").toString()).build(); ANResponse> response = request.executeForObjectList(User.class); User user = response.getResult().get(0); assertEquals("Amit", user.firstName); assertEquals("Shekhar", user.lastName); } @SuppressWarnings("unchecked") public void testSynchronousObjectListGetRequest404() throws InterruptedException { server.enqueue(new MockResponse().setResponseCode(404).setBody("data")); ANRequest request = AndroidNetworking.get(server.url("/").toString()).build(); ANResponse> response = request.executeForObjectList(User.class); ANError error = response.getError(); assertEquals("data", error.getErrorBody()); assertEquals(ANConstants.RESPONSE_FROM_SERVER_ERROR, error.getErrorDetail()); assertEquals(404, error.getErrorCode()); } public void testResponseBodyAndObjectGet() throws InterruptedException { server.enqueue(new MockResponse().setBody("{\"firstName\":\"Amit\", \"lastName\":\"Shekhar\"}")); final AtomicReference firstNameRef = new AtomicReference<>(); final AtomicReference lastNameRef = new AtomicReference<>(); final AtomicReference responseBodySuccess = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.get(server.url("/").toString()) .setExecutor(Executors.newSingleThreadExecutor()) .build() .getAsOkHttpResponseAndObject(User.class, new OkHttpResponseAndParsedRequestListener() { @Override public void onResponse(Response okHttpResponse, User user) { firstNameRef.set(user.firstName); lastNameRef.set(user.lastName); responseBodySuccess.set(okHttpResponse.isSuccessful()); latch.countDown(); } @Override public void onError(ANError anError) { assertTrue(false); } }); assertTrue(latch.await(2, SECONDS)); assertTrue(responseBodySuccess.get()); assertEquals("Amit", firstNameRef.get()); assertEquals("Shekhar", lastNameRef.get()); } public void testResponseBodyAndObjectGet404() throws InterruptedException { server.enqueue(new MockResponse().setResponseCode(404).setBody("data")); final AtomicReference errorBodyRef = new AtomicReference<>(); final AtomicReference errorCodeRef = new AtomicReference<>(); final AtomicReference errorDetailRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.get(server.url("/").toString()) .setExecutor(Executors.newSingleThreadExecutor()) .build() .getAsOkHttpResponseAndObject(User.class, new OkHttpResponseAndParsedRequestListener() { @Override public void onResponse(Response okHttpResponse, User user) { assertTrue(false); } @Override public void onError(ANError anError) { errorBodyRef.set(anError.getErrorBody()); errorDetailRef.set(anError.getErrorDetail()); errorCodeRef.set(anError.getErrorCode()); latch.countDown(); } }); assertTrue(latch.await(2, SECONDS)); assertEquals(ANConstants.RESPONSE_FROM_SERVER_ERROR, errorDetailRef.get()); assertEquals("data", errorBodyRef.get()); assertEquals(404, errorCodeRef.get().intValue()); } public void testResponseBodyAndObjectListGet() throws InterruptedException { server.enqueue(new MockResponse().setBody("[{\"firstName\":\"Amit\", \"lastName\":\"Shekhar\"}]")); final AtomicReference firstNameRef = new AtomicReference<>(); final AtomicReference lastNameRef = new AtomicReference<>(); final AtomicReference responseBodySuccess = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.get(server.url("/").toString()) .setExecutor(Executors.newSingleThreadExecutor()) .build() .getAsOkHttpResponseAndObjectList(User.class, new OkHttpResponseAndParsedRequestListener>() { @Override public void onResponse(Response okHttpResponse, List userList) { firstNameRef.set(userList.get(0).firstName); lastNameRef.set(userList.get(0).lastName); responseBodySuccess.set(okHttpResponse.isSuccessful()); latch.countDown(); } @Override public void onError(ANError anError) { assertTrue(false); } }); assertTrue(latch.await(2, SECONDS)); assertTrue(responseBodySuccess.get()); assertEquals("Amit", firstNameRef.get()); assertEquals("Shekhar", lastNameRef.get()); } public void testResponseBodyAndObjectListGet404() throws InterruptedException { server.enqueue(new MockResponse().setResponseCode(404).setBody("data")); final AtomicReference errorBodyRef = new AtomicReference<>(); final AtomicReference errorCodeRef = new AtomicReference<>(); final AtomicReference errorDetailRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.get(server.url("/").toString()) .setExecutor(Executors.newSingleThreadExecutor()) .build() .getAsOkHttpResponseAndObjectList(User.class, new OkHttpResponseAndParsedRequestListener>() { @Override public void onResponse(Response okHttpResponse, List userList) { assertTrue(false); } @Override public void onError(ANError anError) { errorBodyRef.set(anError.getErrorBody()); errorDetailRef.set(anError.getErrorDetail()); errorCodeRef.set(anError.getErrorCode()); latch.countDown(); } }); assertTrue(latch.await(2, SECONDS)); assertEquals(ANConstants.RESPONSE_FROM_SERVER_ERROR, errorDetailRef.get()); assertEquals("data", errorBodyRef.get()); assertEquals(404, errorCodeRef.get().intValue()); } public void testHeaderGetRequest() throws InterruptedException { server.enqueue(new MockResponse().setBody("{\"firstName\":\"Amit\", \"lastName\":\"Shekhar\"}")); final AtomicReference firstNameRef = new AtomicReference<>(); final AtomicReference lastNameRef = new AtomicReference<>(); final AtomicReference headerRef = new AtomicReference<>(); final AtomicReference responseBodySuccess = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.get(server.url("/").toString()) .addHeaders("headerKey", "headerValue") .setExecutor(Executors.newSingleThreadExecutor()) .build() .getAsOkHttpResponseAndObject(User.class, new OkHttpResponseAndParsedRequestListener() { @Override public void onResponse(Response okHttpResponse, User user) { firstNameRef.set(user.firstName); lastNameRef.set(user.lastName); responseBodySuccess.set(okHttpResponse.isSuccessful()); headerRef.set(okHttpResponse.request().header("headerKey")); latch.countDown(); } @Override public void onError(ANError anError) { assertTrue(false); } }); assertTrue(latch.await(2, SECONDS)); assertTrue(responseBodySuccess.get()); assertEquals("Amit", firstNameRef.get()); assertEquals("Shekhar", lastNameRef.get()); assertEquals("headerValue", headerRef.get()); } } ================================================ FILE: android-networking/src/androidTest/java/com/androidnetworking/GetStringApiTest.java ================================================ /* * Copyright (C) 2016 Amit Shekhar * Copyright (C) 2011 Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.androidnetworking; import android.app.Application; import android.test.ApplicationTestCase; import com.androidnetworking.common.ANConstants; import com.androidnetworking.common.ANRequest; import com.androidnetworking.common.ANResponse; import com.androidnetworking.error.ANError; import com.androidnetworking.interfaces.OkHttpResponseAndStringRequestListener; import com.androidnetworking.interfaces.OkHttpResponseListener; import com.androidnetworking.interfaces.StringRequestListener; import org.junit.Rule; import java.io.IOException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicReference; import okhttp3.Response; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import static java.util.concurrent.TimeUnit.SECONDS; public class GetStringApiTest extends ApplicationTestCase { @Rule public final MockWebServer server = new MockWebServer(); public GetStringApiTest() { super(Application.class); } @Override public void setUp() throws Exception { super.setUp(); createApplication(); } public void testStringGetRequest() throws InterruptedException { server.enqueue(new MockResponse().setBody("data")); final AtomicReference responseRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.get(server.url("/").toString()) .build() .getAsString(new StringRequestListener() { @Override public void onResponse(String response) { responseRef.set(response); latch.countDown(); } @Override public void onError(ANError anError) { assertTrue(false); } }); assertTrue(latch.await(2, SECONDS)); assertEquals("data", responseRef.get()); } public void testStringGetRequest404() throws InterruptedException { server.enqueue(new MockResponse().setResponseCode(404).setBody("data")); final AtomicReference errorDetailRef = new AtomicReference<>(); final AtomicReference errorBodyRef = new AtomicReference<>(); final AtomicReference errorCodeRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.get(server.url("/").toString()) .build() .getAsString(new StringRequestListener() { @Override public void onResponse(String response) { assertTrue(false); } @Override public void onError(ANError anError) { errorBodyRef.set(anError.getErrorBody()); errorDetailRef.set(anError.getErrorDetail()); errorCodeRef.set(anError.getErrorCode()); latch.countDown(); } }); assertTrue(latch.await(2, SECONDS)); assertEquals(ANConstants.RESPONSE_FROM_SERVER_ERROR, errorDetailRef.get()); assertEquals("data", errorBodyRef.get()); assertEquals(404, errorCodeRef.get().intValue()); } @SuppressWarnings("unchecked") public void testSynchronousStringGetRequest() throws InterruptedException { server.enqueue(new MockResponse().setBody("data")); ANRequest request = AndroidNetworking.get(server.url("/").toString()).build(); ANResponse response = request.executeForString(); assertEquals("data", response.getResult()); } @SuppressWarnings("unchecked") public void testSynchronousStringGetRequest404() throws InterruptedException { server.enqueue(new MockResponse().setResponseCode(404).setBody("data")); ANRequest request = AndroidNetworking.get(server.url("/").toString()).build(); ANResponse response = request.executeForString(); ANError error = response.getError(); assertEquals("data", error.getErrorBody()); assertEquals(ANConstants.RESPONSE_FROM_SERVER_ERROR, error.getErrorDetail()); assertEquals(404, error.getErrorCode()); } public void testResponseBodyGet() throws InterruptedException { server.enqueue(new MockResponse().setBody("data")); final AtomicReference responseRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.get(server.url("/").toString()) .setExecutor(Executors.newSingleThreadExecutor()) .build() .getAsOkHttpResponse(new OkHttpResponseListener() { @Override public void onResponse(Response response) { try { responseRef.set(response.body().string()); latch.countDown(); } catch (IOException e) { assertTrue(false); } } @Override public void onError(ANError anError) { assertTrue(false); } }); assertTrue(latch.await(2, SECONDS)); assertEquals("data", responseRef.get()); } public void testResponseBodyGet404() throws InterruptedException { server.enqueue(new MockResponse().setResponseCode(404).setBody("data")); final AtomicReference errorBodyRef = new AtomicReference<>(); final AtomicReference errorCodeRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.get(server.url("/").toString()) .setExecutor(Executors.newSingleThreadExecutor()) .build() .getAsOkHttpResponse(new OkHttpResponseListener() { @Override public void onResponse(Response response) { try { errorBodyRef.set(response.body().string()); errorCodeRef.set(response.code()); latch.countDown(); } catch (IOException e) { assertTrue(false); } } @Override public void onError(ANError anError) { assertTrue(false); } }); assertTrue(latch.await(2, SECONDS)); assertEquals("data", errorBodyRef.get()); assertEquals(404, errorCodeRef.get().intValue()); } @SuppressWarnings("unchecked") public void testSyncResponseBodyGet() throws InterruptedException, IOException { server.enqueue(new MockResponse().setBody("data")); ANRequest request = AndroidNetworking.get(server.url("/").toString()).build(); ANResponse response = request.executeForOkHttpResponse(); assertEquals("data", response.getResult().body().string()); } @SuppressWarnings("unchecked") public void testSyncResponseBodyGet404() throws InterruptedException, IOException { server.enqueue(new MockResponse().setResponseCode(404).setBody("data")); ANRequest request = AndroidNetworking.get(server.url("/").toString()).build(); ANResponse response = request.executeForOkHttpResponse(); assertEquals("data", response.getResult().body().string()); assertEquals(404, response.getResult().code()); } public void testResponseBodyAndStringGet() throws InterruptedException { server.enqueue(new MockResponse().setBody("data")); final AtomicReference responseBodySuccess = new AtomicReference<>(); final AtomicReference responseStringRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.get(server.url("/").toString()) .setExecutor(Executors.newSingleThreadExecutor()) .build() .getAsOkHttpResponseAndString(new OkHttpResponseAndStringRequestListener() { @Override public void onResponse(Response okHttpResponse, String response) { responseBodySuccess.set(okHttpResponse.isSuccessful()); responseStringRef.set(response); latch.countDown(); } @Override public void onError(ANError anError) { assertTrue(false); } }); assertTrue(latch.await(2, SECONDS)); assertTrue(responseBodySuccess.get()); assertEquals("data", responseStringRef.get()); } public void testResponseBodyAndStringGet404() throws InterruptedException { server.enqueue(new MockResponse().setResponseCode(404).setBody("data")); final AtomicReference errorBodyRef = new AtomicReference<>(); final AtomicReference errorCodeRef = new AtomicReference<>(); final AtomicReference errorDetailRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.get(server.url("/").toString()) .setExecutor(Executors.newSingleThreadExecutor()) .build() .getAsOkHttpResponseAndString(new OkHttpResponseAndStringRequestListener() { @Override public void onResponse(Response okHttpResponse, String response) { assertTrue(false); } @Override public void onError(ANError anError) { errorBodyRef.set(anError.getErrorBody()); errorDetailRef.set(anError.getErrorDetail()); errorCodeRef.set(anError.getErrorCode()); latch.countDown(); } }); assertTrue(latch.await(2, SECONDS)); assertEquals(ANConstants.RESPONSE_FROM_SERVER_ERROR, errorDetailRef.get()); assertEquals("data", errorBodyRef.get()); assertEquals(404, errorCodeRef.get().intValue()); } public void testHeaderGetRequest() throws InterruptedException { server.enqueue(new MockResponse().setBody("data")); final AtomicReference responseRef = new AtomicReference<>(); final AtomicReference headerRef = new AtomicReference<>(); final AtomicReference responseBodySuccess = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.get(server.url("/").toString()) .addHeaders("headerKey", "headerValue") .setExecutor(Executors.newSingleThreadExecutor()) .build() .getAsOkHttpResponseAndString(new OkHttpResponseAndStringRequestListener() { @Override public void onResponse(Response okHttpResponse, String response) { responseRef.set(response); responseBodySuccess.set(okHttpResponse.isSuccessful()); headerRef.set(okHttpResponse.request().header("headerKey")); latch.countDown(); } @Override public void onError(ANError anError) { assertTrue(false); } }); assertTrue(latch.await(2, SECONDS)); assertTrue(responseBodySuccess.get()); assertEquals("data", responseRef.get()); assertEquals("headerValue", headerRef.get()); } } ================================================ FILE: android-networking/src/androidTest/java/com/androidnetworking/MultipartJSONApiTest.java ================================================ /* * * * Copyright (C) 2016 Amit Shekhar * * Copyright (C) 2011 Android Open Source Project * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * */ package com.androidnetworking; import android.app.Application; import android.test.ApplicationTestCase; import com.androidnetworking.common.ANConstants; import com.androidnetworking.common.ANRequest; import com.androidnetworking.common.ANResponse; import com.androidnetworking.error.ANError; import com.androidnetworking.interfaces.JSONArrayRequestListener; import com.androidnetworking.interfaces.JSONObjectRequestListener; import com.androidnetworking.interfaces.OkHttpResponseAndJSONArrayRequestListener; import com.androidnetworking.interfaces.OkHttpResponseAndJSONObjectRequestListener; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.junit.Rule; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicReference; import okhttp3.Response; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import static java.util.concurrent.TimeUnit.SECONDS; /** * Created by amitshekhar on 09/04/17. */ public class MultipartJSONApiTest extends ApplicationTestCase { @Rule public final MockWebServer server = new MockWebServer(); public MultipartJSONApiTest() { super(Application.class); } @Override public void setUp() throws Exception { super.setUp(); createApplication(); } public void testJSONObjectMultipartRequest() throws InterruptedException { server.enqueue(new MockResponse().setBody("{\"firstName\":\"Amit\", \"lastName\":\"Shekhar\"}")); final AtomicReference firstNameRef = new AtomicReference<>(); final AtomicReference lastNameRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.upload(server.url("/").toString()) .addMultipartParameter("key", "value") .build() .getAsJSONObject(new JSONObjectRequestListener() { @Override public void onResponse(JSONObject response) { try { firstNameRef.set(response.getString("firstName")); lastNameRef.set(response.getString("lastName")); latch.countDown(); } catch (JSONException e) { assertTrue(false); } } @Override public void onError(ANError anError) { assertTrue(false); } }); assertTrue(latch.await(2, SECONDS)); assertEquals("Amit", firstNameRef.get()); assertEquals("Shekhar", lastNameRef.get()); } public void testJSONObjectMultipartRequest404() throws InterruptedException { server.enqueue(new MockResponse().setResponseCode(404).setBody("data")); final AtomicReference errorDetailRef = new AtomicReference<>(); final AtomicReference errorBodyRef = new AtomicReference<>(); final AtomicReference errorCodeRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.upload(server.url("/").toString()) .addMultipartParameter("key", "value") .build() .getAsJSONObject(new JSONObjectRequestListener() { @Override public void onResponse(JSONObject response) { assertTrue(false); } @Override public void onError(ANError anError) { errorBodyRef.set(anError.getErrorBody()); errorDetailRef.set(anError.getErrorDetail()); errorCodeRef.set(anError.getErrorCode()); latch.countDown(); } }); assertTrue(latch.await(2, SECONDS)); assertEquals(ANConstants.RESPONSE_FROM_SERVER_ERROR, errorDetailRef.get()); assertEquals("data", errorBodyRef.get()); assertEquals(404, errorCodeRef.get().intValue()); } public void testJSONArrayMultipartRequest() throws InterruptedException { server.enqueue(new MockResponse().setBody("[{\"firstName\":\"Amit\", \"lastName\":\"Shekhar\"}]")); final AtomicReference firstNameRef = new AtomicReference<>(); final AtomicReference lastNameRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.upload(server.url("/").toString()) .addMultipartParameter("key", "value") .build() .getAsJSONArray(new JSONArrayRequestListener() { @Override public void onResponse(JSONArray response) { try { JSONObject jsonObject = response.getJSONObject(0); firstNameRef.set(jsonObject.getString("firstName")); lastNameRef.set(jsonObject.getString("lastName")); latch.countDown(); } catch (JSONException e) { assertTrue(false); } } @Override public void onError(ANError anError) { assertTrue(false); } }); assertTrue(latch.await(2, SECONDS)); assertEquals("Amit", firstNameRef.get()); assertEquals("Shekhar", lastNameRef.get()); } public void testJSONArrayMultipartRequest404() throws InterruptedException { server.enqueue(new MockResponse().setResponseCode(404).setBody("data")); final AtomicReference errorDetailRef = new AtomicReference<>(); final AtomicReference errorBodyRef = new AtomicReference<>(); final AtomicReference errorCodeRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.upload(server.url("/").toString()) .addMultipartParameter("key", "value") .build() .getAsJSONArray(new JSONArrayRequestListener() { @Override public void onResponse(JSONArray response) { assertTrue(false); } @Override public void onError(ANError anError) { errorBodyRef.set(anError.getErrorBody()); errorDetailRef.set(anError.getErrorDetail()); errorCodeRef.set(anError.getErrorCode()); latch.countDown(); } }); assertTrue(latch.await(2, SECONDS)); assertEquals(ANConstants.RESPONSE_FROM_SERVER_ERROR, errorDetailRef.get()); assertEquals("data", errorBodyRef.get()); assertEquals(404, errorCodeRef.get().intValue()); } @SuppressWarnings("unchecked") public void testSynchronousJSONObjectMultipartRequest() throws InterruptedException, JSONException { server.enqueue(new MockResponse().setBody("{\"firstName\":\"Amit\", \"lastName\":\"Shekhar\"}")); ANRequest request = AndroidNetworking.upload(server.url("/").toString()) .addMultipartParameter("key", "value") .build(); ANResponse response = request.executeForJSONObject(); assertEquals("Amit", response.getResult().getString("firstName")); assertEquals("Shekhar", response.getResult().getString("lastName")); } @SuppressWarnings("unchecked") public void testSynchronousJSONObjectMultipartRequest404() throws InterruptedException { server.enqueue(new MockResponse().setResponseCode(404).setBody("data")); ANRequest request = AndroidNetworking.upload(server.url("/").toString()) .addMultipartParameter("key", "value") .build(); ANResponse response = request.executeForJSONObject(); ANError error = response.getError(); assertEquals("data", error.getErrorBody()); assertEquals(ANConstants.RESPONSE_FROM_SERVER_ERROR, error.getErrorDetail()); assertEquals(404, error.getErrorCode()); } @SuppressWarnings("unchecked") public void testSynchronousJSONArrayMultipartRequest() throws InterruptedException, JSONException { server.enqueue(new MockResponse().setBody("[{\"firstName\":\"Amit\", \"lastName\":\"Shekhar\"}]")); ANRequest request = AndroidNetworking.upload(server.url("/").toString()) .addMultipartParameter("key", "value") .build(); ANResponse response = request.executeForJSONArray(); JSONObject jsonObject = response.getResult().getJSONObject(0); assertEquals("Amit", jsonObject.getString("firstName")); assertEquals("Shekhar", jsonObject.getString("lastName")); } @SuppressWarnings("unchecked") public void testSynchronousJSONArrayMultipartRequest404() throws InterruptedException { server.enqueue(new MockResponse().setResponseCode(404).setBody("data")); ANRequest request = AndroidNetworking.upload(server.url("/").toString()) .addMultipartParameter("key", "value") .build(); ANResponse response = request.executeForJSONArray(); ANError error = response.getError(); assertEquals("data", error.getErrorBody()); assertEquals(ANConstants.RESPONSE_FROM_SERVER_ERROR, error.getErrorDetail()); assertEquals(404, error.getErrorCode()); } public void testResponseBodyAndJSONObjectMultipart() throws InterruptedException { server.enqueue(new MockResponse().setBody("{\"firstName\":\"Amit\", \"lastName\":\"Shekhar\"}")); final AtomicReference firstNameRef = new AtomicReference<>(); final AtomicReference lastNameRef = new AtomicReference<>(); final AtomicReference responseBodySuccess = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.upload(server.url("/").toString()) .addMultipartParameter("key", "value") .setExecutor(Executors.newSingleThreadExecutor()) .build() .getAsOkHttpResponseAndJSONObject(new OkHttpResponseAndJSONObjectRequestListener() { @Override public void onResponse(Response okHttpResponse, JSONObject response) { try { firstNameRef.set(response.getString("firstName")); lastNameRef.set(response.getString("lastName")); responseBodySuccess.set(okHttpResponse.isSuccessful()); latch.countDown(); } catch (JSONException e) { assertTrue(false); } } @Override public void onError(ANError anError) { assertTrue(false); } }); assertTrue(latch.await(2, SECONDS)); assertTrue(responseBodySuccess.get()); assertEquals("Amit", firstNameRef.get()); assertEquals("Shekhar", lastNameRef.get()); } public void testResponseBodyAndJSONObjectMultipart404() throws InterruptedException { server.enqueue(new MockResponse().setResponseCode(404).setBody("data")); final AtomicReference errorBodyRef = new AtomicReference<>(); final AtomicReference errorCodeRef = new AtomicReference<>(); final AtomicReference errorDetailRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.upload(server.url("/").toString()) .addMultipartParameter("key", "value") .setExecutor(Executors.newSingleThreadExecutor()) .build() .getAsOkHttpResponseAndJSONObject(new OkHttpResponseAndJSONObjectRequestListener() { @Override public void onResponse(Response okHttpResponse, JSONObject response) { assertTrue(false); } @Override public void onError(ANError anError) { errorBodyRef.set(anError.getErrorBody()); errorDetailRef.set(anError.getErrorDetail()); errorCodeRef.set(anError.getErrorCode()); latch.countDown(); } }); assertTrue(latch.await(2, SECONDS)); assertEquals(ANConstants.RESPONSE_FROM_SERVER_ERROR, errorDetailRef.get()); assertEquals("data", errorBodyRef.get()); assertEquals(404, errorCodeRef.get().intValue()); } public void testResponseBodyAndJSONArrayMultipart() throws InterruptedException { server.enqueue(new MockResponse().setBody("[{\"firstName\":\"Amit\", \"lastName\":\"Shekhar\"}]")); final AtomicReference firstNameRef = new AtomicReference<>(); final AtomicReference lastNameRef = new AtomicReference<>(); final AtomicReference responseBodySuccess = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.upload(server.url("/").toString()) .addMultipartParameter("key", "value") .setExecutor(Executors.newSingleThreadExecutor()) .build() .getAsOkHttpResponseAndJSONArray(new OkHttpResponseAndJSONArrayRequestListener() { @Override public void onResponse(Response okHttpResponse, JSONArray response) { try { JSONObject jsonObject = response.getJSONObject(0); firstNameRef.set(jsonObject.getString("firstName")); lastNameRef.set(jsonObject.getString("lastName")); responseBodySuccess.set(okHttpResponse.isSuccessful()); latch.countDown(); } catch (JSONException e) { assertTrue(false); } } @Override public void onError(ANError anError) { assertTrue(false); } }); assertTrue(latch.await(2, SECONDS)); assertTrue(responseBodySuccess.get()); assertEquals("Amit", firstNameRef.get()); assertEquals("Shekhar", lastNameRef.get()); } public void testResponseBodyAndJSONArrayMultipart404() throws InterruptedException { server.enqueue(new MockResponse().setResponseCode(404).setBody("data")); final AtomicReference errorBodyRef = new AtomicReference<>(); final AtomicReference errorCodeRef = new AtomicReference<>(); final AtomicReference errorDetailRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.upload(server.url("/").toString()) .addMultipartParameter("key", "value") .setExecutor(Executors.newSingleThreadExecutor()) .build() .getAsOkHttpResponseAndJSONArray(new OkHttpResponseAndJSONArrayRequestListener() { @Override public void onResponse(Response okHttpResponse, JSONArray response) { assertTrue(false); } @Override public void onError(ANError anError) { errorBodyRef.set(anError.getErrorBody()); errorDetailRef.set(anError.getErrorDetail()); errorCodeRef.set(anError.getErrorCode()); latch.countDown(); } }); assertTrue(latch.await(2, SECONDS)); assertEquals(ANConstants.RESPONSE_FROM_SERVER_ERROR, errorDetailRef.get()); assertEquals("data", errorBodyRef.get()); assertEquals(404, errorCodeRef.get().intValue()); } public void testHeaderMultipartRequest() throws InterruptedException { server.enqueue(new MockResponse().setBody("{\"firstName\":\"Amit\", \"lastName\":\"Shekhar\"}")); final AtomicReference firstNameRef = new AtomicReference<>(); final AtomicReference lastNameRef = new AtomicReference<>(); final AtomicReference headerRef = new AtomicReference<>(); final AtomicReference responseBodySuccess = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.upload(server.url("/").toString()) .addHeaders("headerKey", "headerValue") .addMultipartParameter("key", "value") .setExecutor(Executors.newSingleThreadExecutor()) .build() .getAsOkHttpResponseAndJSONObject(new OkHttpResponseAndJSONObjectRequestListener() { @Override public void onResponse(Response okHttpResponse, JSONObject response) { try { firstNameRef.set(response.getString("firstName")); lastNameRef.set(response.getString("lastName")); responseBodySuccess.set(okHttpResponse.isSuccessful()); headerRef.set(okHttpResponse.request().header("headerKey")); latch.countDown(); } catch (JSONException e) { assertTrue(false); } } @Override public void onError(ANError anError) { assertTrue(false); } }); assertTrue(latch.await(2, SECONDS)); assertTrue(responseBodySuccess.get()); assertEquals("Amit", firstNameRef.get()); assertEquals("Shekhar", lastNameRef.get()); assertEquals("headerValue", headerRef.get()); } } ================================================ FILE: android-networking/src/androidTest/java/com/androidnetworking/MultipartObjectApiTest.java ================================================ /* * * * Copyright (C) 2016 Amit Shekhar * * Copyright (C) 2011 Android Open Source Project * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * */ package com.androidnetworking; import android.app.Application; import android.test.ApplicationTestCase; import com.androidnetworking.common.ANConstants; import com.androidnetworking.common.ANRequest; import com.androidnetworking.common.ANResponse; import com.androidnetworking.error.ANError; import com.androidnetworking.interfaces.OkHttpResponseAndParsedRequestListener; import com.androidnetworking.interfaces.ParsedRequestListener; import com.androidnetworking.model.User; import org.json.JSONException; import org.junit.Rule; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicReference; import okhttp3.Response; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import static java.util.concurrent.TimeUnit.SECONDS; /** * Created by amitshekhar on 12/04/17. */ public class MultipartObjectApiTest extends ApplicationTestCase { @Rule public final MockWebServer server = new MockWebServer(); public MultipartObjectApiTest() { super(Application.class); } @Override public void setUp() throws Exception { super.setUp(); createApplication(); } public void testObjectMultipartRequest() throws InterruptedException { server.enqueue(new MockResponse().setBody("{\"firstName\":\"Amit\", \"lastName\":\"Shekhar\"}")); final AtomicReference firstNameRef = new AtomicReference<>(); final AtomicReference lastNameRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.upload(server.url("/").toString()) .addMultipartParameter("key", "value") .build() .getAsObject(User.class, new ParsedRequestListener() { @Override public void onResponse(User user) { firstNameRef.set(user.firstName); lastNameRef.set(user.lastName); latch.countDown(); } @Override public void onError(ANError anError) { assertTrue(false); } }); assertTrue(latch.await(2, SECONDS)); assertEquals("Amit", firstNameRef.get()); assertEquals("Shekhar", lastNameRef.get()); } public void testObjectMultipartRequest404() throws InterruptedException { server.enqueue(new MockResponse().setResponseCode(404).setBody("data")); final AtomicReference errorDetailRef = new AtomicReference<>(); final AtomicReference errorBodyRef = new AtomicReference<>(); final AtomicReference errorCodeRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.upload(server.url("/").toString()) .addMultipartParameter("key", "value") .build() .getAsObject(User.class, new ParsedRequestListener() { @Override public void onResponse(User user) { assertTrue(false); } @Override public void onError(ANError anError) { errorBodyRef.set(anError.getErrorBody()); errorDetailRef.set(anError.getErrorDetail()); errorCodeRef.set(anError.getErrorCode()); latch.countDown(); } }); assertTrue(latch.await(2, SECONDS)); assertEquals(ANConstants.RESPONSE_FROM_SERVER_ERROR, errorDetailRef.get()); assertEquals("data", errorBodyRef.get()); assertEquals(404, errorCodeRef.get().intValue()); } public void testObjectListMultipartRequest() throws InterruptedException { server.enqueue(new MockResponse().setBody("[{\"firstName\":\"Amit\", \"lastName\":\"Shekhar\"}]")); final AtomicReference firstNameRef = new AtomicReference<>(); final AtomicReference lastNameRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.upload(server.url("/").toString()) .addMultipartParameter("key", "value") .build() .getAsObjectList(User.class, new ParsedRequestListener>() { @Override public void onResponse(List userList) { firstNameRef.set(userList.get(0).firstName); lastNameRef.set(userList.get(0).lastName); latch.countDown(); } @Override public void onError(ANError anError) { assertTrue(false); } }); assertTrue(latch.await(2, SECONDS)); assertEquals("Amit", firstNameRef.get()); assertEquals("Shekhar", lastNameRef.get()); } public void testObjectListMultipartRequest404() throws InterruptedException { server.enqueue(new MockResponse().setResponseCode(404).setBody("data")); final AtomicReference errorDetailRef = new AtomicReference<>(); final AtomicReference errorBodyRef = new AtomicReference<>(); final AtomicReference errorCodeRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.upload(server.url("/").toString()) .addMultipartParameter("key", "value") .build() .getAsObjectList(User.class, new ParsedRequestListener>() { @Override public void onResponse(List userList) { assertTrue(false); } @Override public void onError(ANError anError) { errorBodyRef.set(anError.getErrorBody()); errorDetailRef.set(anError.getErrorDetail()); errorCodeRef.set(anError.getErrorCode()); latch.countDown(); } }); assertTrue(latch.await(2, SECONDS)); assertEquals(ANConstants.RESPONSE_FROM_SERVER_ERROR, errorDetailRef.get()); assertEquals("data", errorBodyRef.get()); assertEquals(404, errorCodeRef.get().intValue()); } @SuppressWarnings("unchecked") public void testSynchronousObjectMultipartRequest() throws InterruptedException, JSONException { server.enqueue(new MockResponse().setBody("{\"firstName\":\"Amit\", \"lastName\":\"Shekhar\"}")); ANRequest request = AndroidNetworking.upload(server.url("/").toString()) .addMultipartParameter("key", "value") .build(); ANResponse response = request.executeForObject(User.class); assertEquals("Amit", response.getResult().firstName); assertEquals("Shekhar", response.getResult().lastName); } @SuppressWarnings("unchecked") public void testSynchronousObjectMultipartRequest404() throws InterruptedException { server.enqueue(new MockResponse().setResponseCode(404).setBody("data")); ANRequest request = AndroidNetworking.upload(server.url("/").toString()) .addMultipartParameter("key", "value") .build(); ANResponse response = request.executeForObject(User.class); ANError error = response.getError(); assertEquals("data", error.getErrorBody()); assertEquals(ANConstants.RESPONSE_FROM_SERVER_ERROR, error.getErrorDetail()); assertEquals(404, error.getErrorCode()); } @SuppressWarnings("unchecked") public void testSynchronousObjectListMultipartRequest() throws InterruptedException, JSONException { server.enqueue(new MockResponse().setBody("[{\"firstName\":\"Amit\", \"lastName\":\"Shekhar\"}]")); ANRequest request = AndroidNetworking.upload(server.url("/").toString()) .addMultipartParameter("key", "value") .build(); ANResponse> response = request.executeForObjectList(User.class); User user = response.getResult().get(0); assertEquals("Amit", user.firstName); assertEquals("Shekhar", user.lastName); } @SuppressWarnings("unchecked") public void testSynchronousObjectListMultipartRequest404() throws InterruptedException { server.enqueue(new MockResponse().setResponseCode(404).setBody("data")); ANRequest request = AndroidNetworking.upload(server.url("/").toString()) .addMultipartParameter("key", "value") .build(); ANResponse> response = request.executeForObjectList(User.class); ANError error = response.getError(); assertEquals("data", error.getErrorBody()); assertEquals(ANConstants.RESPONSE_FROM_SERVER_ERROR, error.getErrorDetail()); assertEquals(404, error.getErrorCode()); } public void testResponseBodyAndObjectMultipart() throws InterruptedException { server.enqueue(new MockResponse().setBody("{\"firstName\":\"Amit\", \"lastName\":\"Shekhar\"}")); final AtomicReference firstNameRef = new AtomicReference<>(); final AtomicReference lastNameRef = new AtomicReference<>(); final AtomicReference responseBodySuccess = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.upload(server.url("/").toString()) .addMultipartParameter("key", "value") .setExecutor(Executors.newSingleThreadExecutor()) .build() .getAsOkHttpResponseAndObject(User.class, new OkHttpResponseAndParsedRequestListener() { @Override public void onResponse(Response okHttpResponse, User user) { firstNameRef.set(user.firstName); lastNameRef.set(user.lastName); responseBodySuccess.set(okHttpResponse.isSuccessful()); latch.countDown(); } @Override public void onError(ANError anError) { assertTrue(false); } }); assertTrue(latch.await(2, SECONDS)); assertTrue(responseBodySuccess.get()); assertEquals("Amit", firstNameRef.get()); assertEquals("Shekhar", lastNameRef.get()); } public void testResponseBodyAndObjectMultipart404() throws InterruptedException { server.enqueue(new MockResponse().setResponseCode(404).setBody("data")); final AtomicReference errorBodyRef = new AtomicReference<>(); final AtomicReference errorCodeRef = new AtomicReference<>(); final AtomicReference errorDetailRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.upload(server.url("/").toString()) .addMultipartParameter("key", "value") .setExecutor(Executors.newSingleThreadExecutor()) .build() .getAsOkHttpResponseAndObject(User.class, new OkHttpResponseAndParsedRequestListener() { @Override public void onResponse(Response okHttpResponse, User user) { assertTrue(false); } @Override public void onError(ANError anError) { errorBodyRef.set(anError.getErrorBody()); errorDetailRef.set(anError.getErrorDetail()); errorCodeRef.set(anError.getErrorCode()); latch.countDown(); } }); assertTrue(latch.await(2, SECONDS)); assertEquals(ANConstants.RESPONSE_FROM_SERVER_ERROR, errorDetailRef.get()); assertEquals("data", errorBodyRef.get()); assertEquals(404, errorCodeRef.get().intValue()); } public void testResponseBodyAndObjectListMultipart() throws InterruptedException { server.enqueue(new MockResponse().setBody("[{\"firstName\":\"Amit\", \"lastName\":\"Shekhar\"}]")); final AtomicReference firstNameRef = new AtomicReference<>(); final AtomicReference lastNameRef = new AtomicReference<>(); final AtomicReference responseBodySuccess = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.upload(server.url("/").toString()) .addMultipartParameter("key", "value") .setExecutor(Executors.newSingleThreadExecutor()) .build() .getAsOkHttpResponseAndObjectList(User.class, new OkHttpResponseAndParsedRequestListener>() { @Override public void onResponse(Response okHttpResponse, List userList) { firstNameRef.set(userList.get(0).firstName); lastNameRef.set(userList.get(0).lastName); responseBodySuccess.set(okHttpResponse.isSuccessful()); latch.countDown(); } @Override public void onError(ANError anError) { assertTrue(false); } }); assertTrue(latch.await(2, SECONDS)); assertTrue(responseBodySuccess.get()); assertEquals("Amit", firstNameRef.get()); assertEquals("Shekhar", lastNameRef.get()); } public void testResponseBodyAndObjectListMultipart404() throws InterruptedException { server.enqueue(new MockResponse().setResponseCode(404).setBody("data")); final AtomicReference errorBodyRef = new AtomicReference<>(); final AtomicReference errorCodeRef = new AtomicReference<>(); final AtomicReference errorDetailRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.upload(server.url("/").toString()) .addMultipartParameter("key", "value") .setExecutor(Executors.newSingleThreadExecutor()) .build() .getAsOkHttpResponseAndObjectList(User.class, new OkHttpResponseAndParsedRequestListener>() { @Override public void onResponse(Response okHttpResponse, List userList) { assertTrue(false); } @Override public void onError(ANError anError) { errorBodyRef.set(anError.getErrorBody()); errorDetailRef.set(anError.getErrorDetail()); errorCodeRef.set(anError.getErrorCode()); latch.countDown(); } }); assertTrue(latch.await(2, SECONDS)); assertEquals(ANConstants.RESPONSE_FROM_SERVER_ERROR, errorDetailRef.get()); assertEquals("data", errorBodyRef.get()); assertEquals(404, errorCodeRef.get().intValue()); } public void testHeaderMultipartRequest() throws InterruptedException { server.enqueue(new MockResponse().setBody("{\"firstName\":\"Amit\", \"lastName\":\"Shekhar\"}")); final AtomicReference firstNameRef = new AtomicReference<>(); final AtomicReference lastNameRef = new AtomicReference<>(); final AtomicReference headerRef = new AtomicReference<>(); final AtomicReference responseBodySuccess = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.upload(server.url("/").toString()) .addHeaders("headerKey", "headerValue") .addMultipartParameter("key", "value") .setExecutor(Executors.newSingleThreadExecutor()) .build() .getAsOkHttpResponseAndObject(User.class, new OkHttpResponseAndParsedRequestListener() { @Override public void onResponse(Response okHttpResponse, User user) { firstNameRef.set(user.firstName); lastNameRef.set(user.lastName); responseBodySuccess.set(okHttpResponse.isSuccessful()); headerRef.set(okHttpResponse.request().header("headerKey")); latch.countDown(); } @Override public void onError(ANError anError) { assertTrue(false); } }); assertTrue(latch.await(2, SECONDS)); assertTrue(responseBodySuccess.get()); assertEquals("Amit", firstNameRef.get()); assertEquals("Shekhar", lastNameRef.get()); assertEquals("headerValue", headerRef.get()); } } ================================================ FILE: android-networking/src/androidTest/java/com/androidnetworking/MultipartStringApiTest.java ================================================ /* * * * Copyright (C) 2016 Amit Shekhar * * Copyright (C) 2011 Android Open Source Project * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * */ package com.androidnetworking; import android.app.Application; import android.test.ApplicationTestCase; import com.androidnetworking.common.ANConstants; import com.androidnetworking.common.ANRequest; import com.androidnetworking.common.ANResponse; import com.androidnetworking.error.ANError; import com.androidnetworking.interfaces.OkHttpResponseAndParsedRequestListener; import com.androidnetworking.interfaces.OkHttpResponseAndStringRequestListener; import com.androidnetworking.interfaces.OkHttpResponseListener; import com.androidnetworking.interfaces.StringRequestListener; import com.androidnetworking.model.User; import org.junit.Rule; import java.io.IOException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicReference; import okhttp3.Response; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import static java.util.concurrent.TimeUnit.SECONDS; /** * Created by amitshekhar on 27/03/17. */ public class MultipartStringApiTest extends ApplicationTestCase { @Rule public final MockWebServer server = new MockWebServer(); public MultipartStringApiTest() { super(Application.class); } @Override public void setUp() throws Exception { super.setUp(); createApplication(); } public void testStringMultipartRequest() throws InterruptedException { server.enqueue(new MockResponse().setBody("data")); final AtomicReference responseRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.upload(server.url("/").toString()) .addMultipartParameter("key", "value") .build() .getAsString(new StringRequestListener() { @Override public void onResponse(String response) { responseRef.set(response); latch.countDown(); } @Override public void onError(ANError anError) { assertTrue(false); } }); assertTrue(latch.await(2, SECONDS)); assertEquals("data", responseRef.get()); } public void testStringMultipartRequest404() throws InterruptedException { server.enqueue(new MockResponse().setResponseCode(404).setBody("data")); final AtomicReference errorDetailRef = new AtomicReference<>(); final AtomicReference errorBodyRef = new AtomicReference<>(); final AtomicReference errorCodeRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.upload(server.url("/").toString()) .addMultipartParameter("key", "value") .build() .getAsString(new StringRequestListener() { @Override public void onResponse(String response) { assertTrue(false); } @Override public void onError(ANError anError) { errorBodyRef.set(anError.getErrorBody()); errorDetailRef.set(anError.getErrorDetail()); errorCodeRef.set(anError.getErrorCode()); latch.countDown(); } }); assertTrue(latch.await(2, SECONDS)); assertEquals(ANConstants.RESPONSE_FROM_SERVER_ERROR, errorDetailRef.get()); assertEquals("data", errorBodyRef.get()); assertEquals(404, errorCodeRef.get().intValue()); } @SuppressWarnings("unchecked") public void testSynchronousStringMultipartRequest() throws InterruptedException { server.enqueue(new MockResponse().setBody("data")); ANRequest request = AndroidNetworking.upload(server.url("/").toString()) .addMultipartParameter("key", "value") .build(); ANResponse response = request.executeForString(); assertEquals("data", response.getResult()); } @SuppressWarnings("unchecked") public void testSynchronousMultipartRequest404() throws InterruptedException { server.enqueue(new MockResponse().setResponseCode(404).setBody("data")); ANRequest request = AndroidNetworking.upload(server.url("/").toString()) .addMultipartParameter("key", "value") .build(); ANResponse response = request.executeForString(); ANError error = response.getError(); assertEquals("data", error.getErrorBody()); assertEquals(ANConstants.RESPONSE_FROM_SERVER_ERROR, error.getErrorDetail()); assertEquals(404, error.getErrorCode()); } public void testResponseBodyMultipart() throws InterruptedException { server.enqueue(new MockResponse().setBody("data")); final AtomicReference responseRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.upload(server.url("/").toString()) .addMultipartParameter("key", "value") .setExecutor(Executors.newSingleThreadExecutor()) .build() .getAsOkHttpResponse(new OkHttpResponseListener() { @Override public void onResponse(Response response) { try { responseRef.set(response.body().string()); latch.countDown(); } catch (IOException e) { assertTrue(false); } } @Override public void onError(ANError anError) { assertTrue(false); } }); assertTrue(latch.await(2, SECONDS)); assertEquals("data", responseRef.get()); } public void testResponseBodyMultipart404() throws InterruptedException { server.enqueue(new MockResponse().setResponseCode(404).setBody("data")); final AtomicReference errorBodyRef = new AtomicReference<>(); final AtomicReference errorCodeRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.upload(server.url("/").toString()) .addMultipartParameter("key", "value") .setExecutor(Executors.newSingleThreadExecutor()) .build() .getAsOkHttpResponse(new OkHttpResponseListener() { @Override public void onResponse(Response response) { try { errorBodyRef.set(response.body().string()); errorCodeRef.set(response.code()); latch.countDown(); } catch (IOException e) { assertTrue(false); } } @Override public void onError(ANError anError) { assertTrue(false); } }); assertTrue(latch.await(2, SECONDS)); assertEquals("data", errorBodyRef.get()); assertEquals(404, errorCodeRef.get().intValue()); } @SuppressWarnings("unchecked") public void testSyncResponseBodyMultipart() throws InterruptedException, IOException { server.enqueue(new MockResponse().setBody("data")); ANRequest request = AndroidNetworking.upload(server.url("/").toString()) .addMultipartParameter("key", "value") .build(); ANResponse response = request.executeForOkHttpResponse(); assertEquals("data", response.getResult().body().string()); } @SuppressWarnings("unchecked") public void testSyncResponseBodyMultipart404() throws InterruptedException, IOException { server.enqueue(new MockResponse().setResponseCode(404).setBody("data")); ANRequest request = AndroidNetworking.upload(server.url("/").toString()) .addMultipartParameter("key", "value") .build(); ANResponse response = request.executeForOkHttpResponse(); assertEquals("data", response.getResult().body().string()); assertEquals(404, response.getResult().code()); } public void testResponseBodyAndStringMultipart() throws InterruptedException { server.enqueue(new MockResponse().setBody("data")); final AtomicReference responseBodySuccess = new AtomicReference<>(); final AtomicReference responseStringRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.upload(server.url("/").toString()) .addMultipartParameter("key", "value") .setExecutor(Executors.newSingleThreadExecutor()) .build() .getAsOkHttpResponseAndString(new OkHttpResponseAndStringRequestListener() { @Override public void onResponse(Response okHttpResponse, String response) { responseBodySuccess.set(okHttpResponse.isSuccessful()); responseStringRef.set(response); latch.countDown(); } @Override public void onError(ANError anError) { assertTrue(false); } }); assertTrue(latch.await(2, SECONDS)); assertTrue(responseBodySuccess.get()); assertEquals("data", responseStringRef.get()); } public void testResponseBodyAndStringMultipart404() throws InterruptedException { server.enqueue(new MockResponse().setResponseCode(404).setBody("data")); final AtomicReference errorBodyRef = new AtomicReference<>(); final AtomicReference errorCodeRef = new AtomicReference<>(); final AtomicReference errorDetailRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.upload(server.url("/").toString()) .addMultipartParameter("key", "value") .setExecutor(Executors.newSingleThreadExecutor()) .build() .getAsOkHttpResponseAndString(new OkHttpResponseAndStringRequestListener() { @Override public void onResponse(Response okHttpResponse, String response) { assertTrue(false); } @Override public void onError(ANError anError) { errorBodyRef.set(anError.getErrorBody()); errorDetailRef.set(anError.getErrorDetail()); errorCodeRef.set(anError.getErrorCode()); latch.countDown(); } }); assertTrue(latch.await(2, SECONDS)); assertEquals(ANConstants.RESPONSE_FROM_SERVER_ERROR, errorDetailRef.get()); assertEquals("data", errorBodyRef.get()); assertEquals(404, errorCodeRef.get().intValue()); } public void testHeaderMultipartRequest() throws InterruptedException { server.enqueue(new MockResponse().setBody("data")); final AtomicReference responseRef = new AtomicReference<>(); final AtomicReference headerRef = new AtomicReference<>(); final AtomicReference responseBodySuccess = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.upload(server.url("/").toString()) .addHeaders("headerKey", "headerValue") .addMultipartParameter("key", "value") .setExecutor(Executors.newSingleThreadExecutor()) .build() .getAsOkHttpResponseAndString(new OkHttpResponseAndStringRequestListener() { @Override public void onResponse(Response okHttpResponse, String response) { responseRef.set(response); responseBodySuccess.set(okHttpResponse.isSuccessful()); headerRef.set(okHttpResponse.request().header("headerKey")); latch.countDown(); } @Override public void onError(ANError anError) { assertTrue(false); } }); assertTrue(latch.await(2, SECONDS)); assertTrue(responseBodySuccess.get()); assertEquals("data", responseRef.get()); assertEquals("headerValue", headerRef.get()); } } ================================================ FILE: android-networking/src/androidTest/java/com/androidnetworking/PostJSONApiTest.java ================================================ /* * * * Copyright (C) 2016 Amit Shekhar * * Copyright (C) 2011 Android Open Source Project * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * */ package com.androidnetworking; import android.app.Application; import android.test.ApplicationTestCase; import com.androidnetworking.common.ANConstants; import com.androidnetworking.common.ANRequest; import com.androidnetworking.common.ANResponse; import com.androidnetworking.error.ANError; import com.androidnetworking.interfaces.JSONArrayRequestListener; import com.androidnetworking.interfaces.JSONObjectRequestListener; import com.androidnetworking.interfaces.OkHttpResponseAndJSONArrayRequestListener; import com.androidnetworking.interfaces.OkHttpResponseAndJSONObjectRequestListener; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.junit.Rule; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicReference; import okhttp3.Response; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import static java.util.concurrent.TimeUnit.SECONDS; /** * Created by amitshekhar on 06/04/17. */ public class PostJSONApiTest extends ApplicationTestCase { @Rule public final MockWebServer server = new MockWebServer(); public PostJSONApiTest() { super(Application.class); } @Override public void setUp() throws Exception { super.setUp(); createApplication(); } public void testJSONObjectPostRequest() throws InterruptedException { server.enqueue(new MockResponse().setBody("{\"firstName\":\"Amit\", \"lastName\":\"Shekhar\"}")); final AtomicReference firstNameRef = new AtomicReference<>(); final AtomicReference lastNameRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.post(server.url("/").toString()) .addBodyParameter("fistName", "Amit") .addBodyParameter("lastName", "Shekhar") .build() .getAsJSONObject(new JSONObjectRequestListener() { @Override public void onResponse(JSONObject response) { try { firstNameRef.set(response.getString("firstName")); lastNameRef.set(response.getString("lastName")); latch.countDown(); } catch (JSONException e) { assertTrue(false); } } @Override public void onError(ANError anError) { assertTrue(false); } }); assertTrue(latch.await(2, SECONDS)); assertEquals("Amit", firstNameRef.get()); assertEquals("Shekhar", lastNameRef.get()); } public void testJSONObjectPostRequest404() throws InterruptedException { server.enqueue(new MockResponse().setResponseCode(404).setBody("data")); final AtomicReference errorDetailRef = new AtomicReference<>(); final AtomicReference errorBodyRef = new AtomicReference<>(); final AtomicReference errorCodeRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.post(server.url("/").toString()) .addBodyParameter("fistName", "Amit") .addBodyParameter("lastName", "Shekhar") .build() .getAsJSONObject(new JSONObjectRequestListener() { @Override public void onResponse(JSONObject response) { assertTrue(false); } @Override public void onError(ANError anError) { errorBodyRef.set(anError.getErrorBody()); errorDetailRef.set(anError.getErrorDetail()); errorCodeRef.set(anError.getErrorCode()); latch.countDown(); } }); assertTrue(latch.await(2, SECONDS)); assertEquals(ANConstants.RESPONSE_FROM_SERVER_ERROR, errorDetailRef.get()); assertEquals("data", errorBodyRef.get()); assertEquals(404, errorCodeRef.get().intValue()); } public void testJSONArrayPostRequest() throws InterruptedException { server.enqueue(new MockResponse().setBody("[{\"firstName\":\"Amit\", \"lastName\":\"Shekhar\"}]")); final AtomicReference firstNameRef = new AtomicReference<>(); final AtomicReference lastNameRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.post(server.url("/").toString()) .addBodyParameter("fistName", "Amit") .addBodyParameter("lastName", "Shekhar") .build() .getAsJSONArray(new JSONArrayRequestListener() { @Override public void onResponse(JSONArray response) { try { JSONObject jsonObject = response.getJSONObject(0); firstNameRef.set(jsonObject.getString("firstName")); lastNameRef.set(jsonObject.getString("lastName")); latch.countDown(); } catch (JSONException e) { assertTrue(false); } } @Override public void onError(ANError anError) { assertTrue(false); } }); assertTrue(latch.await(2, SECONDS)); assertEquals("Amit", firstNameRef.get()); assertEquals("Shekhar", lastNameRef.get()); } public void testJSONArrayPostRequest404() throws InterruptedException { server.enqueue(new MockResponse().setResponseCode(404).setBody("data")); final AtomicReference errorDetailRef = new AtomicReference<>(); final AtomicReference errorBodyRef = new AtomicReference<>(); final AtomicReference errorCodeRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.post(server.url("/").toString()) .addBodyParameter("fistName", "Amit") .addBodyParameter("lastName", "Shekhar") .build() .getAsJSONArray(new JSONArrayRequestListener() { @Override public void onResponse(JSONArray response) { assertTrue(false); } @Override public void onError(ANError anError) { errorBodyRef.set(anError.getErrorBody()); errorDetailRef.set(anError.getErrorDetail()); errorCodeRef.set(anError.getErrorCode()); latch.countDown(); } }); assertTrue(latch.await(2, SECONDS)); assertEquals(ANConstants.RESPONSE_FROM_SERVER_ERROR, errorDetailRef.get()); assertEquals("data", errorBodyRef.get()); assertEquals(404, errorCodeRef.get().intValue()); } @SuppressWarnings("unchecked") public void testSynchronousJSONObjectPostRequest() throws InterruptedException, JSONException { server.enqueue(new MockResponse().setBody("{\"firstName\":\"Amit\", \"lastName\":\"Shekhar\"}")); ANRequest request = AndroidNetworking.post(server.url("/").toString()) .addBodyParameter("fistName", "Amit") .addBodyParameter("lastName", "Shekhar") .build(); ANResponse response = request.executeForJSONObject(); assertEquals("Amit", response.getResult().getString("firstName")); assertEquals("Shekhar", response.getResult().getString("lastName")); } @SuppressWarnings("unchecked") public void testSynchronousJSONObjectPostRequest404() throws InterruptedException { server.enqueue(new MockResponse().setResponseCode(404).setBody("data")); ANRequest request = AndroidNetworking.post(server.url("/").toString()) .addBodyParameter("fistName", "Amit") .addBodyParameter("lastName", "Shekhar") .build(); ANResponse response = request.executeForJSONObject(); ANError error = response.getError(); assertEquals("data", error.getErrorBody()); assertEquals(ANConstants.RESPONSE_FROM_SERVER_ERROR, error.getErrorDetail()); assertEquals(404, error.getErrorCode()); } @SuppressWarnings("unchecked") public void testSynchronousJSONArrayPostRequest() throws InterruptedException, JSONException { server.enqueue(new MockResponse().setBody("[{\"firstName\":\"Amit\", \"lastName\":\"Shekhar\"}]")); ANRequest request = AndroidNetworking.post(server.url("/").toString()) .addBodyParameter("fistName", "Amit") .addBodyParameter("lastName", "Shekhar") .build(); ANResponse response = request.executeForJSONArray(); JSONObject jsonObject = response.getResult().getJSONObject(0); assertEquals("Amit", jsonObject.getString("firstName")); assertEquals("Shekhar", jsonObject.getString("lastName")); } @SuppressWarnings("unchecked") public void testSynchronousJSONArrayPostRequest404() throws InterruptedException { server.enqueue(new MockResponse().setResponseCode(404).setBody("data")); ANRequest request = AndroidNetworking.post(server.url("/").toString()) .addBodyParameter("fistName", "Amit") .addBodyParameter("lastName", "Shekhar") .build(); ANResponse response = request.executeForJSONArray(); ANError error = response.getError(); assertEquals("data", error.getErrorBody()); assertEquals(ANConstants.RESPONSE_FROM_SERVER_ERROR, error.getErrorDetail()); assertEquals(404, error.getErrorCode()); } public void testResponseBodyAndJSONObjectPost() throws InterruptedException { server.enqueue(new MockResponse().setBody("{\"firstName\":\"Amit\", \"lastName\":\"Shekhar\"}")); final AtomicReference firstNameRef = new AtomicReference<>(); final AtomicReference lastNameRef = new AtomicReference<>(); final AtomicReference responseBodySuccess = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.post(server.url("/").toString()) .addBodyParameter("fistName", "Amit") .addBodyParameter("lastName", "Shekhar") .setExecutor(Executors.newSingleThreadExecutor()) .build() .getAsOkHttpResponseAndJSONObject(new OkHttpResponseAndJSONObjectRequestListener() { @Override public void onResponse(Response okHttpResponse, JSONObject response) { try { firstNameRef.set(response.getString("firstName")); lastNameRef.set(response.getString("lastName")); responseBodySuccess.set(okHttpResponse.isSuccessful()); latch.countDown(); } catch (JSONException e) { assertTrue(false); } } @Override public void onError(ANError anError) { assertTrue(false); } }); assertTrue(latch.await(2, SECONDS)); assertTrue(responseBodySuccess.get()); assertEquals("Amit", firstNameRef.get()); assertEquals("Shekhar", lastNameRef.get()); } public void testResponseBodyAndJSONObjectPost404() throws InterruptedException { server.enqueue(new MockResponse().setResponseCode(404).setBody("data")); final AtomicReference errorBodyRef = new AtomicReference<>(); final AtomicReference errorCodeRef = new AtomicReference<>(); final AtomicReference errorDetailRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.post(server.url("/").toString()) .addBodyParameter("fistName", "Amit") .addBodyParameter("lastName", "Shekhar") .setExecutor(Executors.newSingleThreadExecutor()) .build() .getAsOkHttpResponseAndJSONObject(new OkHttpResponseAndJSONObjectRequestListener() { @Override public void onResponse(Response okHttpResponse, JSONObject response) { assertTrue(false); } @Override public void onError(ANError anError) { errorBodyRef.set(anError.getErrorBody()); errorDetailRef.set(anError.getErrorDetail()); errorCodeRef.set(anError.getErrorCode()); latch.countDown(); } }); assertTrue(latch.await(2, SECONDS)); assertEquals(ANConstants.RESPONSE_FROM_SERVER_ERROR, errorDetailRef.get()); assertEquals("data", errorBodyRef.get()); assertEquals(404, errorCodeRef.get().intValue()); } public void testResponseBodyAndJSONArrayPost() throws InterruptedException { server.enqueue(new MockResponse().setBody("[{\"firstName\":\"Amit\", \"lastName\":\"Shekhar\"}]")); final AtomicReference firstNameRef = new AtomicReference<>(); final AtomicReference lastNameRef = new AtomicReference<>(); final AtomicReference responseBodySuccess = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.post(server.url("/").toString()) .addBodyParameter("fistName", "Amit") .addBodyParameter("lastName", "Shekhar") .setExecutor(Executors.newSingleThreadExecutor()) .build() .getAsOkHttpResponseAndJSONArray(new OkHttpResponseAndJSONArrayRequestListener() { @Override public void onResponse(Response okHttpResponse, JSONArray response) { try { JSONObject jsonObject = response.getJSONObject(0); firstNameRef.set(jsonObject.getString("firstName")); lastNameRef.set(jsonObject.getString("lastName")); responseBodySuccess.set(okHttpResponse.isSuccessful()); latch.countDown(); } catch (JSONException e) { assertTrue(false); } } @Override public void onError(ANError anError) { assertTrue(false); } }); assertTrue(latch.await(2, SECONDS)); assertTrue(responseBodySuccess.get()); assertEquals("Amit", firstNameRef.get()); assertEquals("Shekhar", lastNameRef.get()); } public void testResponseBodyAndJSONArrayPost404() throws InterruptedException { server.enqueue(new MockResponse().setResponseCode(404).setBody("data")); final AtomicReference errorBodyRef = new AtomicReference<>(); final AtomicReference errorCodeRef = new AtomicReference<>(); final AtomicReference errorDetailRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.post(server.url("/").toString()) .addBodyParameter("fistName", "Amit") .addBodyParameter("lastName", "Shekhar") .setExecutor(Executors.newSingleThreadExecutor()) .build() .getAsOkHttpResponseAndJSONArray(new OkHttpResponseAndJSONArrayRequestListener() { @Override public void onResponse(Response okHttpResponse, JSONArray response) { assertTrue(false); } @Override public void onError(ANError anError) { errorBodyRef.set(anError.getErrorBody()); errorDetailRef.set(anError.getErrorDetail()); errorCodeRef.set(anError.getErrorCode()); latch.countDown(); } }); assertTrue(latch.await(2, SECONDS)); assertEquals(ANConstants.RESPONSE_FROM_SERVER_ERROR, errorDetailRef.get()); assertEquals("data", errorBodyRef.get()); assertEquals(404, errorCodeRef.get().intValue()); } public void testHeaderPostRequest() throws InterruptedException { server.enqueue(new MockResponse().setBody("{\"firstName\":\"Amit\", \"lastName\":\"Shekhar\"}")); final AtomicReference firstNameRef = new AtomicReference<>(); final AtomicReference lastNameRef = new AtomicReference<>(); final AtomicReference headerRef = new AtomicReference<>(); final AtomicReference responseBodySuccess = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.post(server.url("/").toString()) .addHeaders("headerKey", "headerValue") .addBodyParameter("fistName", "Amit") .addBodyParameter("lastName", "Shekhar") .setExecutor(Executors.newSingleThreadExecutor()) .build() .getAsOkHttpResponseAndJSONObject(new OkHttpResponseAndJSONObjectRequestListener() { @Override public void onResponse(Response okHttpResponse, JSONObject response) { try { firstNameRef.set(response.getString("firstName")); lastNameRef.set(response.getString("lastName")); responseBodySuccess.set(okHttpResponse.isSuccessful()); headerRef.set(okHttpResponse.request().header("headerKey")); latch.countDown(); } catch (JSONException e) { assertTrue(false); } } @Override public void onError(ANError anError) { assertTrue(false); } }); assertTrue(latch.await(2, SECONDS)); assertTrue(responseBodySuccess.get()); assertEquals("Amit", firstNameRef.get()); assertEquals("Shekhar", lastNameRef.get()); assertEquals("headerValue", headerRef.get()); } } ================================================ FILE: android-networking/src/androidTest/java/com/androidnetworking/PostObjectApiTest.java ================================================ /* * * * Copyright (C) 2016 Amit Shekhar * * Copyright (C) 2011 Android Open Source Project * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * */ package com.androidnetworking; import android.app.Application; import android.test.ApplicationTestCase; import com.androidnetworking.common.ANConstants; import com.androidnetworking.common.ANRequest; import com.androidnetworking.common.ANResponse; import com.androidnetworking.error.ANError; import com.androidnetworking.interfaces.OkHttpResponseAndParsedRequestListener; import com.androidnetworking.interfaces.ParsedRequestListener; import com.androidnetworking.model.User; import org.json.JSONException; import org.junit.Rule; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicReference; import okhttp3.Response; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import static java.util.concurrent.TimeUnit.SECONDS; /** * Created by amitshekhar on 11/04/17. */ public class PostObjectApiTest extends ApplicationTestCase { @Rule public final MockWebServer server = new MockWebServer(); public PostObjectApiTest() { super(Application.class); } @Override public void setUp() throws Exception { super.setUp(); createApplication(); } public void testObjectPostRequest() throws InterruptedException { server.enqueue(new MockResponse().setBody("{\"firstName\":\"Amit\", \"lastName\":\"Shekhar\"}")); final AtomicReference firstNameRef = new AtomicReference<>(); final AtomicReference lastNameRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.post(server.url("/").toString()) .addBodyParameter("fistName", "Amit") .addBodyParameter("lastName", "Shekhar") .build() .getAsObject(User.class, new ParsedRequestListener() { @Override public void onResponse(User user) { firstNameRef.set(user.firstName); lastNameRef.set(user.lastName); latch.countDown(); } @Override public void onError(ANError anError) { assertTrue(false); } }); assertTrue(latch.await(2, SECONDS)); assertEquals("Amit", firstNameRef.get()); assertEquals("Shekhar", lastNameRef.get()); } public void testObjectPostRequest404() throws InterruptedException { server.enqueue(new MockResponse().setResponseCode(404).setBody("data")); final AtomicReference errorDetailRef = new AtomicReference<>(); final AtomicReference errorBodyRef = new AtomicReference<>(); final AtomicReference errorCodeRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.post(server.url("/").toString()) .addBodyParameter("fistName", "Amit") .addBodyParameter("lastName", "Shekhar") .build() .getAsObject(User.class, new ParsedRequestListener() { @Override public void onResponse(User user) { assertTrue(false); } @Override public void onError(ANError anError) { errorBodyRef.set(anError.getErrorBody()); errorDetailRef.set(anError.getErrorDetail()); errorCodeRef.set(anError.getErrorCode()); latch.countDown(); } }); assertTrue(latch.await(2, SECONDS)); assertEquals(ANConstants.RESPONSE_FROM_SERVER_ERROR, errorDetailRef.get()); assertEquals("data", errorBodyRef.get()); assertEquals(404, errorCodeRef.get().intValue()); } public void testObjectListPostRequest() throws InterruptedException { server.enqueue(new MockResponse().setBody("[{\"firstName\":\"Amit\", \"lastName\":\"Shekhar\"}]")); final AtomicReference firstNameRef = new AtomicReference<>(); final AtomicReference lastNameRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.post(server.url("/").toString()) .addBodyParameter("fistName", "Amit") .addBodyParameter("lastName", "Shekhar") .build() .getAsObjectList(User.class, new ParsedRequestListener>() { @Override public void onResponse(List userList) { firstNameRef.set(userList.get(0).firstName); lastNameRef.set(userList.get(0).lastName); latch.countDown(); } @Override public void onError(ANError anError) { assertTrue(false); } }); assertTrue(latch.await(2, SECONDS)); assertEquals("Amit", firstNameRef.get()); assertEquals("Shekhar", lastNameRef.get()); } public void testObjectListPostRequest404() throws InterruptedException { server.enqueue(new MockResponse().setResponseCode(404).setBody("data")); final AtomicReference errorDetailRef = new AtomicReference<>(); final AtomicReference errorBodyRef = new AtomicReference<>(); final AtomicReference errorCodeRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.post(server.url("/").toString()) .addBodyParameter("fistName", "Amit") .addBodyParameter("lastName", "Shekhar") .build() .getAsObjectList(User.class, new ParsedRequestListener>() { @Override public void onResponse(List userList) { assertTrue(false); } @Override public void onError(ANError anError) { errorBodyRef.set(anError.getErrorBody()); errorDetailRef.set(anError.getErrorDetail()); errorCodeRef.set(anError.getErrorCode()); latch.countDown(); } }); assertTrue(latch.await(2, SECONDS)); assertEquals(ANConstants.RESPONSE_FROM_SERVER_ERROR, errorDetailRef.get()); assertEquals("data", errorBodyRef.get()); assertEquals(404, errorCodeRef.get().intValue()); } @SuppressWarnings("unchecked") public void testSynchronousObjectPostRequest() throws InterruptedException, JSONException { server.enqueue(new MockResponse().setBody("{\"firstName\":\"Amit\", \"lastName\":\"Shekhar\"}")); ANRequest request = AndroidNetworking.post(server.url("/").toString()) .addBodyParameter("fistName", "Amit") .addBodyParameter("lastName", "Shekhar") .build(); ANResponse response = request.executeForObject(User.class); assertEquals("Amit", response.getResult().firstName); assertEquals("Shekhar", response.getResult().lastName); } @SuppressWarnings("unchecked") public void testSynchronousObjectPostRequest404() throws InterruptedException { server.enqueue(new MockResponse().setResponseCode(404).setBody("data")); ANRequest request = AndroidNetworking.post(server.url("/").toString()) .addBodyParameter("fistName", "Amit") .addBodyParameter("lastName", "Shekhar") .build(); ANResponse response = request.executeForObject(User.class); ANError error = response.getError(); assertEquals("data", error.getErrorBody()); assertEquals(ANConstants.RESPONSE_FROM_SERVER_ERROR, error.getErrorDetail()); assertEquals(404, error.getErrorCode()); } @SuppressWarnings("unchecked") public void testSynchronousObjectListPostRequest() throws InterruptedException, JSONException { server.enqueue(new MockResponse().setBody("[{\"firstName\":\"Amit\", \"lastName\":\"Shekhar\"}]")); ANRequest request = AndroidNetworking.post(server.url("/").toString()) .addBodyParameter("fistName", "Amit") .addBodyParameter("lastName", "Shekhar") .build(); ANResponse> response = request.executeForObjectList(User.class); User user = response.getResult().get(0); assertEquals("Amit", user.firstName); assertEquals("Shekhar", user.lastName); } @SuppressWarnings("unchecked") public void testSynchronousObjectListPostRequest404() throws InterruptedException { server.enqueue(new MockResponse().setResponseCode(404).setBody("data")); ANRequest request = AndroidNetworking.post(server.url("/").toString()) .addBodyParameter("fistName", "Amit") .addBodyParameter("lastName", "Shekhar") .build(); ANResponse> response = request.executeForObjectList(User.class); ANError error = response.getError(); assertEquals("data", error.getErrorBody()); assertEquals(ANConstants.RESPONSE_FROM_SERVER_ERROR, error.getErrorDetail()); assertEquals(404, error.getErrorCode()); } public void testResponseBodyAndObjectPost() throws InterruptedException { server.enqueue(new MockResponse().setBody("{\"firstName\":\"Amit\", \"lastName\":\"Shekhar\"}")); final AtomicReference firstNameRef = new AtomicReference<>(); final AtomicReference lastNameRef = new AtomicReference<>(); final AtomicReference responseBodySuccess = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.post(server.url("/").toString()) .addBodyParameter("fistName", "Amit") .addBodyParameter("lastName", "Shekhar") .setExecutor(Executors.newSingleThreadExecutor()) .build() .getAsOkHttpResponseAndObject(User.class, new OkHttpResponseAndParsedRequestListener() { @Override public void onResponse(Response okHttpResponse, User user) { firstNameRef.set(user.firstName); lastNameRef.set(user.lastName); responseBodySuccess.set(okHttpResponse.isSuccessful()); latch.countDown(); } @Override public void onError(ANError anError) { assertTrue(false); } }); assertTrue(latch.await(2, SECONDS)); assertTrue(responseBodySuccess.get()); assertEquals("Amit", firstNameRef.get()); assertEquals("Shekhar", lastNameRef.get()); } public void testResponseBodyAndObjectPost404() throws InterruptedException { server.enqueue(new MockResponse().setResponseCode(404).setBody("data")); final AtomicReference errorBodyRef = new AtomicReference<>(); final AtomicReference errorCodeRef = new AtomicReference<>(); final AtomicReference errorDetailRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.post(server.url("/").toString()) .addBodyParameter("fistName", "Amit") .addBodyParameter("lastName", "Shekhar") .setExecutor(Executors.newSingleThreadExecutor()) .build() .getAsOkHttpResponseAndObject(User.class, new OkHttpResponseAndParsedRequestListener() { @Override public void onResponse(Response okHttpResponse, User user) { assertTrue(false); } @Override public void onError(ANError anError) { errorBodyRef.set(anError.getErrorBody()); errorDetailRef.set(anError.getErrorDetail()); errorCodeRef.set(anError.getErrorCode()); latch.countDown(); } }); assertTrue(latch.await(2, SECONDS)); assertEquals(ANConstants.RESPONSE_FROM_SERVER_ERROR, errorDetailRef.get()); assertEquals("data", errorBodyRef.get()); assertEquals(404, errorCodeRef.get().intValue()); } public void testResponseBodyAndObjectListPost() throws InterruptedException { server.enqueue(new MockResponse().setBody("[{\"firstName\":\"Amit\", \"lastName\":\"Shekhar\"}]")); final AtomicReference firstNameRef = new AtomicReference<>(); final AtomicReference lastNameRef = new AtomicReference<>(); final AtomicReference responseBodySuccess = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.post(server.url("/").toString()) .addBodyParameter("fistName", "Amit") .addBodyParameter("lastName", "Shekhar") .setExecutor(Executors.newSingleThreadExecutor()) .build() .getAsOkHttpResponseAndObjectList(User.class, new OkHttpResponseAndParsedRequestListener>() { @Override public void onResponse(Response okHttpResponse, List userList) { firstNameRef.set(userList.get(0).firstName); lastNameRef.set(userList.get(0).lastName); responseBodySuccess.set(okHttpResponse.isSuccessful()); latch.countDown(); } @Override public void onError(ANError anError) { assertTrue(false); } }); assertTrue(latch.await(2, SECONDS)); assertTrue(responseBodySuccess.get()); assertEquals("Amit", firstNameRef.get()); assertEquals("Shekhar", lastNameRef.get()); } public void testResponseBodyAndObjectListPost404() throws InterruptedException { server.enqueue(new MockResponse().setResponseCode(404).setBody("data")); final AtomicReference errorBodyRef = new AtomicReference<>(); final AtomicReference errorCodeRef = new AtomicReference<>(); final AtomicReference errorDetailRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.post(server.url("/").toString()) .addBodyParameter("fistName", "Amit") .addBodyParameter("lastName", "Shekhar") .setExecutor(Executors.newSingleThreadExecutor()) .build() .getAsOkHttpResponseAndObjectList(User.class, new OkHttpResponseAndParsedRequestListener>() { @Override public void onResponse(Response okHttpResponse, List userList) { assertTrue(false); } @Override public void onError(ANError anError) { errorBodyRef.set(anError.getErrorBody()); errorDetailRef.set(anError.getErrorDetail()); errorCodeRef.set(anError.getErrorCode()); latch.countDown(); } }); assertTrue(latch.await(2, SECONDS)); assertEquals(ANConstants.RESPONSE_FROM_SERVER_ERROR, errorDetailRef.get()); assertEquals("data", errorBodyRef.get()); assertEquals(404, errorCodeRef.get().intValue()); } public void testHeaderPostRequest() throws InterruptedException { server.enqueue(new MockResponse().setBody("{\"firstName\":\"Amit\", \"lastName\":\"Shekhar\"}")); final AtomicReference firstNameRef = new AtomicReference<>(); final AtomicReference lastNameRef = new AtomicReference<>(); final AtomicReference headerRef = new AtomicReference<>(); final AtomicReference responseBodySuccess = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.post(server.url("/").toString()) .addHeaders("headerKey", "headerValue") .addBodyParameter("fistName", "Amit") .addBodyParameter("lastName", "Shekhar") .setExecutor(Executors.newSingleThreadExecutor()) .build() .getAsOkHttpResponseAndObject(User.class, new OkHttpResponseAndParsedRequestListener() { @Override public void onResponse(Response okHttpResponse, User user) { firstNameRef.set(user.firstName); lastNameRef.set(user.lastName); responseBodySuccess.set(okHttpResponse.isSuccessful()); headerRef.set(okHttpResponse.request().header("headerKey")); latch.countDown(); } @Override public void onError(ANError anError) { assertTrue(false); } }); assertTrue(latch.await(2, SECONDS)); assertTrue(responseBodySuccess.get()); assertEquals("Amit", firstNameRef.get()); assertEquals("Shekhar", lastNameRef.get()); assertEquals("headerValue", headerRef.get()); } } ================================================ FILE: android-networking/src/androidTest/java/com/androidnetworking/PostStringApiTest.java ================================================ /* * * * Copyright (C) 2016 Amit Shekhar * * Copyright (C) 2011 Android Open Source Project * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * */ package com.androidnetworking; import android.app.Application; import android.test.ApplicationTestCase; import com.androidnetworking.common.ANConstants; import com.androidnetworking.common.ANRequest; import com.androidnetworking.common.ANResponse; import com.androidnetworking.error.ANError; import com.androidnetworking.interfaces.OkHttpResponseAndStringRequestListener; import com.androidnetworking.interfaces.OkHttpResponseListener; import com.androidnetworking.interfaces.StringRequestListener; import org.junit.Rule; import java.io.IOException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicReference; import okhttp3.Response; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import static java.util.concurrent.TimeUnit.SECONDS; /** * Created by amitshekhar on 25/03/17. */ public class PostStringApiTest extends ApplicationTestCase { @Rule public final MockWebServer server = new MockWebServer(); public PostStringApiTest() { super(Application.class); } @Override public void setUp() throws Exception { super.setUp(); createApplication(); } public void testStringPostRequest() throws InterruptedException { server.enqueue(new MockResponse().setBody("data")); final AtomicReference responseRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.post(server.url("/").toString()) .addBodyParameter("fistName", "Amit") .addBodyParameter("lastName", "Shekhar") .build() .getAsString(new StringRequestListener() { @Override public void onResponse(String response) { responseRef.set(response); latch.countDown(); } @Override public void onError(ANError anError) { assertTrue(false); } }); assertTrue(latch.await(2, SECONDS)); assertEquals("data", responseRef.get()); } public void testStringPostRequest404() throws InterruptedException { server.enqueue(new MockResponse().setResponseCode(404).setBody("data")); final AtomicReference errorDetailRef = new AtomicReference<>(); final AtomicReference errorBodyRef = new AtomicReference<>(); final AtomicReference errorCodeRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.post(server.url("/").toString()) .addBodyParameter("fistName", "Amit") .addBodyParameter("lastName", "Shekhar") .build() .getAsString(new StringRequestListener() { @Override public void onResponse(String response) { assertTrue(false); } @Override public void onError(ANError anError) { errorBodyRef.set(anError.getErrorBody()); errorDetailRef.set(anError.getErrorDetail()); errorCodeRef.set(anError.getErrorCode()); latch.countDown(); } }); assertTrue(latch.await(2, SECONDS)); assertEquals(ANConstants.RESPONSE_FROM_SERVER_ERROR, errorDetailRef.get()); assertEquals("data", errorBodyRef.get()); assertEquals(404, errorCodeRef.get().intValue()); } @SuppressWarnings("unchecked") public void testSynchronousStringPostRequest() throws InterruptedException { server.enqueue(new MockResponse().setBody("data")); ANRequest request = AndroidNetworking.post(server.url("/").toString()) .addBodyParameter("fistName", "Amit") .addBodyParameter("lastName", "Shekhar") .build(); ANResponse response = request.executeForString(); assertEquals("data", response.getResult()); } @SuppressWarnings("unchecked") public void testSynchronousStringPostRequest404() throws InterruptedException { server.enqueue(new MockResponse().setResponseCode(404).setBody("data")); ANRequest request = AndroidNetworking.post(server.url("/").toString()) .addBodyParameter("fistName", "Amit") .addBodyParameter("lastName", "Shekhar") .build(); ANResponse response = request.executeForString(); ANError error = response.getError(); assertEquals("data", error.getErrorBody()); assertEquals(ANConstants.RESPONSE_FROM_SERVER_ERROR, error.getErrorDetail()); assertEquals(404, error.getErrorCode()); } public void testResponseBodyPost() throws InterruptedException { server.enqueue(new MockResponse().setBody("data")); final AtomicReference responseRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.post(server.url("/").toString()) .addBodyParameter("fistName", "Amit") .addBodyParameter("lastName", "Shekhar") .setExecutor(Executors.newSingleThreadExecutor()) .build() .getAsOkHttpResponse(new OkHttpResponseListener() { @Override public void onResponse(Response response) { try { responseRef.set(response.body().string()); latch.countDown(); } catch (IOException e) { assertTrue(false); } } @Override public void onError(ANError anError) { assertTrue(false); } }); assertTrue(latch.await(2, SECONDS)); assertEquals("data", responseRef.get()); } public void testResponseBodyPost404() throws InterruptedException { server.enqueue(new MockResponse().setResponseCode(404).setBody("data")); final AtomicReference errorBodyRef = new AtomicReference<>(); final AtomicReference errorCodeRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.post(server.url("/").toString()) .addBodyParameter("fistName", "Amit") .addBodyParameter("lastName", "Shekhar") .setExecutor(Executors.newSingleThreadExecutor()) .build() .getAsOkHttpResponse(new OkHttpResponseListener() { @Override public void onResponse(Response response) { try { errorBodyRef.set(response.body().string()); errorCodeRef.set(response.code()); latch.countDown(); } catch (IOException e) { assertTrue(false); } } @Override public void onError(ANError anError) { assertTrue(false); } }); assertTrue(latch.await(2, SECONDS)); assertEquals("data", errorBodyRef.get()); assertEquals(404, errorCodeRef.get().intValue()); } @SuppressWarnings("unchecked") public void testSyncResponseBodyPost() throws InterruptedException, IOException { server.enqueue(new MockResponse().setBody("data")); ANRequest request = AndroidNetworking.post(server.url("/").toString()) .addBodyParameter("fistName", "Amit") .addBodyParameter("lastName", "Shekhar") .build(); ANResponse response = request.executeForOkHttpResponse(); assertEquals("data", response.getResult().body().string()); } @SuppressWarnings("unchecked") public void testSyncResponseBodyPost404() throws InterruptedException, IOException { server.enqueue(new MockResponse().setResponseCode(404).setBody("data")); ANRequest request = AndroidNetworking.post(server.url("/").toString()) .addBodyParameter("fistName", "Amit") .addBodyParameter("lastName", "Shekhar") .build(); ANResponse response = request.executeForOkHttpResponse(); assertEquals("data", response.getResult().body().string()); assertEquals(404, response.getResult().code()); } public void testResponseBodyAndStringPost() throws InterruptedException { server.enqueue(new MockResponse().setBody("data")); final AtomicReference responseBodySuccess = new AtomicReference<>(); final AtomicReference responseStringRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.post(server.url("/").toString()) .addBodyParameter("fistName", "Amit") .addBodyParameter("lastName", "Shekhar") .setExecutor(Executors.newSingleThreadExecutor()) .build() .getAsOkHttpResponseAndString(new OkHttpResponseAndStringRequestListener() { @Override public void onResponse(Response okHttpResponse, String response) { responseBodySuccess.set(okHttpResponse.isSuccessful()); responseStringRef.set(response); latch.countDown(); } @Override public void onError(ANError anError) { assertTrue(false); } }); assertTrue(latch.await(2, SECONDS)); assertTrue(responseBodySuccess.get()); assertEquals("data", responseStringRef.get()); } public void testResponseBodyAndStringPost404() throws InterruptedException { server.enqueue(new MockResponse().setResponseCode(404).setBody("data")); final AtomicReference errorBodyRef = new AtomicReference<>(); final AtomicReference errorCodeRef = new AtomicReference<>(); final AtomicReference errorDetailRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.post(server.url("/").toString()) .addBodyParameter("fistName", "Amit") .addBodyParameter("lastName", "Shekhar") .setExecutor(Executors.newSingleThreadExecutor()) .build() .getAsOkHttpResponseAndString(new OkHttpResponseAndStringRequestListener() { @Override public void onResponse(Response okHttpResponse, String response) { assertTrue(false); } @Override public void onError(ANError anError) { errorBodyRef.set(anError.getErrorBody()); errorDetailRef.set(anError.getErrorDetail()); errorCodeRef.set(anError.getErrorCode()); latch.countDown(); } }); assertTrue(latch.await(2, SECONDS)); assertEquals(ANConstants.RESPONSE_FROM_SERVER_ERROR, errorDetailRef.get()); assertEquals("data", errorBodyRef.get()); assertEquals(404, errorCodeRef.get().intValue()); } public void testHeaderPostRequest() throws InterruptedException { server.enqueue(new MockResponse().setBody("data")); final AtomicReference responseRef = new AtomicReference<>(); final AtomicReference headerRef = new AtomicReference<>(); final AtomicReference responseBodySuccess = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); AndroidNetworking.post(server.url("/").toString()) .addHeaders("headerKey", "headerValue") .addBodyParameter("fistName", "Amit") .addBodyParameter("lastName", "Shekhar") .setExecutor(Executors.newSingleThreadExecutor()) .build() .getAsOkHttpResponseAndString(new OkHttpResponseAndStringRequestListener() { @Override public void onResponse(Response okHttpResponse, String response) { responseRef.set(response); responseBodySuccess.set(okHttpResponse.isSuccessful()); headerRef.set(okHttpResponse.request().header("headerKey")); latch.countDown(); } @Override public void onError(ANError anError) { assertTrue(false); } }); assertTrue(latch.await(2, SECONDS)); assertTrue(responseBodySuccess.get()); assertEquals("data", responseRef.get()); assertEquals("headerValue", headerRef.get()); } } ================================================ FILE: android-networking/src/androidTest/java/com/androidnetworking/model/User.java ================================================ /* * * * Copyright (C) 2016 Amit Shekhar * * Copyright (C) 2011 Android Open Source Project * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * */ package com.androidnetworking.model; /** * Created by amitshekhar on 10/04/17. */ public class User { public String firstName; public String lastName; } ================================================ FILE: android-networking/src/main/AndroidManifest.xml ================================================ ================================================ FILE: android-networking/src/main/java/com/androidnetworking/AndroidNetworking.java ================================================ /* * Copyright (C) 2016 Amit Shekhar * Copyright (C) 2011 Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.androidnetworking; import android.content.Context; import android.graphics.BitmapFactory; import com.androidnetworking.common.ANConstants; import com.androidnetworking.common.ANRequest; import com.androidnetworking.common.ConnectionClassManager; import com.androidnetworking.common.ConnectionQuality; import com.androidnetworking.core.Core; import com.androidnetworking.interceptors.HttpLoggingInterceptor.Level; import com.androidnetworking.interfaces.ConnectionQualityChangeListener; import com.androidnetworking.interfaces.Parser; import com.androidnetworking.internal.ANImageLoader; import com.androidnetworking.internal.ANRequestQueue; import com.androidnetworking.internal.InternalNetworking; import com.androidnetworking.utils.ParseUtil; import com.androidnetworking.utils.Utils; import okhttp3.OkHttpClient; /** * Created by amitshekhar on 24/03/16. */ /** * AndroidNetworking entry point. * You must initialize this class before use. The simplest way is to just do * {#code AndroidNetworking.initialize(context)}. */ @SuppressWarnings("unused") public class AndroidNetworking { /** * private constructor to prevent instantiation of this class */ private AndroidNetworking() { } /** * Initializes AndroidNetworking with the default config. * * @param context The context */ public static void initialize(Context context) { InternalNetworking.setClientWithCache(context.getApplicationContext()); ANRequestQueue.initialize(); ANImageLoader.initialize(); } /** * Initializes AndroidNetworking with the specified config. * * @param context The context * @param okHttpClient The okHttpClient */ public static void initialize(Context context, OkHttpClient okHttpClient) { if (okHttpClient != null && okHttpClient.cache() == null) { okHttpClient = okHttpClient .newBuilder() .cache(Utils.getCache(context.getApplicationContext(), ANConstants.MAX_CACHE_SIZE, ANConstants.CACHE_DIR_NAME)) .build(); } InternalNetworking.setClient(okHttpClient); ANRequestQueue.initialize(); ANImageLoader.initialize(); } /** * Method to set decodeOptions * * @param decodeOptions The decode config for Bitmaps */ public static void setBitmapDecodeOptions(BitmapFactory.Options decodeOptions) { if (decodeOptions != null) { ANImageLoader.getInstance().setBitmapDecodeOptions(decodeOptions); } } /** * Method to set connectionQualityChangeListener * * @param connectionChangeListener The connectionQualityChangeListener */ public static void setConnectionQualityChangeListener(ConnectionQualityChangeListener connectionChangeListener) { ConnectionClassManager.getInstance().setListener(connectionChangeListener); } /** * Method to set connectionQualityChangeListener */ public static void removeConnectionQualityChangeListener() { ConnectionClassManager.getInstance().removeListener(); } /** * Method to make GET request * * @param url The url on which request is to be made * @return The GetRequestBuilder */ public static ANRequest.GetRequestBuilder get(String url) { return new ANRequest.GetRequestBuilder(url); } /** * Method to make HEAD request * * @param url The url on which request is to be made * @return The HeadRequestBuilder */ public static ANRequest.HeadRequestBuilder head(String url) { return new ANRequest.HeadRequestBuilder(url); } /** * Method to make OPTIONS request * * @param url The url on which request is to be made * @return The OptionsRequestBuilder */ public static ANRequest.OptionsRequestBuilder options(String url) { return new ANRequest.OptionsRequestBuilder(url); } /** * Method to make POST request * * @param url The url on which request is to be made * @return The PostRequestBuilder */ public static ANRequest.PostRequestBuilder post(String url) { return new ANRequest.PostRequestBuilder(url); } /** * Method to make PUT request * * @param url The url on which request is to be made * @return The PutRequestBuilder */ public static ANRequest.PutRequestBuilder put(String url) { return new ANRequest.PutRequestBuilder(url); } /** * Method to make DELETE request * * @param url The url on which request is to be made * @return The DeleteRequestBuilder */ public static ANRequest.DeleteRequestBuilder delete(String url) { return new ANRequest.DeleteRequestBuilder(url); } /** * Method to make PATCH request * * @param url The url on which request is to be made * @return The PatchRequestBuilder */ public static ANRequest.PatchRequestBuilder patch(String url) { return new ANRequest.PatchRequestBuilder(url); } /** * Method to make download request * * @param url The url on which request is to be made * @param dirPath The directory path on which file is to be saved * @param fileName The file name with which file is to be saved * @return The DownloadBuilder */ public static ANRequest.DownloadBuilder download(String url, String dirPath, String fileName) { return new ANRequest.DownloadBuilder(url, dirPath, fileName); } /** * Method to make upload request * * @param url The url on which request is to be made * @return The MultiPartBuilder */ public static ANRequest.MultiPartBuilder upload(String url) { return new ANRequest.MultiPartBuilder(url); } /** * Method to make Dynamic request * * @param url The url on which request is to be made * @param method The HTTP METHOD for the request * @return The DynamicRequestBuilder */ public static ANRequest.DynamicRequestBuilder request(String url, int method) { return new ANRequest.DynamicRequestBuilder(url, method); } /** * Method to cancel requests with the given tag * * @param tag The tag with which requests are to be cancelled */ public static void cancel(Object tag) { ANRequestQueue.getInstance().cancelRequestWithGivenTag(tag, false); } /** * Method to force cancel requests with the given tag * * @param tag The tag with which requests are to be cancelled */ public static void forceCancel(Object tag) { ANRequestQueue.getInstance().cancelRequestWithGivenTag(tag, true); } /** * Method to cancel all given request */ public static void cancelAll() { ANRequestQueue.getInstance().cancelAll(false); } /** * Method to force cancel all given request */ public static void forceCancelAll() { ANRequestQueue.getInstance().cancelAll(true); } /** * Method to enable logging */ public static void enableLogging() { enableLogging(Level.BASIC); } /** * Method to enable logging with tag * * @param level The level for logging */ public static void enableLogging(Level level) { InternalNetworking.enableLogging(level); } /** * Method to evict a bitmap with given key from LruCache * * @param key The key of the bitmap */ public static void evictBitmap(String key) { final ANImageLoader.ImageCache imageCache = ANImageLoader.getInstance().getImageCache(); if (imageCache != null && key != null) { imageCache.evictBitmap(key); } } /** * Method to clear LruCache */ public static void evictAllBitmap() { final ANImageLoader.ImageCache imageCache = ANImageLoader.getInstance().getImageCache(); if (imageCache != null) { imageCache.evictAllBitmap(); } } /** * Method to set userAgent globally * * @param userAgent The userAgent */ public static void setUserAgent(String userAgent) { InternalNetworking.setUserAgent(userAgent); } /** * Method to get currentBandwidth * * @return currentBandwidth */ public static int getCurrentBandwidth() { return ConnectionClassManager.getInstance().getCurrentBandwidth(); } /** * Method to get currentConnectionQuality * * @return currentConnectionQuality */ public static ConnectionQuality getCurrentConnectionQuality() { return ConnectionClassManager.getInstance().getCurrentConnectionQuality(); } /** * Method to set ParserFactory * * @param parserFactory The ParserFactory */ public static void setParserFactory(Parser.Factory parserFactory) { ParseUtil.setParserFactory(parserFactory); } /** * Method to find if the request is running or not * * @param tag The tag with which request running status is to be checked * @return The request is running or not */ public static boolean isRequestRunning(Object tag) { return ANRequestQueue.getInstance().isRequestRunning(tag); } /** * Shuts AndroidNetworking down */ public static void shutDown() { Core.shutDown(); evictAllBitmap(); ConnectionClassManager.getInstance().removeListener(); ConnectionClassManager.shutDown(); ParseUtil.shutDown(); } } ================================================ FILE: android-networking/src/main/java/com/androidnetworking/cache/LruBitmapCache.java ================================================ /* * Copyright (C) 2016 Amit Shekhar * Copyright (C) 2011 Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.androidnetworking.cache; import android.graphics.Bitmap; import com.androidnetworking.internal.ANImageLoader; /** * Created by amitshekhar on 24/03/16. */ public class LruBitmapCache extends LruCache implements ANImageLoader.ImageCache { public LruBitmapCache(int maxSize) { super(maxSize); } @Override protected int sizeOf(String key, Bitmap value) { return value.getRowBytes() * value.getHeight(); } @Override public Bitmap getBitmap(String key) { return get(key); } @Override public void evictBitmap(String key) { remove(key); } @Override public void evictAllBitmap() { evictAll(); } @Override public void putBitmap(String url, Bitmap bitmap) { put(url, bitmap); } } ================================================ FILE: android-networking/src/main/java/com/androidnetworking/cache/LruCache.java ================================================ /* * Copyright (C) 2016 Amit Shekhar * Copyright (C) 2011 Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.androidnetworking.cache; import android.annotation.SuppressLint; import java.util.LinkedHashMap; import java.util.Map; /** * Created by amitshekhar on 28/05/16. */ public class LruCache { private final LinkedHashMap map; private int size; private int maxSize; private int putCount; private int createCount; private int evictionCount; private int hitCount; private int missCount; public LruCache(int maxSize) { if (maxSize <= 0) { throw new IllegalArgumentException("maxSize <= 0"); } this.maxSize = maxSize; this.map = new LinkedHashMap(0, 0.75f, true); } public void resize(int maxSize) { if (maxSize <= 0) { throw new IllegalArgumentException("maxSize <= 0"); } synchronized (this) { this.maxSize = maxSize; } trimToSize(maxSize); } public final V get(K key) { if (key == null) { throw new NullPointerException("key == null"); } V mapValue; synchronized (this) { mapValue = map.get(key); if (mapValue != null) { hitCount++; return mapValue; } missCount++; } V createdValue = create(key); if (createdValue == null) { return null; } synchronized (this) { createCount++; mapValue = map.put(key, createdValue); if (mapValue != null) { // There was a conflict so undo that last put map.put(key, mapValue); } else { size += safeSizeOf(key, createdValue); } } if (mapValue != null) { entryRemoved(false, key, createdValue, mapValue); return mapValue; } else { trimToSize(maxSize); return createdValue; } } public final V put(K key, V value) { if (key == null || value == null) { throw new NullPointerException("key == null || value == null"); } V previous; synchronized (this) { putCount++; size += safeSizeOf(key, value); previous = map.put(key, value); if (previous != null) { size -= safeSizeOf(key, previous); } } if (previous != null) { entryRemoved(false, key, previous, value); } trimToSize(maxSize); return previous; } public void trimToSize(int maxSize) { while (true) { K key; V value; synchronized (this) { if (size < 0 || (map.isEmpty() && size != 0)) { throw new IllegalStateException(getClass().getName() + ".sizeOf() is reporting inconsistent results!"); } if (size <= maxSize || map.isEmpty()) { break; } Map.Entry toEvict = map.entrySet().iterator().next(); key = toEvict.getKey(); value = toEvict.getValue(); map.remove(key); size -= safeSizeOf(key, value); evictionCount++; } entryRemoved(true, key, value, null); } } public final V remove(K key) { if (key == null) { throw new NullPointerException("key == null"); } V previous; synchronized (this) { previous = map.remove(key); if (previous != null) { size -= safeSizeOf(key, previous); } } if (previous != null) { entryRemoved(false, key, previous, null); } return previous; } protected void entryRemoved(boolean evicted, K key, V oldValue, V newValue) { } protected V create(K key) { return null; } private int safeSizeOf(K key, V value) { int result = sizeOf(key, value); if (result < 0) { throw new IllegalStateException("Negative size: " + key + "=" + value); } return result; } protected int sizeOf(K key, V value) { return 1; } public final void evictAll() { trimToSize(-1); } public synchronized final int size() { return size; } public synchronized final int maxSize() { return maxSize; } public synchronized final int hitCount() { return hitCount; } public synchronized final int missCount() { return missCount; } public synchronized final int createCount() { return createCount; } public synchronized final int putCount() { return putCount; } public synchronized final int evictionCount() { return evictionCount; } public synchronized final Map snapshot() { return new LinkedHashMap(map); } @SuppressLint("DefaultLocale") @Override public synchronized final String toString() { int accesses = hitCount + missCount; int hitPercent = accesses != 0 ? (100 * hitCount / accesses) : 0; return String.format("LruCache[maxSize=%d,hits=%d,misses=%d,hitRate=%d%%]", maxSize, hitCount, missCount, hitPercent); } } ================================================ FILE: android-networking/src/main/java/com/androidnetworking/common/ANConstants.java ================================================ /* * Copyright (C) 2016 Amit Shekhar * Copyright (C) 2011 Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.androidnetworking.common; /** * Created by amitshekhar on 29/03/16. */ public final class ANConstants { public static final int MAX_CACHE_SIZE = 10 * 1024 * 1024; public static final int UPDATE = 0x01; public static final String CACHE_DIR_NAME = "cache_an"; public static final String CONNECTION_ERROR = "connectionError"; public static final String RESPONSE_FROM_SERVER_ERROR = "responseFromServerError"; public static final String REQUEST_CANCELLED_ERROR = "requestCancelledError"; public static final String PARSE_ERROR = "parseError"; public static final String PREFETCH = "prefetch"; public static final String FAST_ANDROID_NETWORKING = "FastAndroidNetworking"; public static final String USER_AGENT = "User-Agent"; public static final String SUCCESS = "success"; public static final String OPTIONS = "OPTIONS"; } ================================================ FILE: android-networking/src/main/java/com/androidnetworking/common/ANRequest.java ================================================ /* * Copyright (C) 2016 Amit Shekhar * Copyright (C) 2011 Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.androidnetworking.common; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.widget.ImageView; import com.androidnetworking.core.Core; import com.androidnetworking.error.ANError; import com.androidnetworking.interfaces.AnalyticsListener; import com.androidnetworking.interfaces.BitmapRequestListener; import com.androidnetworking.interfaces.DownloadListener; import com.androidnetworking.interfaces.DownloadProgressListener; import com.androidnetworking.interfaces.JSONArrayRequestListener; import com.androidnetworking.interfaces.JSONObjectRequestListener; import com.androidnetworking.interfaces.OkHttpResponseAndBitmapRequestListener; import com.androidnetworking.interfaces.OkHttpResponseAndJSONArrayRequestListener; import com.androidnetworking.interfaces.OkHttpResponseAndJSONObjectRequestListener; import com.androidnetworking.interfaces.OkHttpResponseAndParsedRequestListener; import com.androidnetworking.interfaces.OkHttpResponseAndStringRequestListener; import com.androidnetworking.interfaces.OkHttpResponseListener; import com.androidnetworking.interfaces.ParsedRequestListener; import com.androidnetworking.interfaces.StringRequestListener; import com.androidnetworking.interfaces.UploadProgressListener; import com.androidnetworking.internal.ANRequestQueue; import com.androidnetworking.internal.SynchronousCall; import com.androidnetworking.model.MultipartFileBody; import com.androidnetworking.model.MultipartStringBody; import com.androidnetworking.utils.ParseUtil; import com.androidnetworking.utils.Utils; import com.google.gson.internal.$Gson$Types; import com.google.gson.reflect.TypeToken; import org.json.JSONArray; import org.json.JSONObject; import java.io.File; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.Executor; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import okhttp3.CacheControl; import okhttp3.Call; import okhttp3.FormBody; import okhttp3.Headers; import okhttp3.HttpUrl; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.OkHttpClient; import okhttp3.RequestBody; import okhttp3.Response; import okio.Okio; /** * Created by amitshekhar on 26/03/16. */ @SuppressWarnings({"unchecked", "unused"}) public class ANRequest { private final static String TAG = ANRequest.class.getSimpleName(); private int mMethod; private Priority mPriority; private int mRequestType; private String mUrl; private int sequenceNumber; private Object mTag; private ResponseType mResponseType; private HashMap> mHeadersMap = new HashMap<>(); private HashMap mBodyParameterMap = new HashMap<>(); private HashMap mUrlEncodedFormBodyParameterMap = new HashMap<>(); private HashMap mMultiPartParameterMap = new HashMap<>(); private HashMap> mQueryParameterMap = new HashMap<>(); private HashMap mPathParameterMap = new HashMap<>(); private HashMap> mMultiPartFileMap = new HashMap<>(); private String mDirPath; private String mFileName; private String mApplicationJsonString = null; private String mStringBody = null; private byte[] mByte = null; private File mFile = null; private static final MediaType JSON_MEDIA_TYPE = MediaType.parse("application/json; charset=utf-8"); private static final MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("text/x-markdown; charset=utf-8"); private MediaType customMediaType = null; private static final Object sDecodeLock = new Object(); private Future future; private Call call; private int mProgress; private boolean isCancelled; private boolean isDelivered; private boolean isRunning; private int mPercentageThresholdForCancelling = 0; private JSONArrayRequestListener mJSONArrayRequestListener; private JSONObjectRequestListener mJSONObjectRequestListener; private StringRequestListener mStringRequestListener; private OkHttpResponseListener mOkHttpResponseListener; private BitmapRequestListener mBitmapRequestListener; private ParsedRequestListener mParsedRequestListener; private OkHttpResponseAndJSONObjectRequestListener mOkHttpResponseAndJSONObjectRequestListener; private OkHttpResponseAndJSONArrayRequestListener mOkHttpResponseAndJSONArrayRequestListener; private OkHttpResponseAndStringRequestListener mOkHttpResponseAndStringRequestListener; private OkHttpResponseAndBitmapRequestListener mOkHttpResponseAndBitmapRequestListener; private OkHttpResponseAndParsedRequestListener mOkHttpResponseAndParsedRequestListener; private DownloadProgressListener mDownloadProgressListener; private UploadProgressListener mUploadProgressListener; private DownloadListener mDownloadListener; private AnalyticsListener mAnalyticsListener; private Bitmap.Config mDecodeConfig; private int mMaxWidth; private int mMaxHeight; private ImageView.ScaleType mScaleType; private CacheControl mCacheControl = null; private Executor mExecutor = null; private OkHttpClient mOkHttpClient = null; private String mUserAgent = null; private Type mType = null; public ANRequest(GetRequestBuilder builder) { this.mRequestType = RequestType.SIMPLE; this.mMethod = builder.mMethod; this.mPriority = builder.mPriority; this.mUrl = builder.mUrl; this.mTag = builder.mTag; this.mHeadersMap = builder.mHeadersMap; this.mDecodeConfig = builder.mDecodeConfig; this.mMaxHeight = builder.mMaxHeight; this.mMaxWidth = builder.mMaxWidth; this.mScaleType = builder.mScaleType; this.mQueryParameterMap = builder.mQueryParameterMap; this.mPathParameterMap = builder.mPathParameterMap; this.mCacheControl = builder.mCacheControl; this.mExecutor = builder.mExecutor; this.mOkHttpClient = builder.mOkHttpClient; this.mUserAgent = builder.mUserAgent; } public ANRequest(PostRequestBuilder builder) { this.mRequestType = RequestType.SIMPLE; this.mMethod = builder.mMethod; this.mPriority = builder.mPriority; this.mUrl = builder.mUrl; this.mTag = builder.mTag; this.mHeadersMap = builder.mHeadersMap; this.mBodyParameterMap = builder.mBodyParameterMap; this.mUrlEncodedFormBodyParameterMap = builder.mUrlEncodedFormBodyParameterMap; this.mQueryParameterMap = builder.mQueryParameterMap; this.mPathParameterMap = builder.mPathParameterMap; this.mApplicationJsonString = builder.mApplicationJsonString; this.mStringBody = builder.mStringBody; this.mFile = builder.mFile; this.mByte = builder.mByte; this.mCacheControl = builder.mCacheControl; this.mExecutor = builder.mExecutor; this.mOkHttpClient = builder.mOkHttpClient; this.mUserAgent = builder.mUserAgent; if (builder.mCustomContentType != null) { this.customMediaType = MediaType.parse(builder.mCustomContentType); } } public ANRequest(DownloadBuilder builder) { this.mRequestType = RequestType.DOWNLOAD; this.mMethod = Method.GET; this.mPriority = builder.mPriority; this.mUrl = builder.mUrl; this.mTag = builder.mTag; this.mDirPath = builder.mDirPath; this.mFileName = builder.mFileName; this.mHeadersMap = builder.mHeadersMap; this.mQueryParameterMap = builder.mQueryParameterMap; this.mPathParameterMap = builder.mPathParameterMap; this.mCacheControl = builder.mCacheControl; this.mPercentageThresholdForCancelling = builder.mPercentageThresholdForCancelling; this.mExecutor = builder.mExecutor; this.mOkHttpClient = builder.mOkHttpClient; this.mUserAgent = builder.mUserAgent; } public ANRequest(MultiPartBuilder builder) { this.mRequestType = RequestType.MULTIPART; this.mMethod = Method.POST; this.mPriority = builder.mPriority; this.mUrl = builder.mUrl; this.mTag = builder.mTag; this.mHeadersMap = builder.mHeadersMap; this.mQueryParameterMap = builder.mQueryParameterMap; this.mPathParameterMap = builder.mPathParameterMap; this.mMultiPartParameterMap = builder.mMultiPartParameterMap; this.mMultiPartFileMap = builder.mMultiPartFileMap; this.mCacheControl = builder.mCacheControl; this.mPercentageThresholdForCancelling = builder.mPercentageThresholdForCancelling; this.mExecutor = builder.mExecutor; this.mOkHttpClient = builder.mOkHttpClient; this.mUserAgent = builder.mUserAgent; if (builder.mCustomContentType != null) { this.customMediaType = MediaType.parse(builder.mCustomContentType); } } public void getAsJSONObject(JSONObjectRequestListener requestListener) { this.mResponseType = ResponseType.JSON_OBJECT; this.mJSONObjectRequestListener = requestListener; ANRequestQueue.getInstance().addRequest(this); } public void getAsJSONArray(JSONArrayRequestListener requestListener) { this.mResponseType = ResponseType.JSON_ARRAY; this.mJSONArrayRequestListener = requestListener; ANRequestQueue.getInstance().addRequest(this); } public void getAsString(StringRequestListener requestListener) { this.mResponseType = ResponseType.STRING; this.mStringRequestListener = requestListener; ANRequestQueue.getInstance().addRequest(this); } public void getAsOkHttpResponse(OkHttpResponseListener requestListener) { this.mResponseType = ResponseType.OK_HTTP_RESPONSE; this.mOkHttpResponseListener = requestListener; ANRequestQueue.getInstance().addRequest(this); } public void getAsBitmap(BitmapRequestListener requestListener) { this.mResponseType = ResponseType.BITMAP; this.mBitmapRequestListener = requestListener; ANRequestQueue.getInstance().addRequest(this); } public void getAsParsed(TypeToken typeToken, ParsedRequestListener parsedRequestListener) { this.mType = typeToken.getType(); this.mResponseType = ResponseType.PARSED; this.mParsedRequestListener = parsedRequestListener; ANRequestQueue.getInstance().addRequest(this); } public void getAsObject(Class objectClass, ParsedRequestListener parsedRequestListener) { this.mType = objectClass; this.mResponseType = ResponseType.PARSED; this.mParsedRequestListener = parsedRequestListener; ANRequestQueue.getInstance().addRequest(this); } public void getAsObjectList(Class objectClass, ParsedRequestListener parsedRequestListener) { this.mType = $Gson$Types.newParameterizedTypeWithOwner(null, List.class, objectClass); this.mResponseType = ResponseType.PARSED; this.mParsedRequestListener = parsedRequestListener; ANRequestQueue.getInstance().addRequest(this); } public void getAsOkHttpResponseAndJSONObject(OkHttpResponseAndJSONObjectRequestListener requestListener) { this.mResponseType = ResponseType.JSON_OBJECT; this.mOkHttpResponseAndJSONObjectRequestListener = requestListener; ANRequestQueue.getInstance().addRequest(this); } public void getAsOkHttpResponseAndJSONArray(OkHttpResponseAndJSONArrayRequestListener requestListener) { this.mResponseType = ResponseType.JSON_ARRAY; this.mOkHttpResponseAndJSONArrayRequestListener = requestListener; ANRequestQueue.getInstance().addRequest(this); } public void getAsOkHttpResponseAndString(OkHttpResponseAndStringRequestListener requestListener) { this.mResponseType = ResponseType.STRING; this.mOkHttpResponseAndStringRequestListener = requestListener; ANRequestQueue.getInstance().addRequest(this); } public void getAsOkHttpResponseAndBitmap(OkHttpResponseAndBitmapRequestListener requestListener) { this.mResponseType = ResponseType.BITMAP; this.mOkHttpResponseAndBitmapRequestListener = requestListener; ANRequestQueue.getInstance().addRequest(this); } public void getAsOkHttpResponseAndParsed(TypeToken typeToken, OkHttpResponseAndParsedRequestListener parsedRequestListener) { this.mType = typeToken.getType(); this.mResponseType = ResponseType.PARSED; this.mOkHttpResponseAndParsedRequestListener = parsedRequestListener; ANRequestQueue.getInstance().addRequest(this); } public void getAsOkHttpResponseAndObject(Class objectClass, OkHttpResponseAndParsedRequestListener parsedRequestListener) { this.mType = objectClass; this.mResponseType = ResponseType.PARSED; this.mOkHttpResponseAndParsedRequestListener = parsedRequestListener; ANRequestQueue.getInstance().addRequest(this); } public void getAsOkHttpResponseAndObjectList(Class objectClass, OkHttpResponseAndParsedRequestListener parsedRequestListener) { this.mType = $Gson$Types.newParameterizedTypeWithOwner(null, List.class, objectClass); this.mResponseType = ResponseType.PARSED; this.mOkHttpResponseAndParsedRequestListener = parsedRequestListener; ANRequestQueue.getInstance().addRequest(this); } public void startDownload(DownloadListener downloadListener) { this.mDownloadListener = downloadListener; ANRequestQueue.getInstance().addRequest(this); } public void prefetch() { this.mResponseType = ResponseType.PREFETCH; ANRequestQueue.getInstance().addRequest(this); } public ANResponse executeForJSONObject() { this.mResponseType = ResponseType.JSON_OBJECT; return SynchronousCall.execute(this); } public ANResponse executeForJSONArray() { this.mResponseType = ResponseType.JSON_ARRAY; return SynchronousCall.execute(this); } public ANResponse executeForString() { this.mResponseType = ResponseType.STRING; return SynchronousCall.execute(this); } public ANResponse executeForOkHttpResponse() { this.mResponseType = ResponseType.OK_HTTP_RESPONSE; return SynchronousCall.execute(this); } public ANResponse executeForBitmap() { this.mResponseType = ResponseType.BITMAP; return SynchronousCall.execute(this); } public ANResponse executeForParsed(TypeToken typeToken) { this.mType = typeToken.getType(); this.mResponseType = ResponseType.PARSED; return SynchronousCall.execute(this); } public ANResponse executeForObject(Class objectClass) { this.mType = objectClass; this.mResponseType = ResponseType.PARSED; return SynchronousCall.execute(this); } public ANResponse executeForObjectList(Class objectClass) { this.mType = $Gson$Types.newParameterizedTypeWithOwner(null, List.class, objectClass); this.mResponseType = ResponseType.PARSED; return SynchronousCall.execute(this); } public ANResponse executeForDownload() { return SynchronousCall.execute(this); } public T setDownloadProgressListener(DownloadProgressListener downloadProgressListener) { this.mDownloadProgressListener = downloadProgressListener; return (T) this; } public T setUploadProgressListener(UploadProgressListener uploadProgressListener) { this.mUploadProgressListener = uploadProgressListener; return (T) this; } public T setAnalyticsListener(AnalyticsListener analyticsListener) { this.mAnalyticsListener = analyticsListener; return (T) this; } public AnalyticsListener getAnalyticsListener() { return mAnalyticsListener; } public int getMethod() { return mMethod; } public Priority getPriority() { return mPriority; } public String getUrl() { String tempUrl = mUrl; for (HashMap.Entry entry : mPathParameterMap.entrySet()) { tempUrl = tempUrl.replace("{" + entry.getKey() + "}", String.valueOf(entry.getValue())); } HttpUrl.Builder urlBuilder = HttpUrl.parse(tempUrl).newBuilder(); if (mQueryParameterMap != null) { Set>> entries = mQueryParameterMap.entrySet(); for (Map.Entry> entry : entries) { String name = entry.getKey(); List list = entry.getValue(); if (list != null) { for (String value : list) { urlBuilder.addQueryParameter(name, value); } } } } return urlBuilder.build().toString(); } public int getSequenceNumber() { return sequenceNumber; } public void setSequenceNumber(int sequenceNumber) { this.sequenceNumber = sequenceNumber; } public void setProgress(int progress) { this.mProgress = progress; } public void setResponseAs(ResponseType responseType) { this.mResponseType = responseType; } public ResponseType getResponseAs() { return mResponseType; } public Object getTag() { return mTag; } public int getRequestType() { return mRequestType; } public OkHttpClient getOkHttpClient() { return mOkHttpClient; } public void setUserAgent(String userAgent) { this.mUserAgent = userAgent; } public String getUserAgent() { return mUserAgent; } public Type getType() { return mType; } public void setType(Type type) { this.mType = type; } public DownloadProgressListener getDownloadProgressListener() { return new DownloadProgressListener() { @Override public void onProgress(final long bytesDownloaded, final long totalBytes) { if (mDownloadProgressListener != null && !isCancelled) { mDownloadProgressListener.onProgress(bytesDownloaded, totalBytes); } } }; } public void updateDownloadCompletion() { isDelivered = true; if (mDownloadListener != null) { if (!isCancelled) { if (mExecutor != null) { mExecutor.execute(new Runnable() { @Override public void run() { if (mDownloadListener != null) { mDownloadListener.onDownloadComplete(); } finish(); } }); } else { Core.getInstance().getExecutorSupplier().forMainThreadTasks().execute(new Runnable() { @Override public void run() { if (mDownloadListener != null) { mDownloadListener.onDownloadComplete(); } finish(); } }); } } else { deliverError(new ANError()); finish(); } } else { finish(); } } public UploadProgressListener getUploadProgressListener() { return new UploadProgressListener() { @Override public void onProgress(final long bytesUploaded, final long totalBytes) { mProgress = (int) ((bytesUploaded * 100) / totalBytes); if (mUploadProgressListener != null && !isCancelled) { mUploadProgressListener.onProgress(bytesUploaded, totalBytes); } } }; } public String getDirPath() { return mDirPath; } public String getFileName() { return mFileName; } public CacheControl getCacheControl() { return mCacheControl; } public ImageView.ScaleType getScaleType() { return mScaleType; } public void cancel(boolean forceCancel) { try { if (forceCancel || mPercentageThresholdForCancelling == 0 || mProgress < mPercentageThresholdForCancelling) { isCancelled = true; isRunning = false; if (call != null) { call.cancel(); } if (future != null) { future.cancel(true); } if (!isDelivered) { deliverError(new ANError()); } } } catch (Exception e) { e.printStackTrace(); } } public boolean isCanceled() { return isCancelled; } public boolean isRunning() { return isRunning; } public void setRunning(boolean running) { isRunning = running; } public Call getCall() { return call; } public void setCall(Call call) { this.call = call; } public Future getFuture() { return future; } public void setFuture(Future future) { this.future = future; } public void destroy() { mJSONArrayRequestListener = null; mJSONObjectRequestListener = null; mStringRequestListener = null; mBitmapRequestListener = null; mParsedRequestListener = null; mDownloadProgressListener = null; mUploadProgressListener = null; mDownloadListener = null; mAnalyticsListener = null; } public void finish() { destroy(); ANRequestQueue.getInstance().finish(this); } public ANResponse parseResponse(Response response) { switch (mResponseType) { case JSON_ARRAY: try { JSONArray json = new JSONArray(Okio.buffer(response.body().source()).readUtf8()); return ANResponse.success(json); } catch (Exception e) { return ANResponse.failed(Utils.getErrorForParse(new ANError(e))); } case JSON_OBJECT: try { JSONObject json = new JSONObject(Okio.buffer(response.body() .source()).readUtf8()); return ANResponse.success(json); } catch (Exception e) { return ANResponse.failed(Utils.getErrorForParse(new ANError(e))); } case STRING: try { return ANResponse.success(Okio.buffer(response .body().source()).readUtf8()); } catch (Exception e) { return ANResponse.failed(Utils.getErrorForParse(new ANError(e))); } case BITMAP: synchronized (sDecodeLock) { try { return Utils.decodeBitmap(response, mMaxWidth, mMaxHeight, mDecodeConfig, mScaleType); } catch (Exception e) { return ANResponse.failed(Utils.getErrorForParse(new ANError(e))); } } case PARSED: try { return ANResponse.success(ParseUtil.getParserFactory() .responseBodyParser(mType).convert(response.body())); } catch (Exception e) { return ANResponse.failed(Utils.getErrorForParse(new ANError(e))); } case PREFETCH: try { Okio.buffer(response.body().source()).skip(Long.MAX_VALUE); return ANResponse.success(ANConstants.PREFETCH); } catch (Exception e) { return ANResponse.failed(Utils.getErrorForParse(new ANError(e))); } } return null; } public ANError parseNetworkError(ANError anError) { try { if (anError.getResponse() != null && anError.getResponse().body() != null && anError.getResponse().body().source() != null) { anError.setErrorBody(Okio.buffer(anError .getResponse().body().source()).readUtf8()); } } catch (Exception e) { e.printStackTrace(); } return anError; } public synchronized void deliverError(ANError anError) { try { if (!isDelivered) { if (isCancelled) { anError.setCancellationMessageInError(); anError.setErrorCode(0); } deliverErrorResponse(anError); } isDelivered = true; } catch (Exception e) { e.printStackTrace(); } } public void deliverResponse(final ANResponse response) { try { isDelivered = true; if (!isCancelled) { if (mExecutor != null) { mExecutor.execute(new Runnable() { @Override public void run() { deliverSuccessResponse(response); } }); } else { Core.getInstance().getExecutorSupplier().forMainThreadTasks().execute(new Runnable() { public void run() { deliverSuccessResponse(response); } }); } } else { ANError anError = new ANError(); anError.setCancellationMessageInError(); anError.setErrorCode(0); deliverErrorResponse(anError); finish(); } } catch (Exception e) { e.printStackTrace(); } } private void deliverSuccessResponse(ANResponse response) { if (mJSONObjectRequestListener != null) { mJSONObjectRequestListener.onResponse((JSONObject) response.getResult()); } else if (mJSONArrayRequestListener != null) { mJSONArrayRequestListener.onResponse((JSONArray) response.getResult()); } else if (mStringRequestListener != null) { mStringRequestListener.onResponse((String) response.getResult()); } else if (mBitmapRequestListener != null) { mBitmapRequestListener.onResponse((Bitmap) response.getResult()); } else if (mParsedRequestListener != null) { mParsedRequestListener.onResponse(response.getResult()); } else if (mOkHttpResponseAndJSONObjectRequestListener != null) { mOkHttpResponseAndJSONObjectRequestListener.onResponse(response.getOkHttpResponse(), (JSONObject) response.getResult()); } else if (mOkHttpResponseAndJSONArrayRequestListener != null) { mOkHttpResponseAndJSONArrayRequestListener.onResponse(response.getOkHttpResponse(), (JSONArray) response.getResult()); } else if (mOkHttpResponseAndStringRequestListener != null) { mOkHttpResponseAndStringRequestListener.onResponse(response.getOkHttpResponse(), (String) response.getResult()); } else if (mOkHttpResponseAndBitmapRequestListener != null) { mOkHttpResponseAndBitmapRequestListener.onResponse(response.getOkHttpResponse(), (Bitmap) response.getResult()); } else if (mOkHttpResponseAndParsedRequestListener != null) { mOkHttpResponseAndParsedRequestListener.onResponse(response.getOkHttpResponse(), response.getResult()); } finish(); } private void deliverErrorResponse(ANError anError) { if (mJSONObjectRequestListener != null) { mJSONObjectRequestListener.onError(anError); } else if (mJSONArrayRequestListener != null) { mJSONArrayRequestListener.onError(anError); } else if (mStringRequestListener != null) { mStringRequestListener.onError(anError); } else if (mBitmapRequestListener != null) { mBitmapRequestListener.onError(anError); } else if (mParsedRequestListener != null) { mParsedRequestListener.onError(anError); } else if (mOkHttpResponseListener != null) { mOkHttpResponseListener.onError(anError); } else if (mOkHttpResponseAndJSONObjectRequestListener != null) { mOkHttpResponseAndJSONObjectRequestListener.onError(anError); } else if (mOkHttpResponseAndJSONArrayRequestListener != null) { mOkHttpResponseAndJSONArrayRequestListener.onError(anError); } else if (mOkHttpResponseAndStringRequestListener != null) { mOkHttpResponseAndStringRequestListener.onError(anError); } else if (mOkHttpResponseAndBitmapRequestListener != null) { mOkHttpResponseAndBitmapRequestListener.onError(anError); } else if (mOkHttpResponseAndParsedRequestListener != null) { mOkHttpResponseAndParsedRequestListener.onError(anError); } else if (mDownloadListener != null) { mDownloadListener.onError(anError); } } public void deliverOkHttpResponse(final Response response) { try { isDelivered = true; if (!isCancelled) { if (mExecutor != null) { mExecutor.execute(new Runnable() { @Override public void run() { if (mOkHttpResponseListener != null) { mOkHttpResponseListener.onResponse(response); } finish(); } }); } else { Core.getInstance().getExecutorSupplier().forMainThreadTasks().execute(new Runnable() { public void run() { if (mOkHttpResponseListener != null) { mOkHttpResponseListener.onResponse(response); } finish(); } }); } } else { ANError anError = new ANError(); anError.setCancellationMessageInError(); anError.setErrorCode(0); if (mOkHttpResponseListener != null) { mOkHttpResponseListener.onError(anError); } finish(); } } catch (Exception e) { e.printStackTrace(); } } public RequestBody getRequestBody() { if (mApplicationJsonString != null) { if (customMediaType != null) { return RequestBody.create(customMediaType, mApplicationJsonString); } return RequestBody.create(JSON_MEDIA_TYPE, mApplicationJsonString); } else if (mStringBody != null) { if (customMediaType != null) { return RequestBody.create(customMediaType, mStringBody); } return RequestBody.create(MEDIA_TYPE_MARKDOWN, mStringBody); } else if (mFile != null) { if (customMediaType != null) { return RequestBody.create(customMediaType, mFile); } return RequestBody.create(MEDIA_TYPE_MARKDOWN, mFile); } else if (mByte != null) { if (customMediaType != null) { return RequestBody.create(customMediaType, mByte); } return RequestBody.create(MEDIA_TYPE_MARKDOWN, mByte); } else { FormBody.Builder builder = new FormBody.Builder(); try { for (HashMap.Entry entry : mBodyParameterMap.entrySet()) { builder.add(entry.getKey(), entry.getValue()); } for (HashMap.Entry entry : mUrlEncodedFormBodyParameterMap.entrySet()) { builder.addEncoded(entry.getKey(), entry.getValue()); } } catch (Exception e) { e.printStackTrace(); } return builder.build(); } } public RequestBody getMultiPartRequestBody() { MultipartBody.Builder builder = new MultipartBody.Builder() .setType((customMediaType == null) ? MultipartBody.FORM : customMediaType); try { for (HashMap.Entry entry : mMultiPartParameterMap.entrySet()) { MultipartStringBody stringBody = entry.getValue(); MediaType mediaType = null; if (stringBody.contentType != null) { mediaType = MediaType.parse(stringBody.contentType); } builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + entry.getKey() + "\""), RequestBody.create(mediaType, stringBody.value)); } for (HashMap.Entry> entry : mMultiPartFileMap.entrySet()) { List fileBodies = entry.getValue(); for (MultipartFileBody fileBody : fileBodies) { String fileName = fileBody.file.getName(); MediaType mediaType; if (fileBody.contentType != null) { mediaType = MediaType.parse(fileBody.contentType); } else { mediaType = MediaType.parse(Utils.getMimeType(fileName)); } RequestBody requestBody = RequestBody.create(mediaType, fileBody.file); builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + entry.getKey() + "\"; filename=\"" + fileName + "\""), requestBody); } } } catch (Exception e) { e.printStackTrace(); } return builder.build(); } public Headers getHeaders() { Headers.Builder builder = new Headers.Builder(); try { if (mHeadersMap != null) { Set>> entries = mHeadersMap.entrySet(); for (Map.Entry> entry : entries) { String name = entry.getKey(); List list = entry.getValue(); if (list != null) { for (String value : list) { builder.add(name, value); } } } } } catch (Exception e) { e.printStackTrace(); } return builder.build(); } public static class HeadRequestBuilder extends GetRequestBuilder { public HeadRequestBuilder(String url) { super(url, Method.HEAD); } } public static class OptionsRequestBuilder extends GetRequestBuilder { public OptionsRequestBuilder(String url) { super(url, Method.OPTIONS); } } public static class GetRequestBuilder implements RequestBuilder { private Priority mPriority = Priority.MEDIUM; private int mMethod = Method.GET; private String mUrl; private Object mTag; private Bitmap.Config mDecodeConfig; private BitmapFactory.Options mBitmapOptions; private int mMaxWidth; private int mMaxHeight; private ImageView.ScaleType mScaleType; private HashMap> mHeadersMap = new HashMap<>(); private HashMap> mQueryParameterMap = new HashMap<>(); private HashMap mPathParameterMap = new HashMap<>(); private CacheControl mCacheControl; private Executor mExecutor; private OkHttpClient mOkHttpClient; private String mUserAgent; public GetRequestBuilder(String url) { this.mUrl = url; this.mMethod = Method.GET; } public GetRequestBuilder(String url, int method) { this.mUrl = url; this.mMethod = method; } @Override public T setPriority(Priority priority) { mPriority = priority; return (T) this; } @Override public T setTag(Object tag) { mTag = tag; return (T) this; } @Override public T addQueryParameter(String key, String value) { List list = mQueryParameterMap.get(key); if (list == null) { list = new ArrayList<>(); mQueryParameterMap.put(key, list); } if (!list.contains(value)) { list.add(value); } return (T) this; } @Override public T addQueryParameter(Map queryParameterMap) { if (queryParameterMap != null) { for (HashMap.Entry entry : queryParameterMap.entrySet()) { addQueryParameter(entry.getKey(), entry.getValue()); } } return (T) this; } @Override public T addQueryParameter(Object object) { if (object != null) { return addQueryParameter(ParseUtil .getParserFactory() .getStringMap(object)); } return (T) this; } @Override public T addPathParameter(String key, String value) { mPathParameterMap.put(key, value); return (T) this; } @Override public T addPathParameter(Map pathParameterMap) { if (pathParameterMap != null) { mPathParameterMap.putAll(pathParameterMap); } return (T) this; } @Override public T addPathParameter(Object object) { if (object != null) { mPathParameterMap.putAll(ParseUtil .getParserFactory() .getStringMap(object)); } return (T) this; } @Override public T addHeaders(String key, String value) { List list = mHeadersMap.get(key); if (list == null) { list = new ArrayList<>(); mHeadersMap.put(key, list); } if (!list.contains(value)) { list.add(value); } return (T) this; } @Override public T addHeaders(Map headerMap) { if (headerMap != null) { for (HashMap.Entry entry : headerMap.entrySet()) { addHeaders(entry.getKey(), entry.getValue()); } } return (T) this; } @Override public T addHeaders(Object object) { if (object != null) { return addHeaders(ParseUtil .getParserFactory() .getStringMap(object)); } return (T) this; } @Override public T doNotCacheResponse() { mCacheControl = new CacheControl.Builder().noStore().build(); return (T) this; } @Override public T getResponseOnlyIfCached() { mCacheControl = CacheControl.FORCE_CACHE; return (T) this; } @Override public T getResponseOnlyFromNetwork() { mCacheControl = CacheControl.FORCE_NETWORK; return (T) this; } @Override public T setMaxAgeCacheControl(int maxAge, TimeUnit timeUnit) { mCacheControl = new CacheControl.Builder().maxAge(maxAge, timeUnit).build(); return (T) this; } @Override public T setMaxStaleCacheControl(int maxStale, TimeUnit timeUnit) { mCacheControl = new CacheControl.Builder().maxStale(maxStale, timeUnit).build(); return (T) this; } @Override public T setExecutor(Executor executor) { mExecutor = executor; return (T) this; } @Override public T setOkHttpClient(OkHttpClient okHttpClient) { mOkHttpClient = okHttpClient; return (T) this; } @Override public T setUserAgent(String userAgent) { mUserAgent = userAgent; return (T) this; } public T setBitmapConfig(Bitmap.Config bitmapConfig) { mDecodeConfig = bitmapConfig; return (T) this; } public T setBitmapOptions(BitmapFactory.Options bitmapOptions) { mBitmapOptions = bitmapOptions; return (T) this; } public T setBitmapMaxHeight(int maxHeight) { mMaxHeight = maxHeight; return (T) this; } public T setBitmapMaxWidth(int maxWidth) { mMaxWidth = maxWidth; return (T) this; } public T setImageScaleType(ImageView.ScaleType imageScaleType) { mScaleType = imageScaleType; return (T) this; } public ANRequest build() { return new ANRequest(this); } } public static class PutRequestBuilder extends PostRequestBuilder { public PutRequestBuilder(String url) { super(url, Method.PUT); } } public static class DeleteRequestBuilder extends PostRequestBuilder { public DeleteRequestBuilder(String url) { super(url, Method.DELETE); } } public static class PatchRequestBuilder extends PostRequestBuilder { public PatchRequestBuilder(String url) { super(url, Method.PATCH); } } public static class DynamicRequestBuilder extends PostRequestBuilder { public DynamicRequestBuilder(String url, int method) { super(url, method); } } public static class PostRequestBuilder implements RequestBuilder { private Priority mPriority = Priority.MEDIUM; private int mMethod = Method.POST; private String mUrl; private Object mTag; private String mApplicationJsonString = null; private String mStringBody = null; private byte[] mByte = null; private File mFile = null; private HashMap> mHeadersMap = new HashMap<>(); private HashMap mBodyParameterMap = new HashMap<>(); private HashMap mUrlEncodedFormBodyParameterMap = new HashMap<>(); private HashMap> mQueryParameterMap = new HashMap<>(); private HashMap mPathParameterMap = new HashMap<>(); private CacheControl mCacheControl; private Executor mExecutor; private OkHttpClient mOkHttpClient; private String mUserAgent; private String mCustomContentType; public PostRequestBuilder(String url) { this.mUrl = url; this.mMethod = Method.POST; } public PostRequestBuilder(String url, int method) { this.mUrl = url; this.mMethod = method; } @Override public T setPriority(Priority priority) { mPriority = priority; return (T) this; } @Override public T setTag(Object tag) { mTag = tag; return (T) this; } @Override public T addQueryParameter(String key, String value) { List list = mQueryParameterMap.get(key); if (list == null) { list = new ArrayList<>(); mQueryParameterMap.put(key, list); } if (!list.contains(value)) { list.add(value); } return (T) this; } @Override public T addQueryParameter(Map queryParameterMap) { if (queryParameterMap != null) { for (HashMap.Entry entry : queryParameterMap.entrySet()) { addQueryParameter(entry.getKey(), entry.getValue()); } } return (T) this; } @Override public T addQueryParameter(Object object) { if (object != null) { return addQueryParameter(ParseUtil .getParserFactory() .getStringMap(object)); } return (T) this; } @Override public T addPathParameter(String key, String value) { mPathParameterMap.put(key, value); return (T) this; } @Override public T addPathParameter(Map pathParameterMap) { if (pathParameterMap != null) { mPathParameterMap.putAll(pathParameterMap); } return (T) this; } @Override public T addPathParameter(Object object) { if (object != null) { mPathParameterMap.putAll(ParseUtil .getParserFactory() .getStringMap(object)); } return (T) this; } @Override public T addHeaders(String key, String value) { List list = mHeadersMap.get(key); if (list == null) { list = new ArrayList<>(); mHeadersMap.put(key, list); } if (!list.contains(value)) { list.add(value); } return (T) this; } @Override public T addHeaders(Map headerMap) { if (headerMap != null) { for (HashMap.Entry entry : headerMap.entrySet()) { addHeaders(entry.getKey(), entry.getValue()); } } return (T) this; } @Override public T addHeaders(Object object) { if (object != null) { return addHeaders(ParseUtil .getParserFactory() .getStringMap(object)); } return (T) this; } @Override public T doNotCacheResponse() { mCacheControl = new CacheControl.Builder().noStore().build(); return (T) this; } @Override public T getResponseOnlyIfCached() { mCacheControl = CacheControl.FORCE_CACHE; return (T) this; } @Override public T getResponseOnlyFromNetwork() { mCacheControl = CacheControl.FORCE_NETWORK; return (T) this; } @Override public T setMaxAgeCacheControl(int maxAge, TimeUnit timeUnit) { mCacheControl = new CacheControl.Builder().maxAge(maxAge, timeUnit).build(); return (T) this; } @Override public T setMaxStaleCacheControl(int maxStale, TimeUnit timeUnit) { mCacheControl = new CacheControl.Builder().maxStale(maxStale, timeUnit).build(); return (T) this; } @Override public T setExecutor(Executor executor) { mExecutor = executor; return (T) this; } @Override public T setOkHttpClient(OkHttpClient okHttpClient) { mOkHttpClient = okHttpClient; return (T) this; } @Override public T setUserAgent(String userAgent) { mUserAgent = userAgent; return (T) this; } public T addBodyParameter(String key, String value) { mBodyParameterMap.put(key, value); return (T) this; } public T addBodyParameter(Map bodyParameterMap) { if (bodyParameterMap != null) { mBodyParameterMap.putAll(bodyParameterMap); } return (T) this; } public T addBodyParameter(Object object) { if (object != null) { mBodyParameterMap.putAll(ParseUtil .getParserFactory() .getStringMap(object)); } return (T) this; } public T addUrlEncodeFormBodyParameter(String key, String value) { mUrlEncodedFormBodyParameterMap.put(key, value); return (T) this; } public T addUrlEncodeFormBodyParameter(Map bodyParameterMap) { if (bodyParameterMap != null) { mUrlEncodedFormBodyParameterMap.putAll(bodyParameterMap); } return (T) this; } public T addUrlEncodeFormBodyParameter(Object object) { if (object != null) { mUrlEncodedFormBodyParameterMap.putAll(ParseUtil .getParserFactory() .getStringMap(object)); } return (T) this; } public T addApplicationJsonBody(Object object) { if (object != null) { mApplicationJsonString = ParseUtil .getParserFactory() .getString(object); } return (T) this; } public T addJSONObjectBody(JSONObject jsonObject) { if (jsonObject != null) { mApplicationJsonString = jsonObject.toString(); } return (T) this; } public T addJSONArrayBody(JSONArray jsonArray) { if (jsonArray != null) { mApplicationJsonString = jsonArray.toString(); } return (T) this; } public T addStringBody(String stringBody) { mStringBody = stringBody; return (T) this; } public T addFileBody(File file) { mFile = file; return (T) this; } public T addByteBody(byte[] bytes) { mByte = bytes; return (T) this; } public T setContentType(String contentType) { mCustomContentType = contentType; return (T) this; } public ANRequest build() { return new ANRequest(this); } } public static class DownloadBuilder implements RequestBuilder { private Priority mPriority = Priority.MEDIUM; private String mUrl; private Object mTag; private HashMap> mHeadersMap = new HashMap<>(); private HashMap> mQueryParameterMap = new HashMap<>(); private HashMap mPathParameterMap = new HashMap<>(); private String mDirPath; private String mFileName; private CacheControl mCacheControl; private int mPercentageThresholdForCancelling = 0; private Executor mExecutor; private OkHttpClient mOkHttpClient; private String mUserAgent; public DownloadBuilder(String url, String dirPath, String fileName) { this.mUrl = url; this.mDirPath = dirPath; this.mFileName = fileName; } @Override public T setPriority(Priority priority) { mPriority = priority; return (T) this; } @Override public T setTag(Object tag) { mTag = tag; return (T) this; } @Override public T addHeaders(String key, String value) { List list = mHeadersMap.get(key); if (list == null) { list = new ArrayList<>(); mHeadersMap.put(key, list); } if (!list.contains(value)) { list.add(value); } return (T) this; } @Override public T addHeaders(Map headerMap) { if (headerMap != null) { for (HashMap.Entry entry : headerMap.entrySet()) { addHeaders(entry.getKey(), entry.getValue()); } } return (T) this; } @Override public T addHeaders(Object object) { if (object != null) { return addHeaders(ParseUtil .getParserFactory() .getStringMap(object)); } return (T) this; } @Override public T addQueryParameter(String key, String value) { List list = mQueryParameterMap.get(key); if (list == null) { list = new ArrayList<>(); mQueryParameterMap.put(key, list); } if (!list.contains(value)) { list.add(value); } return (T) this; } @Override public T addQueryParameter(Map queryParameterMap) { if (queryParameterMap != null) { for (HashMap.Entry entry : queryParameterMap.entrySet()) { addQueryParameter(entry.getKey(), entry.getValue()); } } return (T) this; } @Override public T addQueryParameter(Object object) { if (object != null) { return addQueryParameter(ParseUtil .getParserFactory() .getStringMap(object)); } return (T) this; } @Override public T addPathParameter(String key, String value) { mPathParameterMap.put(key, value); return (T) this; } @Override public T addPathParameter(Map pathParameterMap) { if (pathParameterMap != null) { mPathParameterMap.putAll(pathParameterMap); } return (T) this; } @Override public T addPathParameter(Object object) { if (object != null) { mPathParameterMap.putAll(ParseUtil .getParserFactory() .getStringMap(object)); } return (T) this; } @Override public T doNotCacheResponse() { mCacheControl = new CacheControl.Builder().noStore().build(); return (T) this; } @Override public T getResponseOnlyIfCached() { mCacheControl = CacheControl.FORCE_CACHE; return (T) this; } @Override public T getResponseOnlyFromNetwork() { mCacheControl = CacheControl.FORCE_NETWORK; return (T) this; } @Override public T setMaxAgeCacheControl(int maxAge, TimeUnit timeUnit) { mCacheControl = new CacheControl.Builder().maxAge(maxAge, timeUnit).build(); return (T) this; } @Override public T setMaxStaleCacheControl(int maxStale, TimeUnit timeUnit) { mCacheControl = new CacheControl.Builder().maxStale(maxStale, timeUnit).build(); return (T) this; } @Override public T setExecutor(Executor executor) { mExecutor = executor; return (T) this; } @Override public T setOkHttpClient(OkHttpClient okHttpClient) { mOkHttpClient = okHttpClient; return (T) this; } @Override public T setUserAgent(String userAgent) { mUserAgent = userAgent; return (T) this; } public T setPercentageThresholdForCancelling(int percentageThresholdForCancelling) { mPercentageThresholdForCancelling = percentageThresholdForCancelling; return (T) this; } public ANRequest build() { return new ANRequest(this); } } public static class MultiPartBuilder implements RequestBuilder { private Priority mPriority = Priority.MEDIUM; private String mUrl; private Object mTag; private HashMap> mHeadersMap = new HashMap<>(); private HashMap> mQueryParameterMap = new HashMap<>(); private HashMap mPathParameterMap = new HashMap<>(); private HashMap mMultiPartParameterMap = new HashMap<>(); private HashMap> mMultiPartFileMap = new HashMap<>(); private CacheControl mCacheControl; private int mPercentageThresholdForCancelling = 0; private Executor mExecutor; private OkHttpClient mOkHttpClient; private String mUserAgent; private String mCustomContentType; public MultiPartBuilder(String url) { this.mUrl = url; } @Override public T setPriority(Priority priority) { mPriority = priority; return (T) this; } @Override public T setTag(Object tag) { mTag = tag; return (T) this; } @Override public T addQueryParameter(String key, String value) { List list = mQueryParameterMap.get(key); if (list == null) { list = new ArrayList<>(); mQueryParameterMap.put(key, list); } if (!list.contains(value)) { list.add(value); } return (T) this; } @Override public T addQueryParameter(Map queryParameterMap) { if (queryParameterMap != null) { for (HashMap.Entry entry : queryParameterMap.entrySet()) { addQueryParameter(entry.getKey(), entry.getValue()); } } return (T) this; } @Override public T addQueryParameter(Object object) { if (object != null) { return addQueryParameter(ParseUtil .getParserFactory() .getStringMap(object)); } return (T) this; } @Override public T addPathParameter(String key, String value) { mPathParameterMap.put(key, value); return (T) this; } @Override public T addPathParameter(Map pathParameterMap) { if (pathParameterMap != null) { mPathParameterMap.putAll(pathParameterMap); } return (T) this; } @Override public T addPathParameter(Object object) { if (object != null) { mPathParameterMap.putAll(ParseUtil .getParserFactory() .getStringMap(object)); } return (T) this; } @Override public T addHeaders(String key, String value) { List list = mHeadersMap.get(key); if (list == null) { list = new ArrayList<>(); mHeadersMap.put(key, list); } if (!list.contains(value)) { list.add(value); } return (T) this; } @Override public T addHeaders(Map headerMap) { if (headerMap != null) { for (HashMap.Entry entry : headerMap.entrySet()) { addHeaders(entry.getKey(), entry.getValue()); } } return (T) this; } @Override public T addHeaders(Object object) { if (object != null) { return addHeaders(ParseUtil .getParserFactory() .getStringMap(object)); } return (T) this; } @Override public T doNotCacheResponse() { mCacheControl = new CacheControl.Builder().noStore().build(); return (T) this; } @Override public T getResponseOnlyIfCached() { mCacheControl = CacheControl.FORCE_CACHE; return (T) this; } @Override public T getResponseOnlyFromNetwork() { mCacheControl = CacheControl.FORCE_NETWORK; return (T) this; } @Override public T setMaxAgeCacheControl(int maxAge, TimeUnit timeUnit) { mCacheControl = new CacheControl.Builder().maxAge(maxAge, timeUnit).build(); return (T) this; } @Override public T setMaxStaleCacheControl(int maxStale, TimeUnit timeUnit) { mCacheControl = new CacheControl.Builder().maxStale(maxStale, timeUnit).build(); return (T) this; } @Override public T setExecutor(Executor executor) { mExecutor = executor; return (T) this; } @Override public T setOkHttpClient(OkHttpClient okHttpClient) { mOkHttpClient = okHttpClient; return (T) this; } @Override public T setUserAgent(String userAgent) { mUserAgent = userAgent; return (T) this; } public T addMultipartParameter(String key, String value) { return addMultipartParameter(key, value, null); } public T addMultipartParameter(String key, String value, String contentType) { MultipartStringBody stringBody = new MultipartStringBody(value, contentType); mMultiPartParameterMap.put(key, stringBody); return (T) this; } public T addMultipartParameter(Map multiPartParameterMap) { return addMultipartParameter(multiPartParameterMap, null); } public T addMultipartParameter(Map multiPartParameterMap, String contentType) { if (multiPartParameterMap != null) { Map parameterMap = new HashMap<>(); for (HashMap.Entry entry : multiPartParameterMap.entrySet()) { MultipartStringBody stringBody = new MultipartStringBody(entry.getValue(), contentType); parameterMap.put(entry.getKey(), stringBody); } mMultiPartParameterMap.putAll(parameterMap); } return (T) this; } public T addMultipartParameter(Object object) { return addMultipartParameter(object, null); } public T addMultipartParameter(Object object, String contentType) { if (object != null) { Map parameterMap = ParseUtil .getParserFactory() .getStringMap(object); addMultipartParameter(parameterMap, contentType); } return (T) this; } public T addMultipartFile(String key, File file) { return addMultipartFile(key, file, null); } public T addMultipartFile(String key, File file, String contentType) { MultipartFileBody fileBody = new MultipartFileBody(file, contentType); addMultipartFileWithKey(key, fileBody); return (T) this; } public T addMultipartFile(Map multiPartFileMap) { return addMultipartFile(multiPartFileMap, null); } public T addMultipartFile(Map multiPartFileMap, String contentType) { if (multiPartFileMap != null) { for (HashMap.Entry entry : multiPartFileMap.entrySet()) { MultipartFileBody fileBody = new MultipartFileBody(entry.getValue(), contentType); addMultipartFileWithKey(entry.getKey(), fileBody); } } return (T) this; } public T addMultipartFileList(String key, List files) { return addMultipartFileList(key, files, null); } public T addMultipartFileList(String key, List files, String contentType) { if (files != null) { for (File file : files) { MultipartFileBody fileBody = new MultipartFileBody(file, contentType); addMultipartFileWithKey(key, fileBody); } } return (T) this; } public T addMultipartFileList(Map> multiPartFileMap) { return addMultipartFileList(multiPartFileMap, null); } public T addMultipartFileList(Map> multiPartFileMap, String contentType) { if (multiPartFileMap != null) { Map> parameterMap = new HashMap<>(); for (HashMap.Entry> entry : multiPartFileMap.entrySet()) { List files = entry.getValue(); List fileBodies = new ArrayList<>(); for (File file : files) { MultipartFileBody fileBody = new MultipartFileBody(file, contentType); fileBodies.add(fileBody); } parameterMap.put(entry.getKey(), fileBodies); } mMultiPartFileMap.putAll(parameterMap); } return (T) this; } public T setPercentageThresholdForCancelling(int percentageThresholdForCancelling) { this.mPercentageThresholdForCancelling = percentageThresholdForCancelling; return (T) this; } public T setContentType(String contentType) { mCustomContentType = contentType; return (T) this; } private void addMultipartFileWithKey(String key, MultipartFileBody fileBody) { List fileBodies = mMultiPartFileMap.get(key); if (fileBodies == null) { fileBodies = new ArrayList<>(); } fileBodies.add(fileBody); mMultiPartFileMap.put(key, fileBodies); } public ANRequest build() { return new ANRequest(this); } } @Override public String toString() { return "ANRequest{" + "sequenceNumber='" + sequenceNumber + ", mMethod=" + mMethod + ", mPriority=" + mPriority + ", mRequestType=" + mRequestType + ", mUrl=" + mUrl + '}'; } } ================================================ FILE: android-networking/src/main/java/com/androidnetworking/common/ANResponse.java ================================================ /* * Copyright (C) 2016 Amit Shekhar * Copyright (C) 2011 Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.androidnetworking.common; import com.androidnetworking.error.ANError; import okhttp3.Response; /** * Created by amitshekhar on 22/03/16. */ public class ANResponse { private final T mResult; private final ANError mANError; private Response response; public static ANResponse success(T result) { return new ANResponse<>(result); } public static ANResponse failed(ANError anError) { return new ANResponse<>(anError); } public ANResponse(T result) { this.mResult = result; this.mANError = null; } public ANResponse(ANError anError) { this.mResult = null; this.mANError = anError; } public T getResult() { return mResult; } public boolean isSuccess() { return mANError == null; } public ANError getError() { return mANError; } public void setOkHttpResponse(Response response) { this.response = response; } public Response getOkHttpResponse() { return response; } } ================================================ FILE: android-networking/src/main/java/com/androidnetworking/common/ConnectionClassManager.java ================================================ /* * Copyright (C) 2016 Amit Shekhar * Copyright (C) 2011 Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.androidnetworking.common; import com.androidnetworking.core.Core; import com.androidnetworking.interfaces.ConnectionQualityChangeListener; /** * Created by amitshekhar on 29/05/16. */ public class ConnectionClassManager { private static final int BYTES_TO_BITS = 8; private static final int DEFAULT_SAMPLES_TO_QUALITY_CHANGE = 5; private static final int MINIMUM_SAMPLES_TO_DECIDE_QUALITY = 2; private static final int DEFAULT_POOR_BANDWIDTH = 150; private static final int DEFAULT_MODERATE_BANDWIDTH = 550; private static final int DEFAULT_GOOD_BANDWIDTH = 2000; private static final long BANDWIDTH_LOWER_BOUND = 10; private static ConnectionClassManager sInstance; private ConnectionQuality mCurrentConnectionQuality = ConnectionQuality.UNKNOWN; private int mCurrentBandwidthForSampling = 0; private int mCurrentNumberOfSample = 0; private int mCurrentBandwidth = 0; private ConnectionQualityChangeListener mConnectionQualityChangeListener; public static ConnectionClassManager getInstance() { if (sInstance == null) { synchronized (ConnectionClassManager.class) { if (sInstance == null) { sInstance = new ConnectionClassManager(); } } } return sInstance; } public synchronized void updateBandwidth(long bytes, long timeInMs) { if (timeInMs == 0 || bytes < 20000 || (bytes) * 1.0 / (timeInMs) * BYTES_TO_BITS < BANDWIDTH_LOWER_BOUND) { return; } double bandwidth = (bytes) * 1.0 / (timeInMs) * BYTES_TO_BITS; mCurrentBandwidthForSampling = (int) ((mCurrentBandwidthForSampling * mCurrentNumberOfSample + bandwidth) / (mCurrentNumberOfSample + 1)); mCurrentNumberOfSample++; if (mCurrentNumberOfSample == DEFAULT_SAMPLES_TO_QUALITY_CHANGE || (mCurrentConnectionQuality == ConnectionQuality.UNKNOWN && mCurrentNumberOfSample == MINIMUM_SAMPLES_TO_DECIDE_QUALITY)) { final ConnectionQuality lastConnectionQuality = mCurrentConnectionQuality; mCurrentBandwidth = mCurrentBandwidthForSampling; if (mCurrentBandwidthForSampling <= 0) { mCurrentConnectionQuality = ConnectionQuality.UNKNOWN; } else if (mCurrentBandwidthForSampling < DEFAULT_POOR_BANDWIDTH) { mCurrentConnectionQuality = ConnectionQuality.POOR; } else if (mCurrentBandwidthForSampling < DEFAULT_MODERATE_BANDWIDTH) { mCurrentConnectionQuality = ConnectionQuality.MODERATE; } else if (mCurrentBandwidthForSampling < DEFAULT_GOOD_BANDWIDTH) { mCurrentConnectionQuality = ConnectionQuality.GOOD; } else if (mCurrentBandwidthForSampling > DEFAULT_GOOD_BANDWIDTH) { mCurrentConnectionQuality = ConnectionQuality.EXCELLENT; } if (mCurrentNumberOfSample == DEFAULT_SAMPLES_TO_QUALITY_CHANGE) { mCurrentBandwidthForSampling = 0; mCurrentNumberOfSample = 0; } if (mCurrentConnectionQuality != lastConnectionQuality && mConnectionQualityChangeListener != null) { Core.getInstance().getExecutorSupplier().forMainThreadTasks() .execute(new Runnable() { @Override public void run() { mConnectionQualityChangeListener .onChange(mCurrentConnectionQuality, mCurrentBandwidth); } }); } } } public int getCurrentBandwidth() { return mCurrentBandwidth; } public ConnectionQuality getCurrentConnectionQuality() { return mCurrentConnectionQuality; } public void setListener(ConnectionQualityChangeListener connectionQualityChangeListener) { mConnectionQualityChangeListener = connectionQualityChangeListener; } public void removeListener() { mConnectionQualityChangeListener = null; } public static void shutDown() { if (sInstance != null) { sInstance = null; } } } ================================================ FILE: android-networking/src/main/java/com/androidnetworking/common/ConnectionQuality.java ================================================ /* * Copyright (C) 2016 Amit Shekhar * Copyright (C) 2011 Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.androidnetworking.common; /** * Created by amitshekhar on 29/05/16. */ public enum ConnectionQuality { /** * Bandwidth under 150 kbps. */ POOR, /** * Bandwidth between 150 and 550 kbps. */ MODERATE, /** * Bandwidth between 550 and 2000 kbps. */ GOOD, /** * EXCELLENT - Bandwidth over 2000 kbps. */ EXCELLENT, /** * Placeholder for unknown bandwidth. This is the initial value and will stay at this value * if a bandwidth cannot be accurately found. */ UNKNOWN } ================================================ FILE: android-networking/src/main/java/com/androidnetworking/common/Method.java ================================================ /* * Copyright (C) 2016 Amit Shekhar * Copyright (C) 2011 Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.androidnetworking.common; /** * Created by amitshekhar on 26/03/16. */ public interface Method { int GET = 0; int POST = 1; int PUT = 2; int DELETE = 3; int HEAD = 4; int PATCH = 5; int OPTIONS = 6; } ================================================ FILE: android-networking/src/main/java/com/androidnetworking/common/Priority.java ================================================ /* * Copyright (C) 2016 Amit Shekhar * Copyright (C) 2011 Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.androidnetworking.common; /** * Created by amitshekhar on 22/03/16. */ /** * Priority levels recognized by the request server. */ public enum Priority { /** * NOTE: DO NOT CHANGE ORDERING OF THOSE CONSTANTS UNDER ANY CIRCUMSTANCES. * Doing so will make ordering incorrect. */ /** * Lowest priority level. Used for prefetches of data. */ LOW, /** * Medium priority level. Used for warming of data that might soon get visible. */ MEDIUM, /** * Highest priority level. Used for data that are currently visible on screen. */ HIGH, /** * Highest priority level. Used for data that are required instantly(mainly for emergency). */ IMMEDIATE } ================================================ FILE: android-networking/src/main/java/com/androidnetworking/common/RequestBuilder.java ================================================ /* * Copyright (C) 2016 Amit Shekhar * Copyright (C) 2011 Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.androidnetworking.common; import java.util.Map; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; import okhttp3.OkHttpClient; /** * Created by amitshekhar on 26/03/16. */ public interface RequestBuilder { RequestBuilder setPriority(Priority priority); RequestBuilder setTag(Object tag); RequestBuilder addHeaders(String key, String value); RequestBuilder addHeaders(Map headerMap); RequestBuilder addHeaders(Object object); RequestBuilder addQueryParameter(String key, String value); RequestBuilder addQueryParameter(Map queryParameterMap); RequestBuilder addQueryParameter(Object object); RequestBuilder addPathParameter(String key, String value); RequestBuilder addPathParameter(Map pathParameterMap); RequestBuilder addPathParameter(Object object); RequestBuilder doNotCacheResponse(); RequestBuilder getResponseOnlyIfCached(); RequestBuilder getResponseOnlyFromNetwork(); RequestBuilder setMaxAgeCacheControl(int maxAge, TimeUnit timeUnit); RequestBuilder setMaxStaleCacheControl(int maxStale, TimeUnit timeUnit); RequestBuilder setExecutor(Executor executor); RequestBuilder setOkHttpClient(OkHttpClient okHttpClient); RequestBuilder setUserAgent(String userAgent); } ================================================ FILE: android-networking/src/main/java/com/androidnetworking/common/RequestType.java ================================================ /* * Copyright (C) 2016 Amit Shekhar * Copyright (C) 2011 Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.androidnetworking.common; /** * Created by amitshekhar on 04/04/16. */ public interface RequestType { int SIMPLE = 0; int DOWNLOAD = 1; int MULTIPART = 2; } ================================================ FILE: android-networking/src/main/java/com/androidnetworking/common/ResponseType.java ================================================ /* * Copyright (C) 2016 Amit Shekhar * Copyright (C) 2011 Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.androidnetworking.common; /** * Created by amitshekhar on 26/03/16. */ public enum ResponseType { STRING, JSON_OBJECT, JSON_ARRAY, OK_HTTP_RESPONSE, BITMAP, PREFETCH, PARSED } ================================================ FILE: android-networking/src/main/java/com/androidnetworking/core/ANExecutor.java ================================================ /* * Copyright (C) 2016 Amit Shekhar * Copyright (C) 2011 Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.androidnetworking.core; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.telephony.TelephonyManager; import com.androidnetworking.common.Priority; import com.androidnetworking.internal.InternalRunnable; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; import java.util.concurrent.PriorityBlockingQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * Created by amitshekhar on 22/03/16. */ public class ANExecutor extends ThreadPoolExecutor { private static final int DEFAULT_THREAD_COUNT = 3; ANExecutor(int maxNumThreads, ThreadFactory threadFactory) { super(maxNumThreads, maxNumThreads, 0, TimeUnit.MILLISECONDS, new PriorityBlockingQueue(), threadFactory); } void adjustThreadCount(NetworkInfo info) { if (info == null || !info.isConnectedOrConnecting()) { setThreadCount(DEFAULT_THREAD_COUNT); return; } switch (info.getType()) { case ConnectivityManager.TYPE_WIFI: case ConnectivityManager.TYPE_WIMAX: case ConnectivityManager.TYPE_ETHERNET: setThreadCount(4); break; case ConnectivityManager.TYPE_MOBILE: switch (info.getSubtype()) { case TelephonyManager.NETWORK_TYPE_LTE: // 4G case TelephonyManager.NETWORK_TYPE_HSPAP: case TelephonyManager.NETWORK_TYPE_EHRPD: setThreadCount(3); break; case TelephonyManager.NETWORK_TYPE_UMTS: // 3G case TelephonyManager.NETWORK_TYPE_CDMA: case TelephonyManager.NETWORK_TYPE_EVDO_0: case TelephonyManager.NETWORK_TYPE_EVDO_A: case TelephonyManager.NETWORK_TYPE_EVDO_B: setThreadCount(2); break; case TelephonyManager.NETWORK_TYPE_GPRS: // 2G case TelephonyManager.NETWORK_TYPE_EDGE: setThreadCount(1); break; default: setThreadCount(DEFAULT_THREAD_COUNT); } break; default: setThreadCount(DEFAULT_THREAD_COUNT); } } private void setThreadCount(int threadCount) { setCorePoolSize(threadCount); setMaximumPoolSize(threadCount); } @Override public Future submit(Runnable task) { AndroidNetworkingFutureTask futureTask = new AndroidNetworkingFutureTask((InternalRunnable) task); execute(futureTask); return futureTask; } private static final class AndroidNetworkingFutureTask extends FutureTask implements Comparable { private final InternalRunnable hunter; public AndroidNetworkingFutureTask(InternalRunnable hunter) { super(hunter, null); this.hunter = hunter; } @Override public int compareTo(AndroidNetworkingFutureTask other) { Priority p1 = hunter.getPriority(); Priority p2 = other.hunter.getPriority(); return (p1 == p2 ? hunter.sequence - other.hunter.sequence : p2.ordinal() - p1.ordinal()); } } } ================================================ FILE: android-networking/src/main/java/com/androidnetworking/core/Core.java ================================================ /* * Copyright (C) 2016 Amit Shekhar * Copyright (C) 2011 Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.androidnetworking.core; /** * Created by amitshekhar on 22/03/16. */ public class Core { private static Core sInstance = null; private final ExecutorSupplier mExecutorSupplier; private Core() { this.mExecutorSupplier = new DefaultExecutorSupplier(); } public static Core getInstance() { if (sInstance == null) { synchronized (Core.class) { if (sInstance == null) { sInstance = new Core(); } } } return sInstance; } public ExecutorSupplier getExecutorSupplier() { return mExecutorSupplier; } public static void shutDown() { if (sInstance != null) { sInstance = null; } } } ================================================ FILE: android-networking/src/main/java/com/androidnetworking/core/DefaultExecutorSupplier.java ================================================ /* * Copyright (C) 2016 Amit Shekhar * Copyright (C) 2011 Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.androidnetworking.core; import android.os.Process; import java.util.concurrent.Executor; import java.util.concurrent.ThreadFactory; /** * Created by amitshekhar on 22/03/16. */ public class DefaultExecutorSupplier implements ExecutorSupplier { public static final int DEFAULT_MAX_NUM_THREADS = 2 * Runtime.getRuntime().availableProcessors() + 1; private final ANExecutor mNetworkExecutor; private final ANExecutor mImmediateNetworkExecutor; private final Executor mMainThreadExecutor; public DefaultExecutorSupplier() { ThreadFactory backgroundPriorityThreadFactory = new PriorityThreadFactory(Process.THREAD_PRIORITY_BACKGROUND); mNetworkExecutor = new ANExecutor(DEFAULT_MAX_NUM_THREADS, backgroundPriorityThreadFactory); mImmediateNetworkExecutor = new ANExecutor(2, backgroundPriorityThreadFactory); mMainThreadExecutor = new MainThreadExecutor(); } @Override public ANExecutor forNetworkTasks() { return mNetworkExecutor; } @Override public ANExecutor forImmediateNetworkTasks() { return mImmediateNetworkExecutor; } @Override public Executor forMainThreadTasks() { return mMainThreadExecutor; } } ================================================ FILE: android-networking/src/main/java/com/androidnetworking/core/ExecutorSupplier.java ================================================ /* * Copyright (C) 2016 Amit Shekhar * Copyright (C) 2011 Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.androidnetworking.core; import java.util.concurrent.Executor; /** * Created by amitshekhar on 22/03/16. */ public interface ExecutorSupplier { ANExecutor forNetworkTasks(); ANExecutor forImmediateNetworkTasks(); Executor forMainThreadTasks(); } ================================================ FILE: android-networking/src/main/java/com/androidnetworking/core/MainThreadExecutor.java ================================================ /* * Copyright (C) 2016 Amit Shekhar * Copyright (C) 2011 Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.androidnetworking.core; import android.os.Handler; import android.os.Looper; import java.util.concurrent.Executor; /** * Created by amitshekhar on 22/03/16. */ public class MainThreadExecutor implements Executor { private final Handler handler = new Handler(Looper.getMainLooper()); @Override public void execute(Runnable runnable) { handler.post(runnable); } } ================================================ FILE: android-networking/src/main/java/com/androidnetworking/core/PriorityThreadFactory.java ================================================ /* * Copyright (C) 2016 Amit Shekhar * Copyright (C) 2011 Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.androidnetworking.core; /** * Created by amitshekhar on 22/03/16. */ import android.os.Process; import java.util.concurrent.ThreadFactory; public class PriorityThreadFactory implements ThreadFactory { private final int mThreadPriority; public PriorityThreadFactory(int threadPriority) { mThreadPriority = threadPriority; } @Override public Thread newThread(final Runnable runnable) { Runnable wrapperRunnable = new Runnable() { @Override public void run() { try { Process.setThreadPriority(mThreadPriority); } catch (Throwable t) { } runnable.run(); } }; return new Thread(wrapperRunnable); } } ================================================ FILE: android-networking/src/main/java/com/androidnetworking/error/ANError.java ================================================ /* * Copyright (C) 2016 Amit Shekhar * Copyright (C) 2011 Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.androidnetworking.error; import com.androidnetworking.common.ANConstants; import com.androidnetworking.utils.ParseUtil; import okhttp3.Response; /** * Created by amitshekhar on 22/03/16. */ @SuppressWarnings({"unchecked", "unused"}) public class ANError extends Exception { private String errorBody; private int errorCode = 0; private String errorDetail; private Response response; public ANError() { } public ANError(Response response) { this.response = response; } public ANError(String message) { super(message); } public ANError(String message, Response response) { super(message); this.response = response; } public ANError(String message, Throwable throwable) { super(message, throwable); } public ANError(String message, Response response, Throwable throwable) { super(message, throwable); this.response = response; } public ANError(Response response, Throwable throwable) { super(throwable); this.response = response; } public ANError(Throwable throwable) { super(throwable); } public Response getResponse() { return response; } public void setErrorDetail(String errorDetail) { this.errorDetail = errorDetail; } public String getErrorDetail() { return this.errorDetail; } public void setErrorCode(int errorCode) { this.errorCode = errorCode; } public int getErrorCode() { return this.errorCode; } public void setCancellationMessageInError() { this.errorDetail = ANConstants.REQUEST_CANCELLED_ERROR; } public String getErrorBody() { return errorBody; } public void setErrorBody(String errorBody) { this.errorBody = errorBody; } public T getErrorAsObject(Class objectClass) { try { return (T) (ParseUtil .getParserFactory() .getObject(errorBody, objectClass)); } catch (Exception e) { e.printStackTrace(); } return null; } } ================================================ FILE: android-networking/src/main/java/com/androidnetworking/gsonparserfactory/GsonParserFactory.java ================================================ /* * * * Copyright (C) 2016 Amit Shekhar * * Copyright (C) 2011 Android Open Source Project * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * */ package com.androidnetworking.gsonparserfactory; import com.androidnetworking.interfaces.Parser; import com.google.gson.Gson; import com.google.gson.TypeAdapter; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; import java.util.HashMap; import okhttp3.RequestBody; import okhttp3.ResponseBody; /** * Created by amitshekhar on 31/07/16. */ public final class GsonParserFactory extends Parser.Factory { private final Gson gson; public GsonParserFactory() { this.gson = new Gson(); } public GsonParserFactory(Gson gson) { this.gson = gson; } @Override public Parser responseBodyParser(Type type) { TypeAdapter adapter = gson.getAdapter(TypeToken.get(type)); return new GsonResponseBodyParser<>(gson, adapter); } @Override public Parser requestBodyParser(Type type) { TypeAdapter adapter = gson.getAdapter(TypeToken.get(type)); return new GsonRequestBodyParser<>(gson, adapter); } @Override public Object getObject(String string, Type type) { try { return gson.fromJson(string, type); } catch (Exception e) { e.printStackTrace(); } return null; } @Override public String getString(Object object) { try { return gson.toJson(object); } catch (Exception e) { e.printStackTrace(); } return ""; } @Override public HashMap getStringMap(Object object) { try { Type type = new TypeToken>() { }.getType(); return gson.fromJson(gson.toJson(object), type); } catch (Exception e) { e.printStackTrace(); } return new HashMap<>(); } } ================================================ FILE: android-networking/src/main/java/com/androidnetworking/gsonparserfactory/GsonRequestBodyParser.java ================================================ /* * * * Copyright (C) 2016 Amit Shekhar * * Copyright (C) 2011 Android Open Source Project * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * */ package com.androidnetworking.gsonparserfactory; import com.androidnetworking.interfaces.Parser; import com.google.gson.Gson; import com.google.gson.TypeAdapter; import com.google.gson.stream.JsonWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.nio.charset.Charset; import okhttp3.MediaType; import okhttp3.RequestBody; import okio.Buffer; /** * Created by amitshekhar on 31/07/16. */ final class GsonRequestBodyParser implements Parser { private static final MediaType MEDIA_TYPE = MediaType.parse("application/json; charset=UTF-8"); private static final Charset UTF_8 = Charset.forName("UTF-8"); private final Gson gson; private final TypeAdapter adapter; GsonRequestBodyParser(Gson gson, TypeAdapter adapter) { this.gson = gson; this.adapter = adapter; } @Override public RequestBody convert(T value) throws IOException { Buffer buffer = new Buffer(); Writer writer = new OutputStreamWriter(buffer.outputStream(), UTF_8); JsonWriter jsonWriter = gson.newJsonWriter(writer); adapter.write(jsonWriter, value); jsonWriter.close(); return RequestBody.create(MEDIA_TYPE, buffer.readByteString()); } } ================================================ FILE: android-networking/src/main/java/com/androidnetworking/gsonparserfactory/GsonResponseBodyParser.java ================================================ /* * * * Copyright (C) 2016 Amit Shekhar * * Copyright (C) 2011 Android Open Source Project * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * */ package com.androidnetworking.gsonparserfactory; import com.androidnetworking.interfaces.Parser; import com.google.gson.Gson; import com.google.gson.TypeAdapter; import com.google.gson.stream.JsonReader; import java.io.IOException; import okhttp3.ResponseBody; /** * Created by amitshekhar on 31/07/16. */ final class GsonResponseBodyParser implements Parser { private final Gson gson; private final TypeAdapter adapter; GsonResponseBodyParser(Gson gson, TypeAdapter adapter) { this.gson = gson; this.adapter = adapter; } @Override public T convert(ResponseBody value) throws IOException { JsonReader jsonReader = gson.newJsonReader(value.charStream()); try { return adapter.read(jsonReader); } finally { value.close(); } } } ================================================ FILE: android-networking/src/main/java/com/androidnetworking/interceptors/GzipRequestInterceptor.java ================================================ /* * Copyright (C) 2016 Amit Shekhar * Copyright (C) 2011 Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.androidnetworking.interceptors; import java.io.IOException; import okhttp3.Interceptor; import okhttp3.MediaType; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import okio.Buffer; import okio.BufferedSink; import okio.GzipSink; import okio.Okio; /** * Created by amitshekhar on 02/05/16. */ public class GzipRequestInterceptor implements Interceptor { @Override public Response intercept(Chain chain) throws IOException { Request originalRequest = chain.request(); if (originalRequest.body() == null || originalRequest.header("Content-Encoding") != null) { return chain.proceed(originalRequest); } Request compressedRequest = originalRequest.newBuilder() .header("Content-Encoding", "gzip") .method(originalRequest.method(), forceContentLength(gzip(originalRequest.body()))) .build(); return chain.proceed(compressedRequest); } private RequestBody forceContentLength(final RequestBody requestBody) throws IOException { final Buffer buffer = new Buffer(); requestBody.writeTo(buffer); return new RequestBody() { @Override public MediaType contentType() { return requestBody.contentType(); } @Override public long contentLength() { return buffer.size(); } @Override public void writeTo(BufferedSink sink) throws IOException { sink.write(buffer.snapshot()); } }; } private RequestBody gzip(final RequestBody body) { return new RequestBody() { @Override public MediaType contentType() { return body.contentType(); } @Override public long contentLength() { return -1; // We don't know the compressed length in advance! } @Override public void writeTo(BufferedSink sink) throws IOException { BufferedSink gzipSink = Okio.buffer(new GzipSink(sink)); body.writeTo(gzipSink); gzipSink.close(); } }; } } ================================================ FILE: android-networking/src/main/java/com/androidnetworking/interceptors/HttpLoggingInterceptor.java ================================================ /* * * * Copyright (C) 2016 Amit Shekhar * * Copyright (C) 2011 Android Open Source Project * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * */ package com.androidnetworking.interceptors; import java.io.EOFException; import java.io.IOException; import java.nio.charset.Charset; import java.util.concurrent.TimeUnit; import okhttp3.Connection; import okhttp3.Headers; import okhttp3.Interceptor; import okhttp3.MediaType; import okhttp3.Protocol; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import okhttp3.ResponseBody; import okhttp3.internal.http.HttpHeaders; import okhttp3.internal.platform.Platform; import okio.Buffer; import okio.BufferedSource; import static okhttp3.internal.platform.Platform.INFO; /** * Created by amitshekhar on 31/01/17. */ public class HttpLoggingInterceptor implements Interceptor { private static final Charset UTF8 = Charset.forName("UTF-8"); public enum Level { /** * No logs. */ NONE, /** * Logs request and response lines. *

*

Example: *

{@code
         * --> POST /greeting http/1.1 (3-byte body)
         *
         * <-- 200 OK (22ms, 6-byte body)
         * }
*/ BASIC, /** * Logs request and response lines and their respective headers. *

*

Example: *

{@code
         * --> POST /greeting http/1.1
         * Host: example.com
         * Content-Type: plain/text
         * Content-Length: 3
         * --> END POST
         *
         * <-- 200 OK (22ms)
         * Content-Type: plain/text
         * Content-Length: 6
         * <-- END HTTP
         * }
*/ HEADERS, /** * Logs request and response lines and their respective headers and bodies (if present). *

*

Example: *

{@code
         * --> POST /greeting http/1.1
         * Host: example.com
         * Content-Type: plain/text
         * Content-Length: 3
         *
         * Hi?
         * --> END POST
         *
         * <-- 200 OK (22ms)
         * Content-Type: plain/text
         * Content-Length: 6
         *
         * Hello!
         * <-- END HTTP
         * }
*/ BODY } public interface Logger { void log(String message); /** * A {@link Logger} defaults output appropriate for the current platform. */ Logger DEFAULT = new Logger() { @Override public void log(String message) { Platform.get().log(INFO, message, null); } }; } public HttpLoggingInterceptor() { this(Logger.DEFAULT); } public HttpLoggingInterceptor(Logger logger) { this.logger = logger; } private final Logger logger; private volatile Level level = Level.NONE; /** * Change the level at which this interceptor logs. */ public HttpLoggingInterceptor setLevel(Level level) { if (level == null) throw new NullPointerException("level == null. Use Level.NONE instead."); this.level = level; return this; } public Level getLevel() { return level; } @Override public Response intercept(Chain chain) throws IOException { Level level = this.level; Request request = chain.request(); if (level == Level.NONE) { return chain.proceed(request); } boolean logBody = level == Level.BODY; boolean logHeaders = logBody || level == Level.HEADERS; RequestBody requestBody = request.body(); boolean hasRequestBody = requestBody != null; Connection connection = chain.connection(); Protocol protocol = connection != null ? connection.protocol() : Protocol.HTTP_1_1; String requestStartMessage = "--> " + request.method() + ' ' + request.url() + ' ' + protocol; if (!logHeaders && hasRequestBody) { requestStartMessage += " (" + requestBody.contentLength() + "-byte body)"; } logger.log(requestStartMessage); if (logHeaders) { if (hasRequestBody) { // Request body headers are only present when installed as a network interceptor. Force // them to be included (when available) so there values are known. if (requestBody.contentType() != null) { logger.log("Content-Type: " + requestBody.contentType()); } if (requestBody.contentLength() != -1) { logger.log("Content-Length: " + requestBody.contentLength()); } } Headers headers = request.headers(); for (int i = 0, count = headers.size(); i < count; i++) { String name = headers.name(i); // Skip headers from the request body as they are explicitly logged above. if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) { logger.log(name + ": " + headers.value(i)); } } if (!logBody || !hasRequestBody) { logger.log("--> END " + request.method()); } else if (bodyEncoded(request.headers())) { logger.log("--> END " + request.method() + " (encoded body omitted)"); } else { Buffer buffer = new Buffer(); requestBody.writeTo(buffer); Charset charset = UTF8; MediaType contentType = requestBody.contentType(); if (contentType != null) { charset = contentType.charset(UTF8); } logger.log(""); if (isPlaintext(buffer)) { logger.log(buffer.readString(charset)); logger.log("--> END " + request.method() + " (" + requestBody.contentLength() + "-byte body)"); } else { logger.log("--> END " + request.method() + " (binary " + requestBody.contentLength() + "-byte body omitted)"); } } } long startNs = System.nanoTime(); Response response; try { response = chain.proceed(request); } catch (Exception e) { logger.log("<-- HTTP FAILED: " + e); throw e; } long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs); ResponseBody responseBody = response.body(); long contentLength = responseBody.contentLength(); String bodySize = contentLength != -1 ? contentLength + "-byte" : "unknown-length"; logger.log("<-- " + response.code() + ' ' + response.message() + ' ' + response.request().url() + " (" + tookMs + "ms" + (!logHeaders ? ", " + bodySize + " body" : "") + ')'); if (logHeaders) { Headers headers = response.headers(); for (int i = 0, count = headers.size(); i < count; i++) { logger.log(headers.name(i) + ": " + headers.value(i)); } if (!logBody || !HttpHeaders.hasBody(response)) { logger.log("<-- END HTTP"); } else if (bodyEncoded(response.headers())) { logger.log("<-- END HTTP (encoded body omitted)"); } else { BufferedSource source = responseBody.source(); source.request(Long.MAX_VALUE); // Buffer the entire body. Buffer buffer = source.buffer(); Charset charset = UTF8; MediaType contentType = responseBody.contentType(); if (contentType != null) { charset = contentType.charset(UTF8); } if (!isPlaintext(buffer)) { logger.log(""); logger.log("<-- END HTTP (binary " + buffer.size() + "-byte body omitted)"); return response; } if (contentLength != 0) { logger.log(""); logger.log(buffer.clone().readString(charset)); } logger.log("<-- END HTTP (" + buffer.size() + "-byte body)"); } } return response; } /** * Returns true if the body in question probably contains human readable text. Uses a small sample * of code points to detect unicode control characters commonly used in binary file signatures. */ static boolean isPlaintext(Buffer buffer) { try { Buffer prefix = new Buffer(); long byteCount = buffer.size() < 64 ? buffer.size() : 64; buffer.copyTo(prefix, 0, byteCount); for (int i = 0; i < 16; i++) { if (prefix.exhausted()) { break; } int codePoint = prefix.readUtf8CodePoint(); if (Character.isISOControl(codePoint) && !Character.isWhitespace(codePoint)) { return false; } } return true; } catch (EOFException e) { return false; // Truncated UTF-8 sequence. } } private boolean bodyEncoded(Headers headers) { String contentEncoding = headers.get("Content-Encoding"); return contentEncoding != null && !contentEncoding.equalsIgnoreCase("identity"); } } ================================================ FILE: android-networking/src/main/java/com/androidnetworking/interfaces/AnalyticsListener.java ================================================ /* * Copyright (C) 2016 Amit Shekhar * Copyright (C) 2011 Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.androidnetworking.interfaces; /** * Created by amitshekhar on 31/05/16. */ public interface AnalyticsListener { void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache); } ================================================ FILE: android-networking/src/main/java/com/androidnetworking/interfaces/BitmapRequestListener.java ================================================ /* * Copyright (C) 2016 Amit Shekhar * Copyright (C) 2011 Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.androidnetworking.interfaces; import android.graphics.Bitmap; import com.androidnetworking.error.ANError; /** * Created by amitshekhar on 23/05/16. */ public interface BitmapRequestListener { void onResponse(Bitmap response); void onError(ANError anError); } ================================================ FILE: android-networking/src/main/java/com/androidnetworking/interfaces/ConnectionQualityChangeListener.java ================================================ /* * Copyright (C) 2016 Amit Shekhar * Copyright (C) 2011 Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.androidnetworking.interfaces; import com.androidnetworking.common.ConnectionQuality; /** * Created by amitshekhar on 29/05/16. */ public interface ConnectionQualityChangeListener { void onChange(ConnectionQuality currentConnectionQuality, int currentBandwidth); } ================================================ FILE: android-networking/src/main/java/com/androidnetworking/interfaces/DownloadListener.java ================================================ /* * Copyright (C) 2016 Amit Shekhar * Copyright (C) 2011 Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.androidnetworking.interfaces; import com.androidnetworking.error.ANError; /** * Created by amitshekhar on 29/04/16. */ public interface DownloadListener { void onDownloadComplete(); void onError(ANError anError); } ================================================ FILE: android-networking/src/main/java/com/androidnetworking/interfaces/DownloadProgressListener.java ================================================ /* * Copyright (C) 2016 Amit Shekhar * Copyright (C) 2011 Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.androidnetworking.interfaces; /** * Created by amitshekhar on 30/03/16. */ public interface DownloadProgressListener { void onProgress(long bytesDownloaded, long totalBytes); } ================================================ FILE: android-networking/src/main/java/com/androidnetworking/interfaces/JSONArrayRequestListener.java ================================================ /* * Copyright (C) 2016 Amit Shekhar * Copyright (C) 2011 Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.androidnetworking.interfaces; import com.androidnetworking.error.ANError; import org.json.JSONArray; /** * Created by amitshekhar on 23/05/16. */ public interface JSONArrayRequestListener { void onResponse(JSONArray response); void onError(ANError anError); } ================================================ FILE: android-networking/src/main/java/com/androidnetworking/interfaces/JSONObjectRequestListener.java ================================================ /* * Copyright (C) 2016 Amit Shekhar * Copyright (C) 2011 Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.androidnetworking.interfaces; import com.androidnetworking.error.ANError; import org.json.JSONObject; /** * Created by amitshekhar on 23/05/16. */ public interface JSONObjectRequestListener { void onResponse(JSONObject response); void onError(ANError anError); } ================================================ FILE: android-networking/src/main/java/com/androidnetworking/interfaces/OkHttpResponseAndBitmapRequestListener.java ================================================ /* * * * Copyright (C) 2016 Amit Shekhar * * Copyright (C) 2011 Android Open Source Project * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * */ package com.androidnetworking.interfaces; import android.graphics.Bitmap; import com.androidnetworking.error.ANError; import okhttp3.Response; /** * Created by amitshekhar on 23/05/16. */ public interface OkHttpResponseAndBitmapRequestListener { void onResponse(Response okHttpResponse, Bitmap response); void onError(ANError anError); } ================================================ FILE: android-networking/src/main/java/com/androidnetworking/interfaces/OkHttpResponseAndJSONArrayRequestListener.java ================================================ /* * * * Copyright (C) 2016 Amit Shekhar * * Copyright (C) 2011 Android Open Source Project * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * */ package com.androidnetworking.interfaces; import com.androidnetworking.error.ANError; import org.json.JSONArray; import okhttp3.Response; /** * Created by amitshekhar on 23/05/16. */ public interface OkHttpResponseAndJSONArrayRequestListener { void onResponse(Response okHttpResponse, JSONArray response); void onError(ANError anError); } ================================================ FILE: android-networking/src/main/java/com/androidnetworking/interfaces/OkHttpResponseAndJSONObjectRequestListener.java ================================================ /* * * * Copyright (C) 2016 Amit Shekhar * * Copyright (C) 2011 Android Open Source Project * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * */ package com.androidnetworking.interfaces; import com.androidnetworking.error.ANError; import org.json.JSONObject; import okhttp3.Response; /** * Created by amitshekhar on 23/05/16. */ public interface OkHttpResponseAndJSONObjectRequestListener { void onResponse(Response okHttpResponse, JSONObject response); void onError(ANError anError); } ================================================ FILE: android-networking/src/main/java/com/androidnetworking/interfaces/OkHttpResponseAndParsedRequestListener.java ================================================ /* * * * Copyright (C) 2016 Amit Shekhar * * Copyright (C) 2011 Android Open Source Project * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * */ package com.androidnetworking.interfaces; import com.androidnetworking.error.ANError; import okhttp3.Response; /** * Created by amitshekhar on 31/07/16. */ public interface OkHttpResponseAndParsedRequestListener { void onResponse(Response okHttpResponse, T response); void onError(ANError anError); } ================================================ FILE: android-networking/src/main/java/com/androidnetworking/interfaces/OkHttpResponseAndStringRequestListener.java ================================================ /* * * * Copyright (C) 2016 Amit Shekhar * * Copyright (C) 2011 Android Open Source Project * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * */ package com.androidnetworking.interfaces; import com.androidnetworking.error.ANError; import okhttp3.Response; /** * Created by amitshekhar on 23/05/16. */ public interface OkHttpResponseAndStringRequestListener { void onResponse(Response okHttpResponse, String response); void onError(ANError anError); } ================================================ FILE: android-networking/src/main/java/com/androidnetworking/interfaces/OkHttpResponseListener.java ================================================ /* * * * Copyright (C) 2016 Amit Shekhar * * Copyright (C) 2011 Android Open Source Project * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * */ package com.androidnetworking.interfaces; import com.androidnetworking.error.ANError; import okhttp3.Response; /** * Created by amitshekhar on 22/08/16. */ public interface OkHttpResponseListener { void onResponse(Response response); void onError(ANError anError); } ================================================ FILE: android-networking/src/main/java/com/androidnetworking/interfaces/ParsedRequestListener.java ================================================ /* * * * Copyright (C) 2016 Amit Shekhar * * Copyright (C) 2011 Android Open Source Project * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * */ package com.androidnetworking.interfaces; import com.androidnetworking.error.ANError; /** * Created by amitshekhar on 31/07/16. */ public interface ParsedRequestListener { void onResponse(T response); void onError(ANError anError); } ================================================ FILE: android-networking/src/main/java/com/androidnetworking/interfaces/Parser.java ================================================ /* * * * Copyright (C) 2016 Amit Shekhar * * Copyright (C) 2011 Android Open Source Project * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * */ package com.androidnetworking.interfaces; import java.io.IOException; import java.lang.reflect.Type; import java.util.HashMap; import okhttp3.RequestBody; import okhttp3.ResponseBody; /** * Created by amitshekhar on 31/07/16. */ public interface Parser { T convert(F value) throws IOException; abstract class Factory { public Parser responseBodyParser(Type type) { return null; } public Parser requestBodyParser(Type type) { return null; } public Object getObject(String string, Type type) { return null; } public String getString(Object object) { return null; } public HashMap getStringMap(Object object) { return null; } } } ================================================ FILE: android-networking/src/main/java/com/androidnetworking/interfaces/StringRequestListener.java ================================================ /* * Copyright (C) 2016 Amit Shekhar * Copyright (C) 2011 Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.androidnetworking.interfaces; import com.androidnetworking.error.ANError; /** * Created by amitshekhar on 23/05/16. */ public interface StringRequestListener { void onResponse(String response); void onError(ANError anError); } ================================================ FILE: android-networking/src/main/java/com/androidnetworking/interfaces/UploadProgressListener.java ================================================ /* * Copyright (C) 2016 Amit Shekhar * Copyright (C) 2011 Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.androidnetworking.interfaces; /** * Created by amitshekhar on 21/04/16. */ public interface UploadProgressListener { void onProgress(long bytesUploaded, long totalBytes); } ================================================ FILE: android-networking/src/main/java/com/androidnetworking/internal/ANImageLoader.java ================================================ /* * Copyright (C) 2016 Amit Shekhar * Copyright (C) 2011 Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.androidnetworking.internal; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Handler; import android.os.Looper; import android.widget.ImageView; import com.androidnetworking.AndroidNetworking; import com.androidnetworking.cache.LruBitmapCache; import com.androidnetworking.common.ANRequest; import com.androidnetworking.error.ANError; import com.androidnetworking.interfaces.BitmapRequestListener; import java.util.HashMap; import java.util.LinkedList; /** * Created by amitshekhar on 23/03/16. */ public class ANImageLoader { // Get max available VM memory, exceeding this amount will throw an // OutOfMemory exception. Stored in kilobytes as LruCache takes an // int in its constructor. private static final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024); // Use 1/8th of the available memory for this memory cache. private static final int cacheSize = maxMemory / 8; private int mBatchResponseDelayMs = 100; private final ImageCache mCache; private final HashMap mInFlightRequests = new HashMap(); private final HashMap mBatchedResponses = new HashMap(); private final Handler mHandler = new Handler(Looper.getMainLooper()); private Runnable mRunnable; private BitmapFactory.Options mBitmapOptions = new BitmapFactory.Options(); private static ANImageLoader sInstance; public static void initialize() { getInstance(); } public static ANImageLoader getInstance() { if (sInstance == null) { synchronized (ANImageLoader.class) { if (sInstance == null) { sInstance = new ANImageLoader(new LruBitmapCache(cacheSize)); } } } return sInstance; } public interface ImageCache { Bitmap getBitmap(String key); void putBitmap(String key, Bitmap bitmap); void evictBitmap(String key); void evictAllBitmap(); } public ANImageLoader(ImageCache imageCache) { mCache = imageCache; } public ImageCache getImageCache() { return mCache; } public static ImageListener getImageListener(final ImageView view, final int defaultImageResId, final int errorImageResId) { return new ImageListener() { @Override public void onResponse(ImageContainer response, boolean isImmediate) { if (response.getBitmap() != null) { view.setImageBitmap(response.getBitmap()); } else if (defaultImageResId != 0) { view.setImageResource(defaultImageResId); } } @Override public void onError(ANError anError) { if (errorImageResId != 0) { view.setImageResource(errorImageResId); } } }; } public interface ImageListener { void onResponse(ImageContainer response, boolean isImmediate); void onError(ANError anError); } public boolean isCached(String requestUrl, int maxWidth, int maxHeight) { return isCached(requestUrl, maxWidth, maxHeight, ImageView.ScaleType.CENTER_INSIDE); } public boolean isCached(String requestUrl, int maxWidth, int maxHeight, ImageView.ScaleType scaleType) { throwIfNotOnMainThread(); String cacheKey = getCacheKey(requestUrl, maxWidth, maxHeight, scaleType); return mCache.getBitmap(cacheKey) != null; } public ImageContainer get(String requestUrl, final ImageListener listener) { return get(requestUrl, listener, 0, 0); } public ImageContainer get(String requestUrl, ImageListener imageListener, int maxWidth, int maxHeight) { return get(requestUrl, imageListener, maxWidth, maxHeight, ImageView.ScaleType.CENTER_INSIDE); } public ImageContainer get(String requestUrl, ImageListener imageListener, int maxWidth, int maxHeight, ImageView.ScaleType scaleType) { throwIfNotOnMainThread(); final String cacheKey = getCacheKey(requestUrl, maxWidth, maxHeight, scaleType); Bitmap cachedBitmap = mCache.getBitmap(cacheKey); if (cachedBitmap != null) { ImageContainer container = new ImageContainer(cachedBitmap, requestUrl, null, null); imageListener.onResponse(container, true); return container; } ImageContainer imageContainer = new ImageContainer(null, requestUrl, cacheKey, imageListener); imageListener.onResponse(imageContainer, true); BatchedImageRequest request = mInFlightRequests.get(cacheKey); if (request != null) { request.addContainer(imageContainer); return imageContainer; } ANRequest newRequest = makeImageRequest(requestUrl, maxWidth, maxHeight, scaleType, cacheKey); mInFlightRequests.put(cacheKey, new BatchedImageRequest(newRequest, imageContainer)); return imageContainer; } protected ANRequest makeImageRequest(String requestUrl, int maxWidth, int maxHeight, ImageView.ScaleType scaleType, final String cacheKey) { ANRequest ANRequest = AndroidNetworking.get(requestUrl) .setTag("ImageRequestTag") .setBitmapMaxHeight(maxHeight) .setBitmapMaxWidth(maxWidth) .setImageScaleType(scaleType) .setBitmapConfig(Bitmap.Config.RGB_565) .setBitmapOptions(mBitmapOptions) .build(); ANRequest.getAsBitmap(new BitmapRequestListener() { @Override public void onResponse(Bitmap response) { onGetImageSuccess(cacheKey, response); } @Override public void onError(ANError anError) { onGetImageError(cacheKey, anError); } }); return ANRequest; } public void setBitmapDecodeOptions(BitmapFactory.Options bitmapOptions) { mBitmapOptions = bitmapOptions; } public void setBatchedResponseDelay(int newBatchedResponseDelayMs) { mBatchResponseDelayMs = newBatchedResponseDelayMs; } protected void onGetImageSuccess(String cacheKey, Bitmap response) { mCache.putBitmap(cacheKey, response); BatchedImageRequest request = mInFlightRequests.remove(cacheKey); if (request != null) { request.mResponseBitmap = response; batchResponse(cacheKey, request); } } protected void onGetImageError(String cacheKey, ANError anError) { BatchedImageRequest request = mInFlightRequests.remove(cacheKey); if (request != null) { request.setError(anError); batchResponse(cacheKey, request); } } public class ImageContainer { private Bitmap mBitmap; private final ImageListener mListener; private final String mCacheKey; private final String mRequestUrl; public ImageContainer(Bitmap bitmap, String requestUrl, String cacheKey, ImageListener listener) { mBitmap = bitmap; mRequestUrl = requestUrl; mCacheKey = cacheKey; mListener = listener; } public void cancelRequest() { if (mListener == null) { return; } BatchedImageRequest request = mInFlightRequests.get(mCacheKey); if (request != null) { boolean canceled = request.removeContainerAndCancelIfNecessary(this); if (canceled) { mInFlightRequests.remove(mCacheKey); } } else { request = mBatchedResponses.get(mCacheKey); if (request != null) { request.removeContainerAndCancelIfNecessary(this); if (request.mContainers.size() == 0) { mBatchedResponses.remove(mCacheKey); } } } } public Bitmap getBitmap() { return mBitmap; } public String getRequestUrl() { return mRequestUrl; } } private class BatchedImageRequest { private final ANRequest mRequest; private Bitmap mResponseBitmap; private ANError mANError; private final LinkedList mContainers = new LinkedList(); public BatchedImageRequest(ANRequest request, ImageContainer container) { mRequest = request; mContainers.add(container); } public void setError(ANError anError) { mANError = anError; } public ANError getError() { return mANError; } public void addContainer(ImageContainer container) { mContainers.add(container); } public boolean removeContainerAndCancelIfNecessary(ImageContainer container) { mContainers.remove(container); if (mContainers.size() == 0) { mRequest.cancel(true); if (mRequest.isCanceled()) { mRequest.destroy(); ANRequestQueue.getInstance().finish(mRequest); } return true; } return false; } } private void batchResponse(String cacheKey, BatchedImageRequest request) { mBatchedResponses.put(cacheKey, request); if (mRunnable == null) { mRunnable = new Runnable() { @Override public void run() { for (BatchedImageRequest bir : mBatchedResponses.values()) { for (ImageContainer container : bir.mContainers) { if (container.mListener == null) { continue; } if (bir.getError() == null) { container.mBitmap = bir.mResponseBitmap; container.mListener.onResponse(container, false); } else { container.mListener.onError(bir.getError()); } } } mBatchedResponses.clear(); mRunnable = null; } }; mHandler.postDelayed(mRunnable, mBatchResponseDelayMs); } } private void throwIfNotOnMainThread() { if (Looper.myLooper() != Looper.getMainLooper()) { throw new IllegalStateException("ImageLoader must be invoked from the main thread."); } } private static String getCacheKey(String url, int maxWidth, int maxHeight, ImageView.ScaleType scaleType) { return new StringBuilder(url.length() + 12).append("#W").append(maxWidth) .append("#H").append(maxHeight).append("#S").append(scaleType.ordinal()).append(url) .toString(); } } ================================================ FILE: android-networking/src/main/java/com/androidnetworking/internal/ANRequestQueue.java ================================================ /* * Copyright (C) 2016 Amit Shekhar * Copyright (C) 2011 Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.androidnetworking.internal; import com.androidnetworking.common.ANRequest; import com.androidnetworking.common.Priority; import com.androidnetworking.core.Core; import java.util.Collections; import java.util.Iterator; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; /** * Created by amitshekhar on 22/03/16. */ public class ANRequestQueue { private final Set mCurrentRequests = Collections.newSetFromMap(new ConcurrentHashMap()); private AtomicInteger mSequenceGenerator = new AtomicInteger(); private static ANRequestQueue sInstance = null; public static void initialize() { getInstance(); } public static ANRequestQueue getInstance() { if (sInstance == null) { synchronized (ANRequestQueue.class) { if (sInstance == null) { sInstance = new ANRequestQueue(); } } } return sInstance; } public interface RequestFilter { boolean apply(ANRequest request); } private void cancel(RequestFilter filter, boolean forceCancel) { try { for (Iterator iterator = mCurrentRequests.iterator(); iterator.hasNext(); ) { ANRequest request = iterator.next(); if (filter.apply(request)) { request.cancel(forceCancel); if (request.isCanceled()) { request.destroy(); iterator.remove(); } } } } catch (Exception e) { e.printStackTrace(); } } public void cancelAll(boolean forceCancel) { try { for (Iterator iterator = mCurrentRequests.iterator(); iterator.hasNext(); ) { ANRequest request = iterator.next(); request.cancel(forceCancel); if (request.isCanceled()) { request.destroy(); iterator.remove(); } } } catch (Exception e) { e.printStackTrace(); } } public void cancelRequestWithGivenTag(final Object tag, final boolean forceCancel) { try { if (tag == null) { return; } cancel(new RequestFilter() { @Override public boolean apply(ANRequest request) { return isRequestWithTheGivenTag(request, tag); } }, forceCancel); } catch (Exception e) { e.printStackTrace(); } } public int getSequenceNumber() { return mSequenceGenerator.incrementAndGet(); } public ANRequest addRequest(ANRequest request) { try { mCurrentRequests.add(request); } catch (Exception e) { e.printStackTrace(); } try { request.setSequenceNumber(getSequenceNumber()); if (request.getPriority() == Priority.IMMEDIATE) { request.setFuture(Core.getInstance() .getExecutorSupplier() .forImmediateNetworkTasks() .submit(new InternalRunnable(request))); } else { request.setFuture(Core.getInstance() .getExecutorSupplier() .forNetworkTasks() .submit(new InternalRunnable(request))); } } catch (Exception e) { e.printStackTrace(); } return request; } public void finish(ANRequest request) { try { mCurrentRequests.remove(request); } catch (Exception e) { e.printStackTrace(); } } public boolean isRequestRunning(Object tag) { try { for (ANRequest request : mCurrentRequests) { if (isRequestWithTheGivenTag(request, tag) && request.isRunning()) { return true; } } } catch (Exception e) { e.printStackTrace(); } return false; } private boolean isRequestWithTheGivenTag(ANRequest request, Object tag) { if (request.getTag() == null) { return false; } if (request.getTag() instanceof String && tag instanceof String) { final String tempRequestTag = (String) request.getTag(); final String tempTag = (String) tag; return tempRequestTag.equals(tempTag); } return request.getTag().equals(tag); } } ================================================ FILE: android-networking/src/main/java/com/androidnetworking/internal/DownloadProgressHandler.java ================================================ /* * Copyright (C) 2016 Amit Shekhar * Copyright (C) 2011 Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.androidnetworking.internal; import android.os.Handler; import android.os.Looper; import android.os.Message; import com.androidnetworking.common.ANConstants; import com.androidnetworking.interfaces.DownloadProgressListener; import com.androidnetworking.model.Progress; /** * Created by amitshekhar on 24/05/16. */ public class DownloadProgressHandler extends Handler { private final DownloadProgressListener mDownloadProgressListener; public DownloadProgressHandler(DownloadProgressListener downloadProgressListener) { super(Looper.getMainLooper()); mDownloadProgressListener = downloadProgressListener; } @Override public void handleMessage(Message msg) { switch (msg.what) { case ANConstants.UPDATE: if (mDownloadProgressListener != null) { final Progress progress = (Progress) msg.obj; mDownloadProgressListener.onProgress(progress.currentBytes, progress.totalBytes); } break; default: super.handleMessage(msg); break; } } } ================================================ FILE: android-networking/src/main/java/com/androidnetworking/internal/InternalNetworking.java ================================================ /* * Copyright (C) 2016 Amit Shekhar * Copyright (C) 2011 Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.androidnetworking.internal; /** * Created by amitshekhar on 22/03/16. */ import android.content.Context; import android.net.TrafficStats; import com.androidnetworking.common.ANConstants; import com.androidnetworking.common.ANRequest; import com.androidnetworking.common.ConnectionClassManager; import com.androidnetworking.error.ANError; import com.androidnetworking.interceptors.HttpLoggingInterceptor; import com.androidnetworking.interceptors.HttpLoggingInterceptor.Level; import com.androidnetworking.utils.Utils; import java.io.File; import java.io.IOException; import java.util.concurrent.TimeUnit; import okhttp3.Headers; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import static com.androidnetworking.common.Method.DELETE; import static com.androidnetworking.common.Method.GET; import static com.androidnetworking.common.Method.HEAD; import static com.androidnetworking.common.Method.OPTIONS; import static com.androidnetworking.common.Method.PATCH; import static com.androidnetworking.common.Method.POST; import static com.androidnetworking.common.Method.PUT; public final class InternalNetworking { private InternalNetworking() { } public static OkHttpClient sHttpClient = getClient(); public static String sUserAgent = null; public static Response performSimpleRequest(ANRequest request) throws ANError { Request okHttpRequest; Response okHttpResponse; try { Request.Builder builder = new Request.Builder().url(request.getUrl()); addHeadersToRequestBuilder(builder, request); RequestBody requestBody = null; switch (request.getMethod()) { case GET: { builder = builder.get(); break; } case POST: { requestBody = request.getRequestBody(); builder = builder.post(requestBody); break; } case PUT: { requestBody = request.getRequestBody(); builder = builder.put(requestBody); break; } case DELETE: { requestBody = request.getRequestBody(); builder = builder.delete(requestBody); break; } case HEAD: { builder = builder.head(); break; } case OPTIONS: { builder = builder.method(ANConstants.OPTIONS, null); break; } case PATCH: { requestBody = request.getRequestBody(); builder = builder.patch(requestBody); break; } } if (request.getCacheControl() != null) { builder.cacheControl(request.getCacheControl()); } okHttpRequest = builder.build(); if (request.getOkHttpClient() != null) { request.setCall(request.getOkHttpClient().newBuilder().cache(sHttpClient.cache()).build().newCall(okHttpRequest)); } else { request.setCall(sHttpClient.newCall(okHttpRequest)); } final long startTime = System.currentTimeMillis(); final long startBytes = TrafficStats.getTotalRxBytes(); okHttpResponse = request.getCall().execute(); final long timeTaken = System.currentTimeMillis() - startTime; if (okHttpResponse.cacheResponse() == null) { final long finalBytes = TrafficStats.getTotalRxBytes(); final long diffBytes; if (startBytes == TrafficStats.UNSUPPORTED || finalBytes == TrafficStats.UNSUPPORTED) { diffBytes = okHttpResponse.body().contentLength(); } else { diffBytes = finalBytes - startBytes; } ConnectionClassManager.getInstance().updateBandwidth(diffBytes, timeTaken); Utils.sendAnalytics(request.getAnalyticsListener(), timeTaken, (requestBody != null && requestBody.contentLength() != 0) ? requestBody.contentLength() : -1, okHttpResponse.body().contentLength(), false); } else if (request.getAnalyticsListener() != null) { if (okHttpResponse.networkResponse() == null) { Utils.sendAnalytics(request.getAnalyticsListener(), timeTaken, 0, 0, true); } else { Utils.sendAnalytics(request.getAnalyticsListener(), timeTaken, (requestBody != null && requestBody.contentLength() != 0) ? requestBody.contentLength() : -1, 0, true); } } } catch (IOException ioe) { throw new ANError(ioe); } return okHttpResponse; } public static Response performDownloadRequest(final ANRequest request) throws ANError { Request okHttpRequest; Response okHttpResponse; try { Request.Builder builder = new Request.Builder().url(request.getUrl()); addHeadersToRequestBuilder(builder, request); builder = builder.get(); if (request.getCacheControl() != null) { builder.cacheControl(request.getCacheControl()); } okHttpRequest = builder.build(); OkHttpClient okHttpClient; if (request.getOkHttpClient() != null) { okHttpClient = request.getOkHttpClient().newBuilder().cache(sHttpClient.cache()) .addNetworkInterceptor(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Response originalResponse = chain.proceed(chain.request()); return originalResponse.newBuilder() .body(new ResponseProgressBody(originalResponse.body(), request.getDownloadProgressListener())) .build(); } }).build(); } else { okHttpClient = sHttpClient.newBuilder() .addNetworkInterceptor(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Response originalResponse = chain.proceed(chain.request()); return originalResponse.newBuilder() .body(new ResponseProgressBody(originalResponse.body(), request.getDownloadProgressListener())) .build(); } }).build(); } request.setCall(okHttpClient.newCall(okHttpRequest)); final long startTime = System.currentTimeMillis(); final long startBytes = TrafficStats.getTotalRxBytes(); okHttpResponse = request.getCall().execute(); Utils.saveFile(okHttpResponse, request.getDirPath(), request.getFileName()); final long timeTaken = System.currentTimeMillis() - startTime; if (okHttpResponse.cacheResponse() == null) { final long finalBytes = TrafficStats.getTotalRxBytes(); final long diffBytes; if (startBytes == TrafficStats.UNSUPPORTED || finalBytes == TrafficStats.UNSUPPORTED) { diffBytes = okHttpResponse.body().contentLength(); } else { diffBytes = finalBytes - startBytes; } ConnectionClassManager.getInstance().updateBandwidth(diffBytes, timeTaken); Utils.sendAnalytics(request.getAnalyticsListener(), timeTaken, -1, okHttpResponse.body().contentLength(), false); } else if (request.getAnalyticsListener() != null) { Utils.sendAnalytics(request.getAnalyticsListener(), timeTaken, -1, 0, true); } } catch (IOException ioe) { try { File destinationFile = new File(request.getDirPath() + File.separator + request.getFileName()); if (destinationFile.exists()) { destinationFile.delete(); } } catch (Exception e) { e.printStackTrace(); } throw new ANError(ioe); } return okHttpResponse; } public static Response performUploadRequest(ANRequest request) throws ANError { Request okHttpRequest; Response okHttpResponse; try { Request.Builder builder = new Request.Builder().url(request.getUrl()); addHeadersToRequestBuilder(builder, request); final RequestBody requestBody = request.getMultiPartRequestBody(); final long requestBodyLength = requestBody.contentLength(); builder = builder.post(new RequestProgressBody(requestBody, request.getUploadProgressListener())); if (request.getCacheControl() != null) { builder.cacheControl(request.getCacheControl()); } okHttpRequest = builder.build(); if (request.getOkHttpClient() != null) { request.setCall(request.getOkHttpClient() .newBuilder() .cache(sHttpClient.cache()) .build() .newCall(okHttpRequest)); } else { request.setCall(sHttpClient.newCall(okHttpRequest)); } final long startTime = System.currentTimeMillis(); okHttpResponse = request.getCall().execute(); final long timeTaken = System.currentTimeMillis() - startTime; if (request.getAnalyticsListener() != null) { if (okHttpResponse.cacheResponse() == null) { Utils.sendAnalytics(request.getAnalyticsListener(), timeTaken, requestBodyLength, okHttpResponse.body().contentLength(), false); } else { if (okHttpResponse.networkResponse() == null) { Utils.sendAnalytics(request.getAnalyticsListener(), timeTaken, 0, 0, true); } else { Utils.sendAnalytics(request.getAnalyticsListener(), timeTaken, requestBodyLength != 0 ? requestBodyLength : -1, 0, true); } } } } catch (IOException ioe) { throw new ANError(ioe); } return okHttpResponse; } public static OkHttpClient getClient() { if (sHttpClient == null) { return getDefaultClient(); } return sHttpClient; } public static void addHeadersToRequestBuilder(Request.Builder builder, ANRequest request) { if (request.getUserAgent() != null) { builder.addHeader(ANConstants.USER_AGENT, request.getUserAgent()); } else if (sUserAgent != null) { request.setUserAgent(sUserAgent); builder.addHeader(ANConstants.USER_AGENT, sUserAgent); } Headers requestHeaders = request.getHeaders(); if (requestHeaders != null) { builder.headers(requestHeaders); if (request.getUserAgent() != null && !requestHeaders.names().contains(ANConstants.USER_AGENT)) { builder.addHeader(ANConstants.USER_AGENT, request.getUserAgent()); } } } public static OkHttpClient getDefaultClient() { return new OkHttpClient().newBuilder() .connectTimeout(60, TimeUnit.SECONDS) .readTimeout(60, TimeUnit.SECONDS) .writeTimeout(60, TimeUnit.SECONDS) .build(); } public static void setClientWithCache(Context context) { sHttpClient = new OkHttpClient().newBuilder() .cache(Utils.getCache(context, ANConstants.MAX_CACHE_SIZE, ANConstants.CACHE_DIR_NAME)) .connectTimeout(60, TimeUnit.SECONDS) .readTimeout(60, TimeUnit.SECONDS) .writeTimeout(60, TimeUnit.SECONDS) .build(); } public static void setUserAgent(String userAgent) { sUserAgent = userAgent; } public static void setClient(OkHttpClient okHttpClient) { sHttpClient = okHttpClient; } public static void enableLogging(Level level) { HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); logging.setLevel(level); sHttpClient = getClient() .newBuilder() .addInterceptor(logging) .build(); } } ================================================ FILE: android-networking/src/main/java/com/androidnetworking/internal/InternalRunnable.java ================================================ /* * Copyright (C) 2016 Amit Shekhar * Copyright (C) 2011 Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.androidnetworking.internal; import com.androidnetworking.common.ANRequest; import com.androidnetworking.common.ANResponse; import com.androidnetworking.common.Priority; import com.androidnetworking.common.ResponseType; import com.androidnetworking.core.Core; import com.androidnetworking.error.ANError; import com.androidnetworking.utils.SourceCloseUtil; import com.androidnetworking.utils.Utils; import okhttp3.Response; import static com.androidnetworking.common.RequestType.DOWNLOAD; import static com.androidnetworking.common.RequestType.MULTIPART; import static com.androidnetworking.common.RequestType.SIMPLE; /** * Created by amitshekhar on 22/03/16. */ public class InternalRunnable implements Runnable { private final Priority priority; public final int sequence; public final ANRequest request; public InternalRunnable(ANRequest request) { this.request = request; this.sequence = request.getSequenceNumber(); this.priority = request.getPriority(); } @Override public void run() { request.setRunning(true); switch (request.getRequestType()) { case SIMPLE: executeSimpleRequest(); break; case DOWNLOAD: executeDownloadRequest(); break; case MULTIPART: executeUploadRequest(); break; } request.setRunning(false); } private void executeSimpleRequest() { Response okHttpResponse = null; try { okHttpResponse = InternalNetworking.performSimpleRequest(request); if (okHttpResponse == null) { deliverError(request, Utils.getErrorForConnection(new ANError())); return; } if (request.getResponseAs() == ResponseType.OK_HTTP_RESPONSE) { request.deliverOkHttpResponse(okHttpResponse); return; } if (okHttpResponse.code() >= 400) { deliverError(request, Utils.getErrorForServerResponse(new ANError(okHttpResponse), request, okHttpResponse.code())); return; } ANResponse response = request.parseResponse(okHttpResponse); if (!response.isSuccess()) { deliverError(request, response.getError()); return; } response.setOkHttpResponse(okHttpResponse); request.deliverResponse(response); } catch (Exception e) { deliverError(request, Utils.getErrorForConnection(new ANError(e))); } finally { SourceCloseUtil.close(okHttpResponse, request); } } private void executeDownloadRequest() { Response okHttpResponse; try { okHttpResponse = InternalNetworking.performDownloadRequest(request); if (okHttpResponse == null) { deliverError(request, Utils.getErrorForConnection(new ANError())); return; } if (okHttpResponse.code() >= 400) { deliverError(request, Utils.getErrorForServerResponse(new ANError(okHttpResponse), request, okHttpResponse.code())); return; } request.updateDownloadCompletion(); } catch (Exception e) { deliverError(request, Utils.getErrorForConnection(new ANError(e))); } } private void executeUploadRequest() { Response okHttpResponse = null; try { okHttpResponse = InternalNetworking.performUploadRequest(request); if (okHttpResponse == null) { deliverError(request, Utils.getErrorForConnection(new ANError())); return; } if (request.getResponseAs() == ResponseType.OK_HTTP_RESPONSE) { request.deliverOkHttpResponse(okHttpResponse); return; } if (okHttpResponse.code() >= 400) { deliverError(request, Utils.getErrorForServerResponse(new ANError(okHttpResponse), request, okHttpResponse.code())); return; } ANResponse response = request.parseResponse(okHttpResponse); if (!response.isSuccess()) { deliverError(request, response.getError()); return; } response.setOkHttpResponse(okHttpResponse); request.deliverResponse(response); } catch (Exception e) { deliverError(request, Utils.getErrorForConnection(new ANError(e))); } finally { SourceCloseUtil.close(okHttpResponse, request); } } public Priority getPriority() { return priority; } private void deliverError(final ANRequest request, final ANError anError) { Core.getInstance().getExecutorSupplier().forMainThreadTasks().execute(new Runnable() { public void run() { request.deliverError(anError); request.finish(); } }); } } ================================================ FILE: android-networking/src/main/java/com/androidnetworking/internal/RequestProgressBody.java ================================================ /* * Copyright (C) 2016 Amit Shekhar * Copyright (C) 2011 Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.androidnetworking.internal; import com.androidnetworking.common.ANConstants; import com.androidnetworking.interfaces.UploadProgressListener; import com.androidnetworking.model.Progress; import java.io.IOException; import okhttp3.MediaType; import okhttp3.RequestBody; import okio.Buffer; import okio.BufferedSink; import okio.ForwardingSink; import okio.Okio; import okio.Sink; /** * Created by amitshekhar on 21/04/16. */ public class RequestProgressBody extends RequestBody { private final RequestBody requestBody; private BufferedSink bufferedSink; private UploadProgressHandler uploadProgressHandler; public RequestProgressBody(RequestBody requestBody, UploadProgressListener uploadProgressListener) { this.requestBody = requestBody; if (uploadProgressListener != null) { this.uploadProgressHandler = new UploadProgressHandler(uploadProgressListener); } } public MediaType contentType() { return requestBody.contentType(); } @Override public long contentLength() throws IOException { return requestBody.contentLength(); } @Override public void writeTo(BufferedSink sink) throws IOException { if (bufferedSink == null) { bufferedSink = Okio.buffer(sink(sink)); } requestBody.writeTo(bufferedSink); bufferedSink.flush(); } private Sink sink(Sink sink) { return new ForwardingSink(sink) { long bytesWritten = 0L; long contentLength = 0L; @Override public void write(Buffer source, long byteCount) throws IOException { super.write(source, byteCount); if (contentLength == 0) { contentLength = contentLength(); } bytesWritten += byteCount; if (uploadProgressHandler != null) { uploadProgressHandler.obtainMessage(ANConstants.UPDATE, new Progress(bytesWritten, contentLength)).sendToTarget(); } } }; } } ================================================ FILE: android-networking/src/main/java/com/androidnetworking/internal/ResponseProgressBody.java ================================================ /* * Copyright (C) 2016 Amit Shekhar * Copyright (C) 2011 Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.androidnetworking.internal; import com.androidnetworking.common.ANConstants; import com.androidnetworking.interfaces.DownloadProgressListener; import com.androidnetworking.model.Progress; import java.io.IOException; import okhttp3.MediaType; import okhttp3.ResponseBody; import okio.Buffer; import okio.BufferedSource; import okio.ForwardingSource; import okio.Okio; import okio.Source; /** * Created by amitshekhar on 24/05/16. */ public class ResponseProgressBody extends ResponseBody { private final ResponseBody mResponseBody; private BufferedSource bufferedSource; private DownloadProgressHandler downloadProgressHandler; public ResponseProgressBody(ResponseBody responseBody, DownloadProgressListener downloadProgressListener) { this.mResponseBody = responseBody; if (downloadProgressListener != null) { this.downloadProgressHandler = new DownloadProgressHandler(downloadProgressListener); } } @Override public MediaType contentType() { return mResponseBody.contentType(); } @Override public long contentLength() { return mResponseBody.contentLength(); } @Override public BufferedSource source() { if (bufferedSource == null) { bufferedSource = Okio.buffer(source(mResponseBody.source())); } return bufferedSource; } private Source source(Source source) { return new ForwardingSource(source) { long totalBytesRead; @Override public long read(Buffer sink, long byteCount) throws IOException { long bytesRead = super.read(sink, byteCount); totalBytesRead += ((bytesRead != -1) ? bytesRead : 0); if (downloadProgressHandler != null) { downloadProgressHandler .obtainMessage(ANConstants.UPDATE, new Progress(totalBytesRead, mResponseBody.contentLength())) .sendToTarget(); } return bytesRead; } }; } } ================================================ FILE: android-networking/src/main/java/com/androidnetworking/internal/SynchronousCall.java ================================================ /* * * * Copyright (C) 2016 Amit Shekhar * * Copyright (C) 2011 Android Open Source Project * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * */ package com.androidnetworking.internal; import com.androidnetworking.common.ANConstants; import com.androidnetworking.common.ANRequest; import com.androidnetworking.common.ANResponse; import com.androidnetworking.common.ResponseType; import com.androidnetworking.error.ANError; import com.androidnetworking.utils.SourceCloseUtil; import com.androidnetworking.utils.Utils; import okhttp3.Response; import static com.androidnetworking.common.RequestType.DOWNLOAD; import static com.androidnetworking.common.RequestType.MULTIPART; import static com.androidnetworking.common.RequestType.SIMPLE; /** * Created by amitshekhar on 14/09/16. */ @SuppressWarnings("unchecked") public final class SynchronousCall { private SynchronousCall() { } public static ANResponse execute(ANRequest request) { switch (request.getRequestType()) { case SIMPLE: return executeSimpleRequest(request); case DOWNLOAD: return executeDownloadRequest(request); case MULTIPART: return executeUploadRequest(request); } return new ANResponse<>(new ANError()); } private static ANResponse executeSimpleRequest(ANRequest request) { Response okHttpResponse = null; try { okHttpResponse = InternalNetworking.performSimpleRequest(request); if (okHttpResponse == null) { return new ANResponse<>(Utils.getErrorForConnection(new ANError())); } if (request.getResponseAs() == ResponseType.OK_HTTP_RESPONSE) { ANResponse response = new ANResponse(okHttpResponse); response.setOkHttpResponse(okHttpResponse); return response; } if (okHttpResponse.code() >= 400) { ANResponse response = new ANResponse<>(Utils.getErrorForServerResponse(new ANError(okHttpResponse), request, okHttpResponse.code())); response.setOkHttpResponse(okHttpResponse); return response; } ANResponse response = request.parseResponse(okHttpResponse); response.setOkHttpResponse(okHttpResponse); return response; } catch (ANError se) { return new ANResponse<>(Utils.getErrorForConnection(new ANError(se))); } catch (Exception e) { return new ANResponse<>(Utils.getErrorForConnection(new ANError(e))); } finally { SourceCloseUtil.close(okHttpResponse, request); } } private static ANResponse executeDownloadRequest(ANRequest request) { Response okHttpResponse; try { okHttpResponse = InternalNetworking.performDownloadRequest(request); if (okHttpResponse == null) { return new ANResponse<>(Utils.getErrorForConnection(new ANError())); } if (okHttpResponse.code() >= 400) { ANResponse response = new ANResponse<>(Utils.getErrorForServerResponse(new ANError(okHttpResponse), request, okHttpResponse.code())); response.setOkHttpResponse(okHttpResponse); return response; } ANResponse response = new ANResponse(ANConstants.SUCCESS); response.setOkHttpResponse(okHttpResponse); return response; } catch (ANError se) { return new ANResponse<>(Utils.getErrorForConnection(new ANError(se))); } catch (Exception e) { return new ANResponse<>(Utils.getErrorForConnection(new ANError(e))); } } private static ANResponse executeUploadRequest(ANRequest request) { Response okHttpResponse = null; try { okHttpResponse = InternalNetworking.performUploadRequest(request); if (okHttpResponse == null) { return new ANResponse<>(Utils.getErrorForConnection(new ANError())); } if (request.getResponseAs() == ResponseType.OK_HTTP_RESPONSE) { ANResponse response = new ANResponse(okHttpResponse); response.setOkHttpResponse(okHttpResponse); return response; } if (okHttpResponse.code() >= 400) { ANResponse response = new ANResponse<>(Utils.getErrorForServerResponse(new ANError(okHttpResponse), request, okHttpResponse.code())); response.setOkHttpResponse(okHttpResponse); return response; } ANResponse response = request.parseResponse(okHttpResponse); response.setOkHttpResponse(okHttpResponse); return response; } catch (ANError se) { return new ANResponse<>(Utils.getErrorForConnection(se)); } catch (Exception e) { return new ANResponse<>(Utils.getErrorForConnection(new ANError(e))); } finally { SourceCloseUtil.close(okHttpResponse, request); } } } ================================================ FILE: android-networking/src/main/java/com/androidnetworking/internal/UploadProgressHandler.java ================================================ /* * Copyright (C) 2016 Amit Shekhar * Copyright (C) 2011 Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.androidnetworking.internal; import android.os.Handler; import android.os.Looper; import android.os.Message; import com.androidnetworking.common.ANConstants; import com.androidnetworking.interfaces.UploadProgressListener; import com.androidnetworking.model.Progress; /** * Created by amitshekhar on 24/05/16. */ public class UploadProgressHandler extends Handler { private final UploadProgressListener mUploadProgressListener; public UploadProgressHandler(UploadProgressListener uploadProgressListener) { super(Looper.getMainLooper()); mUploadProgressListener = uploadProgressListener; } @Override public void handleMessage(Message msg) { switch (msg.what) { case ANConstants.UPDATE: if (mUploadProgressListener != null) { final Progress progress = (Progress) msg.obj; mUploadProgressListener.onProgress(progress.currentBytes, progress.totalBytes); } break; default: super.handleMessage(msg); break; } } } ================================================ FILE: android-networking/src/main/java/com/androidnetworking/model/MultipartFileBody.java ================================================ package com.androidnetworking.model; import java.io.File; public class MultipartFileBody { public final File file; public final String contentType; public MultipartFileBody(File file, String contentType) { this.file = file; this.contentType = contentType; } } ================================================ FILE: android-networking/src/main/java/com/androidnetworking/model/MultipartStringBody.java ================================================ package com.androidnetworking.model; public class MultipartStringBody { public final String value; public final String contentType; public MultipartStringBody(String value, String contentType) { this.value = value; this.contentType = contentType; } } ================================================ FILE: android-networking/src/main/java/com/androidnetworking/model/Progress.java ================================================ /* * Copyright (C) 2016 Amit Shekhar * Copyright (C) 2011 Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.androidnetworking.model; import java.io.Serializable; /** * Created by amitshekhar on 24/05/16. */ public class Progress implements Serializable { public long currentBytes; public long totalBytes; public Progress(long currentBytes, long totalBytes) { this.currentBytes = currentBytes; this.totalBytes = totalBytes; } } ================================================ FILE: android-networking/src/main/java/com/androidnetworking/utils/ParseUtil.java ================================================ /* * * * Copyright (C) 2016 Amit Shekhar * * Copyright (C) 2011 Android Open Source Project * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * */ package com.androidnetworking.utils; import com.androidnetworking.gsonparserfactory.GsonParserFactory; import com.androidnetworking.interfaces.Parser; import com.google.gson.Gson; /** * Created by amitshekhar on 15/09/16. */ public class ParseUtil { private static Parser.Factory mParserFactory; public static void setParserFactory(Parser.Factory parserFactory) { mParserFactory = parserFactory; } public static Parser.Factory getParserFactory() { if (mParserFactory == null) { mParserFactory = new GsonParserFactory(new Gson()); } return mParserFactory; } public static void shutDown() { mParserFactory = null; } } ================================================ FILE: android-networking/src/main/java/com/androidnetworking/utils/SourceCloseUtil.java ================================================ /* * * * Copyright (C) 2016 Amit Shekhar * * Copyright (C) 2011 Android Open Source Project * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * */ package com.androidnetworking.utils; import com.androidnetworking.common.ANRequest; import com.androidnetworking.common.ResponseType; import okhttp3.Response; /** * Created by amitshekhar on 15/09/16. */ public final class SourceCloseUtil { private SourceCloseUtil() { } public static void close(Response response, ANRequest request) { if (request.getResponseAs() != ResponseType.OK_HTTP_RESPONSE && response != null && response.body() != null && response.body().source() != null) { try { response.body().source().close(); } catch (Exception ignore) { } } } } ================================================ FILE: android-networking/src/main/java/com/androidnetworking/utils/Utils.java ================================================ /* * Copyright (C) 2016 Amit Shekhar * Copyright (C) 2011 Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.androidnetworking.utils; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.widget.ImageView; import com.androidnetworking.common.ANConstants; import com.androidnetworking.common.ANRequest; import com.androidnetworking.common.ANResponse; import com.androidnetworking.core.Core; import com.androidnetworking.error.ANError; import com.androidnetworking.interfaces.AnalyticsListener; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.FileNameMap; import java.net.URLConnection; import okhttp3.Cache; import okhttp3.Response; import okio.Okio; /** * Created by amitshekhar on 25/03/16. */ public class Utils { public static File getDiskCacheDir(Context context, String uniqueName) { return new File(context.getCacheDir(), uniqueName); } public static Cache getCache(Context context, int maxCacheSize, String uniqueName) { return new Cache(getDiskCacheDir(context, uniqueName), maxCacheSize); } public static String getMimeType(String path) { FileNameMap fileNameMap = URLConnection.getFileNameMap(); String contentTypeFor = fileNameMap.getContentTypeFor(path); if (contentTypeFor == null) { contentTypeFor = "application/octet-stream"; } return contentTypeFor; } public static ANResponse decodeBitmap(Response response, int maxWidth, int maxHeight, Bitmap.Config decodeConfig, ImageView.ScaleType scaleType) { return decodeBitmap(response, maxWidth, maxHeight, decodeConfig, new BitmapFactory.Options(), scaleType); } public static ANResponse decodeBitmap(Response response, int maxWidth, int maxHeight, Bitmap.Config decodeConfig, BitmapFactory.Options decodeOptions, ImageView.ScaleType scaleType) { byte[] data = new byte[0]; try { data = Okio.buffer(response.body().source()).readByteArray(); } catch (IOException e) { e.printStackTrace(); } Bitmap bitmap = null; if (maxWidth == 0 && maxHeight == 0) { decodeOptions.inPreferredConfig = decodeConfig; bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, decodeOptions); } else { decodeOptions.inJustDecodeBounds = true; BitmapFactory.decodeByteArray(data, 0, data.length, decodeOptions); int actualWidth = decodeOptions.outWidth; int actualHeight = decodeOptions.outHeight; int desiredWidth = getResizedDimension(maxWidth, maxHeight, actualWidth, actualHeight, scaleType); int desiredHeight = getResizedDimension(maxHeight, maxWidth, actualHeight, actualWidth, scaleType); decodeOptions.inJustDecodeBounds = false; decodeOptions.inSampleSize = findBestSampleSize(actualWidth, actualHeight, desiredWidth, desiredHeight); Bitmap tempBitmap = BitmapFactory.decodeByteArray(data, 0, data.length, decodeOptions); if (tempBitmap != null && (tempBitmap.getWidth() > desiredWidth || tempBitmap.getHeight() > desiredHeight)) { bitmap = Bitmap.createScaledBitmap(tempBitmap, desiredWidth, desiredHeight, true); tempBitmap.recycle(); } else { bitmap = tempBitmap; } } if (bitmap == null) { return ANResponse.failed(Utils.getErrorForParse(new ANError(response))); } else { return ANResponse.success(bitmap); } } private static int getResizedDimension(int maxPrimary, int maxSecondary, int actualPrimary, int actualSecondary, ImageView.ScaleType scaleType) { if ((maxPrimary == 0) && (maxSecondary == 0)) { return actualPrimary; } if (scaleType == ImageView.ScaleType.FIT_XY) { if (maxPrimary == 0) { return actualPrimary; } return maxPrimary; } if (maxPrimary == 0) { double ratio = (double) maxSecondary / (double) actualSecondary; return (int) (actualPrimary * ratio); } if (maxSecondary == 0) { return maxPrimary; } double ratio = (double) actualSecondary / (double) actualPrimary; int resized = maxPrimary; if (scaleType == ImageView.ScaleType.CENTER_CROP) { if ((resized * ratio) < maxSecondary) { resized = (int) (maxSecondary / ratio); } return resized; } if ((resized * ratio) > maxSecondary) { resized = (int) (maxSecondary / ratio); } return resized; } public static int findBestSampleSize(int actualWidth, int actualHeight, int desiredWidth, int desiredHeight) { double wr = (double) actualWidth / desiredWidth; double hr = (double) actualHeight / desiredHeight; double ratio = Math.min(wr, hr); float n = 1.0f; while ((n * 2) <= ratio) { n *= 2; } return (int) n; } public static void saveFile(Response response, String dirPath, String fileName) throws IOException { InputStream is = null; byte[] buf = new byte[2048]; int len; FileOutputStream fos = null; try { is = response.body().byteStream(); File dir = new File(dirPath); if (!dir.exists()) { dir.mkdirs(); } File file = new File(dir, fileName); fos = new FileOutputStream(file); while ((len = is.read(buf)) != -1) { fos.write(buf, 0, len); } fos.flush(); } finally { try { if (is != null) is.close(); } catch (IOException e) { e.printStackTrace(); } try { if (fos != null) fos.close(); } catch (IOException e) { e.printStackTrace(); } } } public static void sendAnalytics(final AnalyticsListener analyticsListener, final long timeTakenInMillis, final long bytesSent, final long bytesReceived, final boolean isFromCache) { Core.getInstance().getExecutorSupplier().forMainThreadTasks().execute(new Runnable() { @Override public void run() { if (analyticsListener != null) { analyticsListener.onReceived(timeTakenInMillis, bytesSent, bytesReceived, isFromCache); } } }); } public static ANError getErrorForConnection(ANError error) { error.setErrorDetail(ANConstants.CONNECTION_ERROR); error.setErrorCode(0); return error; } public static ANError getErrorForServerResponse(ANError error, ANRequest request, int code) { error = request.parseNetworkError(error); error.setErrorCode(code); error.setErrorDetail(ANConstants.RESPONSE_FROM_SERVER_ERROR); return error; } public static ANError getErrorForParse(ANError error) { error.setErrorCode(0); error.setErrorDetail(ANConstants.PARSE_ERROR); return error; } } ================================================ FILE: android-networking/src/main/java/com/androidnetworking/widget/ANImageView.java ================================================ /* * Copyright (C) 2016 Amit Shekhar * Copyright (C) 2011 Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.androidnetworking.widget; import android.content.Context; import android.support.v7.widget.AppCompatImageView; import android.text.TextUtils; import android.util.AttributeSet; import android.view.ViewGroup; import android.widget.ImageView; import com.androidnetworking.error.ANError; import com.androidnetworking.internal.ANImageLoader; /** * Created by amitshekhar on 23/03/16. */ public class ANImageView extends AppCompatImageView { private String mUrl; private int mDefaultImageId; private int mErrorImageId; private ANImageLoader.ImageContainer mImageContainer; public ANImageView(Context context) { this(context, null); } public ANImageView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public ANImageView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public void setImageUrl(String url) { mUrl = url; loadImageIfNecessary(false); } public void setDefaultImageResId(int defaultImage) { mDefaultImageId = defaultImage; } public void setErrorImageResId(int errorImage) { mErrorImageId = errorImage; } void loadImageIfNecessary(final boolean isInLayoutPass) { int width = getWidth(); int height = getHeight(); ImageView.ScaleType scaleType = getScaleType(); boolean wrapWidth = false, wrapHeight = false; if (getLayoutParams() != null) { wrapWidth = getLayoutParams().width == ViewGroup.LayoutParams.WRAP_CONTENT; wrapHeight = getLayoutParams().height == ViewGroup.LayoutParams.WRAP_CONTENT; } boolean isFullyWrapContent = wrapWidth && wrapHeight; if (width == 0 && height == 0 && !isFullyWrapContent) { return; } if (TextUtils.isEmpty(mUrl)) { if (mImageContainer != null) { mImageContainer.cancelRequest(); mImageContainer = null; } setDefaultImageOrNull(); return; } if (mImageContainer != null && mImageContainer.getRequestUrl() != null) { if (mImageContainer.getRequestUrl().equals(mUrl)) { return; } else { mImageContainer.cancelRequest(); setDefaultImageOrNull(); } } int maxWidth = wrapWidth ? 0 : width; int maxHeight = wrapHeight ? 0 : height; ANImageLoader.ImageContainer newContainer = ANImageLoader.getInstance().get(mUrl, new ANImageLoader.ImageListener() { @Override public void onResponse(final ANImageLoader.ImageContainer response, boolean isImmediate) { if (isImmediate && isInLayoutPass) { post(new Runnable() { @Override public void run() { onResponse(response, false); } }); return; } if (response.getBitmap() != null) { setImageBitmap(response.getBitmap()); } else if (mDefaultImageId != 0) { setImageResource(mDefaultImageId); } } @Override public void onError(ANError error) { if (mErrorImageId != 0) { setImageResource(mErrorImageId); } } }, maxWidth, maxHeight, scaleType); mImageContainer = newContainer; } private void setDefaultImageOrNull() { if (mDefaultImageId != 0) { setImageResource(mDefaultImageId); } else { setImageBitmap(null); } } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); loadImageIfNecessary(true); } @Override protected void onDetachedFromWindow() { if (mImageContainer != null) { mImageContainer.cancelRequest(); setImageBitmap(null); mImageContainer = null; } super.onDetachedFromWindow(); } @Override protected void drawableStateChanged() { super.drawableStateChanged(); invalidate(); } } ================================================ FILE: android-networking/src/main/res/values/strings.xml ================================================ Android Networking ================================================ FILE: android-networking/src/test/java/com/androidnetworking/ExampleUnitTest.java ================================================ /* * Copyright (C) 2016 Amit Shekhar * Copyright (C) 2011 Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.androidnetworking; import org.junit.Test; import static org.junit.Assert.*; /** * To work on unit tests, switch the Test Artifact in the Build Variants view. */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } } ================================================ FILE: app/.gitignore ================================================ /build ================================================ FILE: app/build.gradle ================================================ /* * Copyright (C) 2016 Amit Shekhar * Copyright (C) 2011 Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ apply plugin: 'com.android.application' android { compileSdkVersion rootProject.ext.compileSdkVersion buildToolsVersion rootProject.ext.buildToolsVersion defaultConfig { applicationId "com.networking" minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) testImplementation "junit:junit:$rootProject.ext.jUnitVersion" implementation "com.android.support:appcompat-v7:$rootProject.ext.supportAppCompatVersion" implementation project(':android-networking') } ================================================ FILE: app/proguard-rules.pro ================================================ # Add project specific ProGuard rules here. # By default, the flags in this file are appended to flags specified # in /Users/amitshekhar/Library/Android/sdk/tools/proguard/proguard-android.txt # You can edit the include path and order by changing the proguardFiles # directive in build.gradle. # # For more details, see # http://developer.android.com/guide/developing/tools/proguard.html # Add any project specific keep options here: # If your project uses WebView with JS, uncomment the following # and specify the fully qualified class name to the JavaScript interface # class: #-keepclassmembers class fqcn.of.javascript.interface.for.webview { # public *; #} ================================================ FILE: app/src/androidTest/java/com/androidnetworking/ApplicationTest.java ================================================ /* * Copyright (C) 2016 Amit Shekhar * Copyright (C) 2011 Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.androidnetworking; import android.app.Application; import android.test.ApplicationTestCase; /** * Testing Fundamentals */ public class ApplicationTest extends ApplicationTestCase { public ApplicationTest() { super(Application.class); } } ================================================ FILE: app/src/main/AndroidManifest.xml ================================================ ================================================ FILE: app/src/main/java/com/networking/ApiEndPoint.java ================================================ /* * Copyright (C) 2016 Amit Shekhar * Copyright (C) 2011 Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.networking; /** * Created by amitshekhar on 29/03/16. */ public class ApiEndPoint { public static final String BASE_URL = "https://fierce-cove-29863.herokuapp.com"; public static final String GET_JSON_ARRAY = "/getAllUsers/{pageNumber}"; public static final String GET_JSON_OBJECT = "/getAnUserDetail/{userId}"; public static final String CHECK_FOR_HEADER = "/checkForHeader"; public static final String POST_CREATE_AN_USER = "/createAnUser"; public static final String UPLOAD_IMAGE = "/uploadImage"; } ================================================ FILE: app/src/main/java/com/networking/ApiTestActivity.java ================================================ /* * Copyright (C) 2016 Amit Shekhar * Copyright (C) 2011 Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.networking; import android.os.Bundle; import android.os.Environment; import android.os.Looper; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import com.androidnetworking.AndroidNetworking; import com.androidnetworking.common.ANRequest; import com.androidnetworking.common.ANResponse; import com.androidnetworking.common.Priority; import com.androidnetworking.error.ANError; import com.androidnetworking.interfaces.AnalyticsListener; import com.androidnetworking.interfaces.DownloadListener; import com.androidnetworking.interfaces.DownloadProgressListener; import com.androidnetworking.interfaces.JSONArrayRequestListener; import com.androidnetworking.interfaces.JSONObjectRequestListener; import com.androidnetworking.interfaces.OkHttpResponseListener; import com.androidnetworking.interfaces.ParsedRequestListener; import com.androidnetworking.interfaces.UploadProgressListener; import com.networking.model.User; import com.networking.utils.Utils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.io.IOException; import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import okhttp3.OkHttpClient; import okhttp3.Response; /** * Created by amitshekhar on 30/03/16. */ public class ApiTestActivity extends AppCompatActivity { private static final String TAG = ApiTestActivity.class.getSimpleName(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_api_test); } public void prefetch(View view) { AndroidNetworking.get(ApiEndPoint.BASE_URL + ApiEndPoint.GET_JSON_ARRAY) .addPathParameter("pageNumber", "0") .addQueryParameter("limit", "3") .setTag(this) .setPriority(Priority.LOW) .build() .setAnalyticsListener(new AnalyticsListener() { @Override public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) { Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis); Log.d(TAG, " bytesSent : " + bytesSent); Log.d(TAG, " bytesReceived : " + bytesReceived); Log.d(TAG, " isFromCache : " + isFromCache); } }) .prefetch(); } public void prefetchDownload(View view) { String url = "http://www.colorado.edu/conflict/peace/download/peace_problem.ZIP"; AndroidNetworking.download(url, Utils.getRootDirPath(getApplicationContext()), "file1.zip") .setPriority(Priority.HIGH) .setTag(this) .build() .setAnalyticsListener(new AnalyticsListener() { @Override public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) { Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis); Log.d(TAG, " bytesSent : " + bytesSent); Log.d(TAG, " bytesReceived : " + bytesReceived); Log.d(TAG, " isFromCache : " + isFromCache); } }) .prefetch(); } public void getAllUsers(View view) { AndroidNetworking.get(ApiEndPoint.BASE_URL + ApiEndPoint.GET_JSON_ARRAY) .addPathParameter("pageNumber", "0") .addQueryParameter("limit", "3") .setTag(this) .setPriority(Priority.LOW) .build() .setAnalyticsListener(new AnalyticsListener() { @Override public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) { Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis); Log.d(TAG, " bytesSent : " + bytesSent); Log.d(TAG, " bytesReceived : " + bytesReceived); Log.d(TAG, " isFromCache : " + isFromCache); } }) .getAsObjectList(User.class, new ParsedRequestListener>() { @Override public void onResponse(List users) { Log.d(TAG, "userList size : " + users.size()); for (User user : users) { Log.d(TAG, "id : " + user.id); Log.d(TAG, "firstname : " + user.firstname); Log.d(TAG, "lastname : " + user.lastname); } } @Override public void onError(ANError anError) { Utils.logError(TAG, anError); } }); } public void getAnUser(View view) { AndroidNetworking.get(ApiEndPoint.BASE_URL + ApiEndPoint.GET_JSON_OBJECT) .addPathParameter("userId", "1") .setTag(this) .setPriority(Priority.LOW) .setUserAgent("getAnUser") .build() .setAnalyticsListener(new AnalyticsListener() { @Override public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) { Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis); Log.d(TAG, " bytesSent : " + bytesSent); Log.d(TAG, " bytesReceived : " + bytesReceived); Log.d(TAG, " isFromCache : " + isFromCache); } }) .getAsObject(User.class, new ParsedRequestListener() { @Override public void onResponse(User user) { Log.d(TAG, "id : " + user.id); Log.d(TAG, "firstname : " + user.firstname); Log.d(TAG, "lastname : " + user.lastname); } @Override public void onError(ANError anError) { Utils.logError(TAG, anError); } }); } public void checkForHeaderGet(View view) { ANRequest.GetRequestBuilder getRequestBuilder = new ANRequest.GetRequestBuilder(ApiEndPoint.BASE_URL + ApiEndPoint.CHECK_FOR_HEADER); getRequestBuilder.addHeaders("token", "1234") .setTag(this) .setPriority(Priority.LOW) .build() .setAnalyticsListener(new AnalyticsListener() { @Override public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) { Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis); Log.d(TAG, " bytesSent : " + bytesSent); Log.d(TAG, " bytesReceived : " + bytesReceived); Log.d(TAG, " isFromCache : " + isFromCache); } }) .getAsJSONObject(new JSONObjectRequestListener() { @Override public void onResponse(JSONObject response) { Log.d(TAG, "onResponse object : " + response.toString()); Log.d(TAG, "onResponse isMainThread : " + String.valueOf(Looper.myLooper() == Looper.getMainLooper())); } @Override public void onError(ANError error) { if (error.getErrorCode() != 0) { // received ANError from server // error.getErrorCode() - the ANError code from server // error.getErrorBody() - the ANError body from server // error.getErrorDetail() - just a ANError detail Log.d(TAG, "onError errorCode : " + error.getErrorCode()); Log.d(TAG, "onError errorBody : " + error.getErrorBody()); Log.d(TAG, "onError errorDetail : " + error.getErrorDetail()); } else { // error.getErrorDetail() : connectionError, parseError, requestCancelledError Log.d(TAG, "onError errorDetail : " + error.getErrorDetail()); } } }); } public void checkForHeaderPost(View view) { ANRequest.PostRequestBuilder postRequestBuilder = AndroidNetworking.post(ApiEndPoint.BASE_URL + ApiEndPoint.CHECK_FOR_HEADER); postRequestBuilder.addHeaders("token", "1234"); ANRequest anRequest = postRequestBuilder.setTag(this) .setPriority(Priority.LOW) .setExecutor(Executors.newSingleThreadExecutor()) .build(); anRequest.setAnalyticsListener(new AnalyticsListener() { @Override public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) { Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis); Log.d(TAG, " bytesSent : " + bytesSent); Log.d(TAG, " bytesReceived : " + bytesReceived); Log.d(TAG, " isFromCache : " + isFromCache); } }); anRequest.getAsJSONObject(new JSONObjectRequestListener() { @Override public void onResponse(JSONObject response) { Log.d(TAG, "onResponse object : " + response.toString()); Log.d(TAG, "onResponse isMainThread : " + String.valueOf(Looper.myLooper() == Looper.getMainLooper())); } @Override public void onError(ANError error) { if (error.getErrorCode() != 0) { // received ANError from server // error.getErrorCode() - the ANError code from server // error.getErrorBody() - the ANError body from server // error.getErrorDetail() - just a ANError detail Log.d(TAG, "onError errorCode : " + error.getErrorCode()); Log.d(TAG, "onError errorBody : " + error.getErrorBody()); Log.d(TAG, "onError errorDetail : " + error.getErrorDetail()); } else { // error.getErrorDetail() : connectionError, parseError, requestCancelledError Log.d(TAG, "onError errorDetail : " + error.getErrorDetail()); } } }); } public void createAnUser(View view) { AndroidNetworking.post(ApiEndPoint.BASE_URL + ApiEndPoint.POST_CREATE_AN_USER) .addBodyParameter("firstname", "Suman") .addBodyParameter("lastname", "Shekhar") .setTag(this) .setPriority(Priority.LOW) .build() .setAnalyticsListener(new AnalyticsListener() { @Override public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) { Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis); Log.d(TAG, " bytesSent : " + bytesSent); Log.d(TAG, " bytesReceived : " + bytesReceived); Log.d(TAG, " isFromCache : " + isFromCache); } }) .getAsJSONObject(new JSONObjectRequestListener() { @Override public void onResponse(JSONObject response) { Log.d(TAG, "onResponse object : " + response.toString()); Log.d(TAG, "onResponse isMainThread : " + String.valueOf(Looper.myLooper() == Looper.getMainLooper())); } @Override public void onError(ANError error) { if (error.getErrorCode() != 0) { // received ANError from server // error.getErrorCode() - the ANError code from server // error.getErrorBody() - the ANError body from server // error.getErrorDetail() - just a ANError detail Log.d(TAG, "onError errorCode : " + error.getErrorCode()); Log.d(TAG, "onError errorBody : " + error.getErrorBody()); Log.d(TAG, "onError errorDetail : " + error.getErrorDetail()); } else { // error.getErrorDetail() : connectionError, parseError, requestCancelledError Log.d(TAG, "onError errorDetail : " + error.getErrorDetail()); } } }); } public void createAnUserJSONObject(View view) { JSONObject jsonObject = new JSONObject(); try { jsonObject.put("firstname", "Rohit"); jsonObject.put("lastname", "Kumar"); } catch (JSONException e) { e.printStackTrace(); } AndroidNetworking.post(ApiEndPoint.BASE_URL + ApiEndPoint.POST_CREATE_AN_USER) .addJSONObjectBody(jsonObject) .setTag(this) .setPriority(Priority.LOW) .build() .setAnalyticsListener(new AnalyticsListener() { @Override public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) { Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis); Log.d(TAG, " bytesSent : " + bytesSent); Log.d(TAG, " bytesReceived : " + bytesReceived); Log.d(TAG, " isFromCache : " + isFromCache); } }) .getAsJSONObject(new JSONObjectRequestListener() { @Override public void onResponse(JSONObject response) { Log.d(TAG, "onResponse object : " + response.toString()); Log.d(TAG, "onResponse isMainThread : " + String.valueOf(Looper.myLooper() == Looper.getMainLooper())); } @Override public void onError(ANError error) { if (error.getErrorCode() != 0) { // received ANError from server // error.getErrorCode() - the ANError code from server // error.getErrorBody() - the ANError body from server // error.getErrorDetail() - just a ANError detail Log.d(TAG, "onError errorCode : " + error.getErrorCode()); Log.d(TAG, "onError errorBody : " + error.getErrorBody()); Log.d(TAG, "onError errorDetail : " + error.getErrorDetail()); } else { // error.getErrorDetail() : connectionError, parseError, requestCancelledError Log.d(TAG, "onError errorDetail : " + error.getErrorDetail()); } } }); } public void downloadFile(final View view) { String url = "http://www.colorado.edu/conflict/peace/download/peace_problem.ZIP"; AndroidNetworking.download(url, Utils.getRootDirPath(getApplicationContext()), "file1.zip") .setPriority(Priority.HIGH) .setTag(this) .build() .setAnalyticsListener(new AnalyticsListener() { @Override public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) { Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis); Log.d(TAG, " bytesSent : " + bytesSent); Log.d(TAG, " bytesReceived : " + bytesReceived); Log.d(TAG, " isFromCache : " + isFromCache); } }) .setDownloadProgressListener(new DownloadProgressListener() { @Override public void onProgress(long bytesDownloaded, long totalBytes) { Log.d(TAG, "bytesDownloaded : " + bytesDownloaded + " totalBytes : " + totalBytes); Log.d(TAG, "setDownloadProgressListener isMainThread : " + String.valueOf(Looper.myLooper() == Looper.getMainLooper())); } }) .startDownload(new DownloadListener() { @Override public void onDownloadComplete() { Log.d(TAG, "File download Completed"); Log.d(TAG, "onDownloadComplete isMainThread : " + String.valueOf(Looper.myLooper() == Looper.getMainLooper())); } @Override public void onError(ANError error) { if (error.getErrorCode() != 0) { // received ANError from server // error.getErrorCode() - the ANError code from server // error.getErrorBody() - the ANError body from server // error.getErrorDetail() - just an ANError detail Log.d(TAG, "onError errorCode : " + error.getErrorCode()); Log.d(TAG, "onError errorBody : " + error.getErrorBody()); Log.d(TAG, "onError errorDetail : " + error.getErrorDetail()); } else { // error.getErrorDetail() : connectionError, parseError, requestCancelledError Log.d(TAG, "onError errorDetail : " + error.getErrorDetail()); } } }); } public void downloadImage(final View view) { String url = "http://i.imgur.com/AtbX9iX.png"; AndroidNetworking.download(url, Utils.getRootDirPath(getApplicationContext()), "image1.png") .setPriority(Priority.MEDIUM) .setTag(this) .build() .setAnalyticsListener(new AnalyticsListener() { @Override public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) { Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis); Log.d(TAG, " bytesSent : " + bytesSent); Log.d(TAG, " bytesReceived : " + bytesReceived); Log.d(TAG, " isFromCache : " + isFromCache); } }) .startDownload(new DownloadListener() { @Override public void onDownloadComplete() { Log.d(TAG, "Image download Completed"); Log.d(TAG, "onDownloadComplete isMainThread : " + String.valueOf(Looper.myLooper() == Looper.getMainLooper())); } @Override public void onError(ANError error) { if (error.getErrorCode() != 0) { // received ANError from server // error.getErrorCode() - the ANError code from server // error.getErrorBody() - the ANError body from server // error.getErrorDetail() - just a ANError detail Log.d(TAG, "onError errorCode : " + error.getErrorCode()); Log.d(TAG, "onError errorBody : " + error.getErrorBody()); Log.d(TAG, "onError errorDetail : " + error.getErrorDetail()); } else { // error.getErrorDetail() : connectionError, parseError, requestCancelledError Log.d(TAG, "onError errorDetail : " + error.getErrorDetail()); } } }); } public void uploadImage(final View view) { final String key = "image"; final File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "test.png"); AndroidNetworking.upload(ApiEndPoint.BASE_URL + ApiEndPoint.UPLOAD_IMAGE) .setPriority(Priority.MEDIUM) .addMultipartFile(key, file) .setTag(this) .build() .setAnalyticsListener(new AnalyticsListener() { @Override public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) { Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis); Log.d(TAG, " bytesSent : " + bytesSent); Log.d(TAG, " bytesReceived : " + bytesReceived); Log.d(TAG, " isFromCache : " + isFromCache); } }) .setUploadProgressListener(new UploadProgressListener() { @Override public void onProgress(long bytesUploaded, long totalBytes) { Log.d(TAG, "bytesUploaded : " + bytesUploaded + " totalBytes : " + totalBytes); Log.d(TAG, "setUploadProgressListener isMainThread : " + String.valueOf(Looper.myLooper() == Looper.getMainLooper())); } }) .getAsJSONObject(new JSONObjectRequestListener() { @Override public void onResponse(JSONObject response) { Log.d(TAG, "Image upload Completed"); Log.d(TAG, "onResponse object : " + response.toString()); } @Override public void onError(ANError error) { if (error.getErrorCode() != 0) { // received ANError from server // error.getErrorCode() - the ANError code from server // error.getErrorBody() - the ANError body from server // error.getErrorDetail() - just a ANError detail Log.d(TAG, "onError errorCode : " + error.getErrorCode()); Log.d(TAG, "onError errorBody : " + error.getErrorBody()); Log.d(TAG, "onError errorDetail : " + error.getErrorDetail()); } else { // error.getErrorDetail() : connectionError, parseError, requestCancelledError Log.d(TAG, "onError errorDetail : " + error.getErrorDetail()); } } }); } public void doNotCacheResponse(View view) { AndroidNetworking.get(ApiEndPoint.BASE_URL + ApiEndPoint.GET_JSON_ARRAY) .addPathParameter("pageNumber", "0") .addQueryParameter("limit", "3") .setTag(this) .setPriority(Priority.LOW) .doNotCacheResponse() .build() .setAnalyticsListener(new AnalyticsListener() { @Override public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) { Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis); Log.d(TAG, " bytesSent : " + bytesSent); Log.d(TAG, " bytesReceived : " + bytesReceived); Log.d(TAG, " isFromCache : " + isFromCache); } }) .getAsJSONArray(new JSONArrayRequestListener() { @Override public void onResponse(JSONArray response) { Log.d(TAG, "onResponse array : " + response.toString()); Log.d(TAG, "onResponse isMainThread : " + String.valueOf(Looper.myLooper() == Looper.getMainLooper())); } @Override public void onError(ANError error) { if (error.getErrorCode() != 0) { // received ANError from server // error.getErrorCode() - the ANError code from server // error.getErrorBody() - the ANError body from server // error.getErrorDetail() - just a ANError detail Log.d(TAG, "onError errorCode : " + error.getErrorCode()); Log.d(TAG, "onError errorBody : " + error.getErrorBody()); Log.d(TAG, "onError errorDetail : " + error.getErrorDetail()); } else { // error.getErrorDetail() : connectionError, parseError, requestCancelledError Log.d(TAG, "onError errorDetail : " + error.getErrorDetail()); } } }); } public void getResponseOnlyIfCached(View view) { AndroidNetworking.get(ApiEndPoint.BASE_URL + ApiEndPoint.GET_JSON_ARRAY) .addPathParameter("pageNumber", "0") .addQueryParameter("limit", "3") .setTag(this) .setPriority(Priority.LOW) .getResponseOnlyIfCached() .build() .setAnalyticsListener(new AnalyticsListener() { @Override public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) { Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis); Log.d(TAG, " bytesSent : " + bytesSent); Log.d(TAG, " bytesReceived : " + bytesReceived); Log.d(TAG, " isFromCache : " + isFromCache); } }) .getAsJSONArray(new JSONArrayRequestListener() { @Override public void onResponse(JSONArray response) { Log.d(TAG, "onResponse array : " + response.toString()); Log.d(TAG, "onResponse isMainThread : " + String.valueOf(Looper.myLooper() == Looper.getMainLooper())); } @Override public void onError(ANError error) { if (error.getErrorCode() != 0) { // received ANError from server // error.getErrorCode() - the ANError code from server // error.getErrorBody() - the ANError body from server // error.getErrorDetail() - just a ANError detail Log.d(TAG, "onError errorCode : " + error.getErrorCode()); Log.d(TAG, "onError errorBody : " + error.getErrorBody()); Log.d(TAG, "onError errorDetail : " + error.getErrorDetail()); } else { // error.getErrorDetail() : connectionError, parseError, requestCancelledError Log.d(TAG, "onError errorDetail : " + error.getErrorDetail()); } } }); } public void getResponseOnlyFromNetwork(View view) { AndroidNetworking.get(ApiEndPoint.BASE_URL + ApiEndPoint.GET_JSON_ARRAY) .addPathParameter("pageNumber", "0") .addQueryParameter("limit", "3") .setTag(this) .setPriority(Priority.LOW) .getResponseOnlyFromNetwork() .build() .setAnalyticsListener(new AnalyticsListener() { @Override public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) { Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis); Log.d(TAG, " bytesSent : " + bytesSent); Log.d(TAG, " bytesReceived : " + bytesReceived); Log.d(TAG, " isFromCache : " + isFromCache); } }) .getAsJSONArray(new JSONArrayRequestListener() { @Override public void onResponse(JSONArray response) { Log.d(TAG, "onResponse array : " + response.toString()); Log.d(TAG, "onResponse isMainThread : " + String.valueOf(Looper.myLooper() == Looper.getMainLooper())); } @Override public void onError(ANError error) { if (error.getErrorCode() != 0) { // received ANError from server // error.getErrorCode() - the ANError code from server // error.getErrorBody() - the ANError body from server // error.getErrorDetail() - just a ANError detail Log.d(TAG, "onError errorCode : " + error.getErrorCode()); Log.d(TAG, "onError errorBody : " + error.getErrorBody()); Log.d(TAG, "onError errorDetail : " + error.getErrorDetail()); } else { // error.getErrorDetail() : connectionError, parseError, requestCancelledError Log.d(TAG, "onError errorDetail : " + error.getErrorDetail()); } } }); } public void setMaxAgeCacheControl(View view) { AndroidNetworking.get(ApiEndPoint.BASE_URL + ApiEndPoint.GET_JSON_ARRAY) .addPathParameter("pageNumber", "0") .addQueryParameter("limit", "3") .setTag(this) .setPriority(Priority.LOW) .setMaxAgeCacheControl(0, TimeUnit.SECONDS) .build() .setAnalyticsListener(new AnalyticsListener() { @Override public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) { Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis); Log.d(TAG, " bytesSent : " + bytesSent); Log.d(TAG, " bytesReceived : " + bytesReceived); Log.d(TAG, " isFromCache : " + isFromCache); } }) .getAsJSONArray(new JSONArrayRequestListener() { @Override public void onResponse(JSONArray response) { Log.d(TAG, "onResponse array : " + response.toString()); Log.d(TAG, "onResponse isMainThread : " + String.valueOf(Looper.myLooper() == Looper.getMainLooper())); } @Override public void onError(ANError error) { if (error.getErrorCode() != 0) { // received ANError from server // error.getErrorCode() - the ANError code from server // error.getErrorBody() - the ANError body from server // error.getErrorDetail() - just a ANError detail Log.d(TAG, "onError errorCode : " + error.getErrorCode()); Log.d(TAG, "onError errorBody : " + error.getErrorBody()); Log.d(TAG, "onError errorDetail : " + error.getErrorDetail()); } else { // error.getErrorDetail() : connectionError, parseError, requestCancelledError Log.d(TAG, "onError errorDetail : " + error.getErrorDetail()); } } }); } public void setMaxStaleCacheControl(View view) { AndroidNetworking.get(ApiEndPoint.BASE_URL + ApiEndPoint.GET_JSON_ARRAY) .addPathParameter("pageNumber", "0") .addQueryParameter("limit", "3") .setTag(this) .setPriority(Priority.LOW) .setMaxStaleCacheControl(365, TimeUnit.SECONDS) .build() .setAnalyticsListener(new AnalyticsListener() { @Override public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) { Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis); Log.d(TAG, " bytesSent : " + bytesSent); Log.d(TAG, " bytesReceived : " + bytesReceived); Log.d(TAG, " isFromCache : " + isFromCache); } }) .getAsJSONArray(new JSONArrayRequestListener() { @Override public void onResponse(JSONArray response) { Log.d(TAG, "onResponse array : " + response.toString()); Log.d(TAG, "onResponse isMainThread : " + String.valueOf(Looper.myLooper() == Looper.getMainLooper())); } @Override public void onError(ANError error) { if (error.getErrorCode() != 0) { // received ANError from server // error.getErrorCode() - the ANError code from server // error.getErrorBody() - the ANError body from server // error.getErrorDetail() - just a ANError detail Log.d(TAG, "onError errorCode : " + error.getErrorCode()); Log.d(TAG, "onError errorBody : " + error.getErrorBody()); Log.d(TAG, "onError errorDetail : " + error.getErrorDetail()); } else { // error.getErrorDetail() : connectionError, parseError, requestCancelledError Log.d(TAG, "onError errorDetail : " + error.getErrorDetail()); } } }); } public void cleanupDestinationTest(View view) { String url = "http://i.imgur.com/m6K1DCQ.jpg"; AndroidNetworking.download(url, Utils.getRootDirPath(getApplicationContext()), "cleanupDestinationTest.jpg") .setPriority(Priority.HIGH) .setTag("cleanupDestinationTest") .build() .setAnalyticsListener(new AnalyticsListener() { @Override public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) { Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis); Log.d(TAG, " bytesSent : " + bytesSent); Log.d(TAG, " bytesReceived : " + bytesReceived); Log.d(TAG, " isFromCache : " + isFromCache); } }) .setDownloadProgressListener(new DownloadProgressListener() { @Override public void onProgress(long bytesDownloaded, long totalBytes) { Log.d(TAG, "bytesDownloaded : " + bytesDownloaded + " totalBytes : " + totalBytes); Log.d(TAG, "setDownloadProgressListener isMainThread : " + String.valueOf(Looper.myLooper() == Looper.getMainLooper())); if (bytesDownloaded > 50) { AndroidNetworking.cancel("cleanupDestinationTest"); Log.d(TAG, "cancel: cleanupDestinationTest"); } } }) .startDownload(new DownloadListener() { @Override public void onDownloadComplete() { Log.d(TAG, "File download Completed"); Log.d(TAG, "onDownloadComplete isMainThread : " + String.valueOf(Looper.myLooper() == Looper.getMainLooper())); } @Override public void onError(ANError error) { if (error.getErrorCode() != 0) { // received ANError from server // error.getErrorCode() - the ANError code from server // error.getErrorBody() - the ANError body from server // error.getErrorDetail() - just an ANError detail Log.d(TAG, "onError errorCode : " + error.getErrorCode()); Log.d(TAG, "onError errorBody : " + error.getErrorBody()); Log.d(TAG, "onError errorDetail : " + error.getErrorDetail()); } else { // error.getErrorDetail() : connectionError, parseError, requestCancelledError Log.d(TAG, "onError errorDetail : " + error.getErrorDetail()); } } }); } public void disableGzipForCustomRequest(View view) { AndroidNetworking.post(ApiEndPoint.BASE_URL + ApiEndPoint.POST_CREATE_AN_USER) .addBodyParameter("firstname", "Amit") .addBodyParameter("lastname", "Shekhar") .setTag(this) .setOkHttpClient(new OkHttpClient()) .setPriority(Priority.LOW) .build() .setAnalyticsListener(new AnalyticsListener() { @Override public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) { Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis); Log.d(TAG, " bytesSent : " + bytesSent); Log.d(TAG, " bytesReceived : " + bytesReceived); Log.d(TAG, " isFromCache : " + isFromCache); } }) .getAsJSONObject(new JSONObjectRequestListener() { @Override public void onResponse(JSONObject response) { Log.d(TAG, "onResponse object : " + response.toString()); Log.d(TAG, "onResponse isMainThread : " + String.valueOf(Looper.myLooper() == Looper.getMainLooper())); } @Override public void onError(ANError error) { if (error.getErrorCode() != 0) { // received ANError from server // error.getErrorCode() - the ANError code from server // error.getErrorBody() - the ANError body from server // error.getErrorDetail() - just a ANError detail Log.d(TAG, "onError errorCode : " + error.getErrorCode()); Log.d(TAG, "onError errorBody : " + error.getErrorBody()); Log.d(TAG, "onError errorDetail : " + error.getErrorDetail()); } else { // error.getErrorDetail() : connectionError, parseError, requestCancelledError Log.d(TAG, "onError errorDetail : " + error.getErrorDetail()); } } }); } public void checkCacheForCustomClient(View view) { String url = "http://www.colorado.edu/conflict/peace/download/peace_problem.ZIP"; AndroidNetworking.download(url, Utils.getRootDirPath(getApplicationContext()), "file1.zip") .setPriority(Priority.HIGH) .setTag(this) .setOkHttpClient(new OkHttpClient()) .build() .setAnalyticsListener(new AnalyticsListener() { @Override public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) { Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis); Log.d(TAG, " bytesSent : " + bytesSent); Log.d(TAG, " bytesReceived : " + bytesReceived); Log.d(TAG, " isFromCache : " + isFromCache); } }) .setDownloadProgressListener(new DownloadProgressListener() { @Override public void onProgress(long bytesDownloaded, long totalBytes) { Log.d(TAG, "bytesDownloaded : " + bytesDownloaded + " totalBytes : " + totalBytes); Log.d(TAG, "setDownloadProgressListener isMainThread : " + String.valueOf(Looper.myLooper() == Looper.getMainLooper())); } }) .startDownload(new DownloadListener() { @Override public void onDownloadComplete() { Log.d(TAG, "File download Completed"); Log.d(TAG, "onDownloadComplete isMainThread : " + String.valueOf(Looper.myLooper() == Looper.getMainLooper())); } @Override public void onError(ANError error) { if (error.getErrorCode() != 0) { // received ANError from server // error.getErrorCode() - the ANError code from server // error.getErrorBody() - the ANError body from server // error.getErrorDetail() - just an ANError detail Log.d(TAG, "onError errorCode : " + error.getErrorCode()); Log.d(TAG, "onError errorBody : " + error.getErrorBody()); Log.d(TAG, "onError errorDetail : " + error.getErrorDetail()); } else { // error.getErrorDetail() : connectionError, parseError, requestCancelledError Log.d(TAG, "onError errorDetail : " + error.getErrorDetail()); } } }); } public void checkOkHttpResponse(View view) { AndroidNetworking.get(ApiEndPoint.BASE_URL + ApiEndPoint.GET_JSON_ARRAY) .addPathParameter("pageNumber", "0") .addQueryParameter("limit", "3") .setTag(this) .setPriority(Priority.LOW) .build() .setAnalyticsListener(new AnalyticsListener() { @Override public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) { Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis); Log.d(TAG, " bytesSent : " + bytesSent); Log.d(TAG, " bytesReceived : " + bytesReceived); Log.d(TAG, " isFromCache : " + isFromCache); } }) .getAsOkHttpResponse(new OkHttpResponseListener() { @Override public void onResponse(Response response) { if (response != null) { if (response.isSuccessful()) { Log.d(TAG, "response is successful"); try { Log.d(TAG, "response : " + response.body().source().readUtf8()); } catch (IOException e) { e.printStackTrace(); } } else { Log.d(TAG, "response is not successful"); } } else { Log.d(TAG, "response is null"); } } @Override public void onError(ANError anError) { Utils.logError(TAG, anError); } }); AndroidNetworking.post(ApiEndPoint.BASE_URL + ApiEndPoint.POST_CREATE_AN_USER) .addBodyParameter("firstname", "Suman") .addBodyParameter("lastname", "Shekhar") .setTag(this) .setPriority(Priority.LOW) .build() .setAnalyticsListener(new AnalyticsListener() { @Override public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) { Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis); Log.d(TAG, " bytesSent : " + bytesSent); Log.d(TAG, " bytesReceived : " + bytesReceived); Log.d(TAG, " isFromCache : " + isFromCache); } }) .getAsOkHttpResponse(new OkHttpResponseListener() { @Override public void onResponse(Response response) { if (response != null) { if (response.isSuccessful()) { Log.d(TAG, "response is successful"); try { Log.d(TAG, "response : " + response.body().source().readUtf8()); } catch (IOException e) { e.printStackTrace(); } } else { Log.d(TAG, "response is not successful"); } } else { Log.d(TAG, "response is null"); } } @Override public void onError(ANError anError) { Utils.logError(TAG, anError); } }); AndroidNetworking.upload(ApiEndPoint.BASE_URL + ApiEndPoint.UPLOAD_IMAGE) .setPriority(Priority.MEDIUM) .addMultipartFile("image", new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "test.png")) .setTag(this) .build() .setAnalyticsListener(new AnalyticsListener() { @Override public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) { Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis); Log.d(TAG, " bytesSent : " + bytesSent); Log.d(TAG, " bytesReceived : " + bytesReceived); Log.d(TAG, " isFromCache : " + isFromCache); } }) .setUploadProgressListener(new UploadProgressListener() { @Override public void onProgress(long bytesUploaded, long totalBytes) { Log.d(TAG, "bytesUploaded : " + bytesUploaded + " totalBytes : " + totalBytes); Log.d(TAG, "setUploadProgressListener isMainThread : " + String.valueOf(Looper.myLooper() == Looper.getMainLooper())); } }) .getAsOkHttpResponse(new OkHttpResponseListener() { @Override public void onResponse(Response response) { if (response != null) { if (response.isSuccessful()) { Log.d(TAG, "response is successful"); try { Log.d(TAG, "response : " + response.body().source().readUtf8()); } catch (IOException e) { e.printStackTrace(); } } else { Log.d(TAG, "response is not successful"); } } else { Log.d(TAG, "response is null"); } } @Override public void onError(ANError anError) { Utils.logError(TAG, anError); } }); } public void checkSynchronousCall(View view) { new Thread(new Runnable() { @Override public void run() { String url = "http://www.colorado.edu/conflict/peace/download/peace_problem.ZIP"; ANRequest requestOne = AndroidNetworking .download(url, Utils.getRootDirPath(getApplicationContext()), "file1.zip") .build() .setAnalyticsListener(new AnalyticsListener() { @Override public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) { Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis); Log.d(TAG, " bytesSent : " + bytesSent); Log.d(TAG, " bytesReceived : " + bytesReceived); Log.d(TAG, " isFromCache : " + isFromCache); } }) .setDownloadProgressListener(new DownloadProgressListener() { @Override public void onProgress(long bytesDownloaded, long totalBytes) { Log.d(TAG, "bytesDownloaded : " + bytesDownloaded + " totalBytes : " + totalBytes); Log.d(TAG, "setDownloadProgressListener isMainThread : " + String.valueOf(Looper.myLooper() == Looper.getMainLooper())); } }); ANResponse responseOne = requestOne.executeForDownload(); if (responseOne.isSuccess()) { Log.d(TAG, "checkSynchronousCall : download success"); Log.d(TAG, "checkSynchronousCall : download result " + responseOne.getResult()); Response response = responseOne.getOkHttpResponse(); Log.d(TAG, "checkSynchronousCall : headers : " + response.headers().toString()); } else { Log.d(TAG, "checkSynchronousCall : download failed"); Utils.logError(TAG, responseOne.getError()); } ANRequest requestTwo = AndroidNetworking.get(ApiEndPoint.BASE_URL + ApiEndPoint.GET_JSON_ARRAY) .addPathParameter("pageNumber", "0") .addQueryParameter("limit", "3") .build() .setAnalyticsListener(new AnalyticsListener() { @Override public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) { Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis); Log.d(TAG, " bytesSent : " + bytesSent); Log.d(TAG, " bytesReceived : " + bytesReceived); Log.d(TAG, " isFromCache : " + isFromCache); } }); ANResponse> responseTwo = requestTwo.executeForObjectList(User.class); if (responseTwo.isSuccess()) { Log.d(TAG, "checkSynchronousCall : response success"); List users = responseTwo.getResult(); Log.d(TAG, "userList size : " + users.size()); for (User user : users) { Log.d(TAG, "id : " + user.id); Log.d(TAG, "firstname : " + user.firstname); Log.d(TAG, "lastname : " + user.lastname); } Response response = responseTwo.getOkHttpResponse(); Log.d(TAG, "checkSynchronousCall : headers : " + response.headers().toString()); } else { Log.d(TAG, "checkSynchronousCall : response failed"); Utils.logError(TAG, responseTwo.getError()); } JSONObject jsonObject = new JSONObject(); try { jsonObject.put("firstname", "Rohit"); jsonObject.put("lastname", "Kumar"); } catch (JSONException e) { e.printStackTrace(); } ANRequest requestThree = AndroidNetworking.post(ApiEndPoint.BASE_URL + ApiEndPoint.POST_CREATE_AN_USER) .addJSONObjectBody(jsonObject) .build() .setAnalyticsListener(new AnalyticsListener() { @Override public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) { Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis); Log.d(TAG, " bytesSent : " + bytesSent); Log.d(TAG, " bytesReceived : " + bytesReceived); Log.d(TAG, " isFromCache : " + isFromCache); } }); ANResponse responseThree = requestThree.executeForJSONObject(); if (responseThree.isSuccess()) { Log.d(TAG, "checkSynchronousCall : jsonObjectANResponse success"); JSONObject jsonObjectFinal = responseThree.getResult(); Log.d(TAG, "checkSynchronousCall : jsonObjectANResponse result " + jsonObjectFinal.toString()); Response response = responseThree.getOkHttpResponse(); Log.d(TAG, "checkSynchronousCall : headers : " + response.headers().toString()); } else { Log.d(TAG, "checkSynchronousCall : jsonObjectANResponse failed"); Utils.logError(TAG, responseThree.getError()); } ANRequest requestFour = AndroidNetworking.get(ApiEndPoint.BASE_URL + ApiEndPoint.GET_JSON_ARRAY) .addPathParameter("pageNumber", "0") .addQueryParameter("limit", "3") .build() .setAnalyticsListener(new AnalyticsListener() { @Override public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) { Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis); Log.d(TAG, " bytesSent : " + bytesSent); Log.d(TAG, " bytesReceived : " + bytesReceived); Log.d(TAG, " isFromCache : " + isFromCache); } }); ANResponse responseFour = requestFour.executeForOkHttpResponse(); if (responseFour.isSuccess()) { Log.d(TAG, "checkSynchronousCall : okHttpResponse success"); Response okHttpResponse = responseFour.getResult(); if (okHttpResponse != null) { if (okHttpResponse.isSuccessful()) { Log.d(TAG, "response is successful"); try { Log.d(TAG, "response : " + okHttpResponse.body().source().readUtf8()); } catch (IOException e) { e.printStackTrace(); } } else { Log.d(TAG, "response is not successful"); } } else { Log.d(TAG, "response is null"); } } else { Log.d(TAG, "checkSynchronousCall : okHttpResponse failed"); Utils.logError(TAG, responseFour.getError()); } } }).start(); } public void checkOptionsRequest(View view) { AndroidNetworking.options("https://api.github.com/square/okhttp/issues") .build() .getAsOkHttpResponse(new OkHttpResponseListener() { @Override public void onResponse(Response response) { Log.d(TAG, "response : " + response.headers().toString()); } @Override public void onError(ANError anError) { Utils.logError(TAG, anError); } }); } public void getCurrentConnectionQuality(View view) { Log.d(TAG, "getCurrentConnectionQuality : " + AndroidNetworking.getCurrentConnectionQuality() + " currentBandwidth : " + AndroidNetworking.getCurrentBandwidth()); } } ================================================ FILE: app/src/main/java/com/networking/ImageGridActivity.java ================================================ /* * Copyright (C) 2016 Amit Shekhar * Copyright (C) 2011 Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.networking; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentTransaction; import com.networking.fragments.ImageGridFragment; /** * Created by amitshekhar on 23/03/16. */ public class ImageGridActivity extends FragmentActivity { private static final String TAG = "ImageGridActivity"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getSupportFragmentManager().findFragmentByTag(TAG) == null) { final FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.add(android.R.id.content, new ImageGridFragment(), TAG); ft.commit(); } } } ================================================ FILE: app/src/main/java/com/networking/MainActivity.java ================================================ /* * Copyright (C) 2016 Amit Shekhar * Copyright (C) 2011 Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.networking; import android.content.Intent; import android.graphics.Bitmap; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.ImageView; import com.androidnetworking.AndroidNetworking; import com.androidnetworking.common.Priority; import com.androidnetworking.error.ANError; import com.androidnetworking.interfaces.AnalyticsListener; import com.androidnetworking.interfaces.BitmapRequestListener; import com.androidnetworking.interfaces.JSONArrayRequestListener; import com.androidnetworking.interfaces.JSONObjectRequestListener; import com.androidnetworking.internal.ANImageLoader; import com.androidnetworking.widget.ANImageView; import com.networking.provider.Images; import org.json.JSONArray; import org.json.JSONObject; public class MainActivity extends AppCompatActivity { private static final String TAG = MainActivity.class.getSimpleName(); private static final String URL_IMAGE = "http://i.imgur.com/2M7Hasn.png"; private static final String URL_IMAGE_LOADER = "http://i.imgur.com/52md06W.jpg"; private ImageView imageView; private ANImageView ANImageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); imageView = (ImageView) findViewById(R.id.imageView); ANImageView = (ANImageView) findViewById(R.id.greatImageView); ANImageView.setDefaultImageResId(R.drawable.ic_toys_black_24dp); ANImageView.setErrorImageResId(R.drawable.ic_error_outline_black_24dp); ANImageView.setImageUrl(Images.imageThumbUrls[0]); makeJSONArrayRequest(); makeJSONObjectRequest(); } private void makeJSONArrayRequest() { AndroidNetworking.get(ApiEndPoint.BASE_URL + ApiEndPoint.GET_JSON_ARRAY) .setTag(this) .addPathParameter("pageNumber", "0") .addQueryParameter("limit", "3") .setPriority(Priority.LOW) .build() .setAnalyticsListener(new AnalyticsListener() { @Override public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) { Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis); Log.d(TAG, " bytesSent : " + bytesSent); Log.d(TAG, " bytesReceived : " + bytesReceived); Log.d(TAG, " isFromCache : " + isFromCache); } }) .getAsJSONArray(new JSONArrayRequestListener() { @Override public void onResponse(JSONArray response) { Log.d(TAG, "onResponse array : " + response.toString()); } @Override public void onError(ANError error) { if (error.getErrorCode() != 0) { // received ANError from server // error.getErrorCode() - the ANError code from server // error.getErrorBody() - the ANError body from server // error.getErrorDetail() - just a ANError detail Log.d(TAG, "onError errorCode : " + error.getErrorCode()); Log.d(TAG, "onError errorBody : " + error.getErrorBody()); Log.d(TAG, "onError errorDetail : " + error.getErrorDetail()); } else { // error.getErrorDetail() : connectionError, parseError, requestCancelledError Log.d(TAG, "onError errorDetail : " + error.getErrorDetail()); } } }); } private void makeJSONObjectRequest() { AndroidNetworking.get(ApiEndPoint.BASE_URL + ApiEndPoint.GET_JSON_OBJECT) .setTag(this) .addPathParameter("userId", "1") .setPriority(Priority.HIGH) .build() .setAnalyticsListener(new AnalyticsListener() { @Override public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) { Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis); Log.d(TAG, " bytesSent : " + bytesSent); Log.d(TAG, " bytesReceived : " + bytesReceived); Log.d(TAG, " isFromCache : " + isFromCache); } }) .getAsJSONObject(new JSONObjectRequestListener() { @Override public void onResponse(JSONObject response) { Log.d(TAG, "onResponse object : " + response.toString()); } @Override public void onError(ANError error) { if (error.getErrorCode() != 0) { // received ANError from server // error.getErrorCode() - the ANError code from server // error.getErrorBody() - the ANError body from server // error.getErrorDetail() - just a ANError detail Log.d(TAG, "onError errorCode : " + error.getErrorCode()); Log.d(TAG, "onError errorBody : " + error.getErrorBody()); Log.d(TAG, "onError errorDetail : " + error.getErrorDetail()); } else { // error.getErrorDetail() : connectionError, parseError, requestCancelledError Log.d(TAG, "onError errorDetail : " + error.getErrorDetail()); } } }); } public void makeRequests(View view) { for (int i = 0; i < 10; i++) { makeJSONArrayRequest(); makeJSONObjectRequest(); } } public void cancelAllRequests(View view) { Log.d(TAG, "isRequestRunning before cancel : " + AndroidNetworking.isRequestRunning(this)); AndroidNetworking.cancel(this); Log.d(TAG, "isRequestRunning after cancel : " + AndroidNetworking.isRequestRunning(this)); } public void loadImageDirect(View view) { AndroidNetworking.get(URL_IMAGE) .setTag("imageRequestTag") .setPriority(Priority.MEDIUM) .setImageScaleType(null) .setBitmapMaxHeight(0) .setBitmapMaxWidth(0) .setBitmapConfig(Bitmap.Config.ARGB_8888) .build() .setAnalyticsListener(new AnalyticsListener() { @Override public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) { Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis); Log.d(TAG, " bytesSent : " + bytesSent); Log.d(TAG, " bytesReceived : " + bytesReceived); Log.d(TAG, " isFromCache : " + isFromCache); } }) .getAsBitmap(new BitmapRequestListener() { @Override public void onResponse(Bitmap response) { Log.d(TAG, "onResponse Bitmap"); imageView.setImageBitmap(response); } @Override public void onError(ANError error) { if (error.getErrorCode() != 0) { // received ANError from server // error.getErrorCode() - the ANError code from server // error.getErrorBody() - the ANError body from server // error.getErrorDetail() - just a ANError detail Log.d(TAG, "onError errorCode : " + error.getErrorCode()); Log.d(TAG, "onError errorBody : " + error.getErrorBody()); Log.d(TAG, "onError errorDetail : " + error.getErrorDetail()); } else { // error.getErrorDetail() : connectionError, parseError, requestCancelledError Log.d(TAG, "onError errorDetail : " + error.getErrorDetail()); } } }); } public void loadImageFromImageLoader(View view) { ANImageLoader.getInstance().get(URL_IMAGE_LOADER, ANImageLoader.getImageListener(imageView, R.drawable.ic_toys_black_24dp, R.drawable.ic_error_outline_black_24dp)); } public void startGridActivity(View view) { startActivity(new Intent(MainActivity.this, ImageGridActivity.class)); } public void startApiTestActivity(View view) { startActivity(new Intent(MainActivity.this, ApiTestActivity.class)); } public void startOkHttpResponseTestActivity(View view) { startActivity(new Intent(MainActivity.this, OkHttpResponseTestActivity.class)); } public void startWebSocketActivity(View view) { startActivity(new Intent(MainActivity.this, WebSocketActivity.class)); } } ================================================ FILE: app/src/main/java/com/networking/MyApplication.java ================================================ /* * Copyright (C) 2016 Amit Shekhar * Copyright (C) 2011 Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.networking; import android.app.Application; import android.graphics.BitmapFactory; import android.util.Log; import com.androidnetworking.AndroidNetworking; import com.androidnetworking.common.ConnectionQuality; import com.androidnetworking.interfaces.ConnectionQualityChangeListener; /** * Created by amitshekhar on 22/03/16. */ public class MyApplication extends Application { private static final String TAG = MyApplication.class.getSimpleName(); private static MyApplication appInstance = null; public static MyApplication getInstance() { return appInstance; } @Override public void onCreate() { super.onCreate(); appInstance = this; AndroidNetworking.initialize(getApplicationContext()); BitmapFactory.Options options = new BitmapFactory.Options(); options.inPurgeable = true; AndroidNetworking.setBitmapDecodeOptions(options); AndroidNetworking.enableLogging(); AndroidNetworking.setConnectionQualityChangeListener(new ConnectionQualityChangeListener() { @Override public void onChange(ConnectionQuality currentConnectionQuality, int currentBandwidth) { Log.d(TAG, "onChange: currentConnectionQuality : " + currentConnectionQuality + " currentBandwidth : " + currentBandwidth); } }); } } ================================================ FILE: app/src/main/java/com/networking/OkHttpResponseTestActivity.java ================================================ /* * * * Copyright (C) 2016 Amit Shekhar * * Copyright (C) 2011 Android Open Source Project * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * */ package com.networking; import android.os.Bundle; import android.os.Environment; import android.os.Looper; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import com.androidnetworking.AndroidNetworking; import com.androidnetworking.common.ANRequest; import com.androidnetworking.common.ANResponse; import com.androidnetworking.common.Priority; import com.androidnetworking.error.ANError; import com.androidnetworking.interfaces.AnalyticsListener; import com.androidnetworking.interfaces.DownloadListener; import com.androidnetworking.interfaces.DownloadProgressListener; import com.androidnetworking.interfaces.OkHttpResponseAndJSONArrayRequestListener; import com.androidnetworking.interfaces.OkHttpResponseAndJSONObjectRequestListener; import com.androidnetworking.interfaces.OkHttpResponseAndParsedRequestListener; import com.androidnetworking.interfaces.OkHttpResponseListener; import com.androidnetworking.interfaces.UploadProgressListener; import com.networking.model.User; import com.networking.utils.Utils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.io.IOException; import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import okhttp3.OkHttpClient; import okhttp3.Response; /** * Created by amitshekhar on 30/03/16. */ public class OkHttpResponseTestActivity extends AppCompatActivity { private static final String TAG = OkHttpResponseTestActivity.class.getSimpleName(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_api_test); } public void prefetch(View view) { AndroidNetworking.get(ApiEndPoint.BASE_URL + ApiEndPoint.GET_JSON_ARRAY) .addPathParameter("pageNumber", "0") .addQueryParameter("limit", "3") .setTag(this) .setPriority(Priority.LOW) .build() .setAnalyticsListener(new AnalyticsListener() { @Override public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) { Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis); Log.d(TAG, " bytesSent : " + bytesSent); Log.d(TAG, " bytesReceived : " + bytesReceived); Log.d(TAG, " isFromCache : " + isFromCache); } }) .prefetch(); } public void prefetchDownload(View view) { String url = "http://www.colorado.edu/conflict/peace/download/peace_problem.ZIP"; AndroidNetworking.download(url, Utils.getRootDirPath(getApplicationContext()), "file1.zip") .setPriority(Priority.HIGH) .setTag(this) .build() .setAnalyticsListener(new AnalyticsListener() { @Override public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) { Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis); Log.d(TAG, " bytesSent : " + bytesSent); Log.d(TAG, " bytesReceived : " + bytesReceived); Log.d(TAG, " isFromCache : " + isFromCache); } }) .prefetch(); } public void getAllUsers(View view) { AndroidNetworking.get(ApiEndPoint.BASE_URL + ApiEndPoint.GET_JSON_ARRAY) .addPathParameter("pageNumber", "0") .addQueryParameter("limit", "3") .setTag(this) .setPriority(Priority.LOW) .build() .setAnalyticsListener(new AnalyticsListener() { @Override public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) { Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis); Log.d(TAG, " bytesSent : " + bytesSent); Log.d(TAG, " bytesReceived : " + bytesReceived); Log.d(TAG, " isFromCache : " + isFromCache); } }) .getAsOkHttpResponseAndObjectList(User.class, new OkHttpResponseAndParsedRequestListener>() { @Override public void onResponse(Response okHttpResponse, List users) { Log.d(TAG, "userList size : " + users.size()); for (User user : users) { Log.d(TAG, "id : " + user.id); Log.d(TAG, "firstname : " + user.firstname); Log.d(TAG, "lastname : " + user.lastname); } if (okHttpResponse.isSuccessful()) { Log.d(TAG, "onResponse success headers : " + okHttpResponse.headers().toString()); } else { Log.d(TAG, "onResponse not success headers : " + okHttpResponse.headers().toString()); } } @Override public void onError(ANError anError) { Utils.logError(TAG, anError); } }); } public void getAnUser(View view) { AndroidNetworking.get(ApiEndPoint.BASE_URL + ApiEndPoint.GET_JSON_OBJECT) .addPathParameter("userId", "1") .setTag(this) .setPriority(Priority.LOW) .setUserAgent("getAnUser") .build() .setAnalyticsListener(new AnalyticsListener() { @Override public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) { Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis); Log.d(TAG, " bytesSent : " + bytesSent); Log.d(TAG, " bytesReceived : " + bytesReceived); Log.d(TAG, " isFromCache : " + isFromCache); } }) .getAsOkHttpResponseAndObject(User.class, new OkHttpResponseAndParsedRequestListener() { @Override public void onResponse(Response okHttpResponse, User user) { Log.d(TAG, "id : " + user.id); Log.d(TAG, "firstname : " + user.firstname); Log.d(TAG, "lastname : " + user.lastname); if (okHttpResponse.isSuccessful()) { Log.d(TAG, "onResponse success headers : " + okHttpResponse.headers().toString()); } else { Log.d(TAG, "onResponse not success headers : " + okHttpResponse.headers().toString()); } } @Override public void onError(ANError anError) { Utils.logError(TAG, anError); } }); } public void checkForHeaderGet(View view) { ANRequest.GetRequestBuilder getRequestBuilder = new ANRequest.GetRequestBuilder(ApiEndPoint.BASE_URL + ApiEndPoint.CHECK_FOR_HEADER); getRequestBuilder.addHeaders("token", "1234") .setTag(this) .setPriority(Priority.LOW) .build() .setAnalyticsListener(new AnalyticsListener() { @Override public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) { Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis); Log.d(TAG, " bytesSent : " + bytesSent); Log.d(TAG, " bytesReceived : " + bytesReceived); Log.d(TAG, " isFromCache : " + isFromCache); } }).getAsOkHttpResponseAndJSONObject(new OkHttpResponseAndJSONObjectRequestListener() { @Override public void onResponse(Response okHttpResponse, JSONObject response) { Log.d(TAG, "onResponse object : " + response.toString()); if (okHttpResponse.isSuccessful()) { Log.d(TAG, "onResponse success headers : " + okHttpResponse.headers().toString()); } else { Log.d(TAG, "onResponse not success headers : " + okHttpResponse.headers().toString()); } } @Override public void onError(ANError anError) { Utils.logError(TAG, anError); } }); } public void checkForHeaderPost(View view) { ANRequest.PostRequestBuilder postRequestBuilder = AndroidNetworking.post(ApiEndPoint.BASE_URL + ApiEndPoint.CHECK_FOR_HEADER); postRequestBuilder.addHeaders("token", "1234"); ANRequest anRequest = postRequestBuilder.setTag(this) .setPriority(Priority.LOW) .setExecutor(Executors.newSingleThreadExecutor()) .build(); anRequest.setAnalyticsListener(new AnalyticsListener() { @Override public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) { Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis); Log.d(TAG, " bytesSent : " + bytesSent); Log.d(TAG, " bytesReceived : " + bytesReceived); Log.d(TAG, " isFromCache : " + isFromCache); } }); anRequest.getAsOkHttpResponseAndJSONObject(new OkHttpResponseAndJSONObjectRequestListener() { @Override public void onResponse(Response okHttpResponse, JSONObject response) { Log.d(TAG, "onResponse object : " + response.toString()); Log.d(TAG, "onResponse isMainThread : " + String.valueOf(Looper.myLooper() == Looper.getMainLooper())); if (okHttpResponse.isSuccessful()) { Log.d(TAG, "onResponse success headers : " + okHttpResponse.headers().toString()); } else { Log.d(TAG, "onResponse not success headers : " + okHttpResponse.headers().toString()); } } @Override public void onError(ANError anError) { Utils.logError(TAG, anError); } }); } public void createAnUser(View view) { AndroidNetworking.post(ApiEndPoint.BASE_URL + ApiEndPoint.POST_CREATE_AN_USER) .addBodyParameter("firstname", "Suman") .addBodyParameter("lastname", "Shekhar") .setTag(this) .setPriority(Priority.LOW) .build() .setAnalyticsListener(new AnalyticsListener() { @Override public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) { Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis); Log.d(TAG, " bytesSent : " + bytesSent); Log.d(TAG, " bytesReceived : " + bytesReceived); Log.d(TAG, " isFromCache : " + isFromCache); } }) .getAsOkHttpResponseAndJSONObject(new OkHttpResponseAndJSONObjectRequestListener() { @Override public void onResponse(Response okHttpResponse, JSONObject response) { Log.d(TAG, "onResponse object : " + response.toString()); Log.d(TAG, "onResponse isMainThread : " + String.valueOf(Looper.myLooper() == Looper.getMainLooper())); if (okHttpResponse.isSuccessful()) { Log.d(TAG, "onResponse success headers : " + okHttpResponse.headers().toString()); } else { Log.d(TAG, "onResponse not success headers : " + okHttpResponse.headers().toString()); } } @Override public void onError(ANError anError) { Utils.logError(TAG, anError); } }); } public void createAnUserJSONObject(View view) { JSONObject jsonObject = new JSONObject(); try { jsonObject.put("firstname", "Rohit"); jsonObject.put("lastname", "Kumar"); } catch (JSONException e) { e.printStackTrace(); } AndroidNetworking.post(ApiEndPoint.BASE_URL + ApiEndPoint.POST_CREATE_AN_USER) .addJSONObjectBody(jsonObject) .setTag(this) .setPriority(Priority.LOW) .build() .setAnalyticsListener(new AnalyticsListener() { @Override public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) { Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis); Log.d(TAG, " bytesSent : " + bytesSent); Log.d(TAG, " bytesReceived : " + bytesReceived); Log.d(TAG, " isFromCache : " + isFromCache); } }).getAsOkHttpResponseAndJSONObject(new OkHttpResponseAndJSONObjectRequestListener() { @Override public void onResponse(Response okHttpResponse, JSONObject response) { Log.d(TAG, "onResponse object : " + response.toString()); Log.d(TAG, "onResponse isMainThread : " + String.valueOf(Looper.myLooper() == Looper.getMainLooper())); if (okHttpResponse.isSuccessful()) { Log.d(TAG, "onResponse success headers : " + okHttpResponse.headers().toString()); } else { Log.d(TAG, "onResponse not success headers : " + okHttpResponse.headers().toString()); } } @Override public void onError(ANError anError) { Utils.logError(TAG, anError); } }); } public void downloadFile(final View view) { String url = "http://www.colorado.edu/conflict/peace/download/peace_problem.ZIP"; AndroidNetworking.download(url, Utils.getRootDirPath(getApplicationContext()), "file1.zip") .setPriority(Priority.HIGH) .setTag(this) .build() .setAnalyticsListener(new AnalyticsListener() { @Override public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) { Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis); Log.d(TAG, " bytesSent : " + bytesSent); Log.d(TAG, " bytesReceived : " + bytesReceived); Log.d(TAG, " isFromCache : " + isFromCache); } }) .setDownloadProgressListener(new DownloadProgressListener() { @Override public void onProgress(long bytesDownloaded, long totalBytes) { Log.d(TAG, "bytesDownloaded : " + bytesDownloaded + " totalBytes : " + totalBytes); Log.d(TAG, "setDownloadProgressListener isMainThread : " + String.valueOf(Looper.myLooper() == Looper.getMainLooper())); } }) .startDownload(new DownloadListener() { @Override public void onDownloadComplete() { Log.d(TAG, "File download Completed"); Log.d(TAG, "onDownloadComplete isMainThread : " + String.valueOf(Looper.myLooper() == Looper.getMainLooper())); } @Override public void onError(ANError error) { if (error.getErrorCode() != 0) { // received ANError from server // error.getErrorCode() - the ANError code from server // error.getErrorBody() - the ANError body from server // error.getErrorDetail() - just an ANError detail Log.d(TAG, "onError errorCode : " + error.getErrorCode()); Log.d(TAG, "onError errorBody : " + error.getErrorBody()); Log.d(TAG, "onError errorDetail : " + error.getErrorDetail()); } else { // error.getErrorDetail() : connectionError, parseError, requestCancelledError Log.d(TAG, "onError errorDetail : " + error.getErrorDetail()); } } }); } public void downloadImage(final View view) { String url = "http://i.imgur.com/AtbX9iX.png"; AndroidNetworking.download(url, Utils.getRootDirPath(getApplicationContext()), "image1.png") .setPriority(Priority.MEDIUM) .setTag(this) .build() .setAnalyticsListener(new AnalyticsListener() { @Override public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) { Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis); Log.d(TAG, " bytesSent : " + bytesSent); Log.d(TAG, " bytesReceived : " + bytesReceived); Log.d(TAG, " isFromCache : " + isFromCache); } }) .startDownload(new DownloadListener() { @Override public void onDownloadComplete() { Log.d(TAG, "Image download Completed"); Log.d(TAG, "onDownloadComplete isMainThread : " + String.valueOf(Looper.myLooper() == Looper.getMainLooper())); } @Override public void onError(ANError error) { if (error.getErrorCode() != 0) { // received ANError from server // error.getErrorCode() - the ANError code from server // error.getErrorBody() - the ANError body from server // error.getErrorDetail() - just a ANError detail Log.d(TAG, "onError errorCode : " + error.getErrorCode()); Log.d(TAG, "onError errorBody : " + error.getErrorBody()); Log.d(TAG, "onError errorDetail : " + error.getErrorDetail()); } else { // error.getErrorDetail() : connectionError, parseError, requestCancelledError Log.d(TAG, "onError errorDetail : " + error.getErrorDetail()); } } }); } public void uploadImage(final View view) { AndroidNetworking.upload(ApiEndPoint.BASE_URL + ApiEndPoint.UPLOAD_IMAGE) .setPriority(Priority.MEDIUM) .addMultipartFile("image", new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "test.png")) .setTag(this) .build() .setAnalyticsListener(new AnalyticsListener() { @Override public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) { Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis); Log.d(TAG, " bytesSent : " + bytesSent); Log.d(TAG, " bytesReceived : " + bytesReceived); Log.d(TAG, " isFromCache : " + isFromCache); } }) .setUploadProgressListener(new UploadProgressListener() { @Override public void onProgress(long bytesUploaded, long totalBytes) { Log.d(TAG, "bytesUploaded : " + bytesUploaded + " totalBytes : " + totalBytes); Log.d(TAG, "setUploadProgressListener isMainThread : " + String.valueOf(Looper.myLooper() == Looper.getMainLooper())); } }) .getAsOkHttpResponseAndJSONObject(new OkHttpResponseAndJSONObjectRequestListener() { @Override public void onResponse(Response okHttpResponse, JSONObject response) { Log.d(TAG, "Image upload Completed"); Log.d(TAG, "onResponse object : " + response.toString()); Log.d(TAG, "onResponse isMainThread : " + String.valueOf(Looper.myLooper() == Looper.getMainLooper())); if (okHttpResponse.isSuccessful()) { Log.d(TAG, "onResponse success headers : " + okHttpResponse.headers().toString()); } else { Log.d(TAG, "onResponse not success headers : " + okHttpResponse.headers().toString()); } } @Override public void onError(ANError anError) { Utils.logError(TAG, anError); } }); } public void doNotCacheResponse(View view) { AndroidNetworking.get(ApiEndPoint.BASE_URL + ApiEndPoint.GET_JSON_ARRAY) .addPathParameter("pageNumber", "0") .addQueryParameter("limit", "3") .setTag(this) .setPriority(Priority.LOW) .doNotCacheResponse() .build() .setAnalyticsListener(new AnalyticsListener() { @Override public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) { Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis); Log.d(TAG, " bytesSent : " + bytesSent); Log.d(TAG, " bytesReceived : " + bytesReceived); Log.d(TAG, " isFromCache : " + isFromCache); } }) .getAsOkHttpResponseAndJSONArray(new OkHttpResponseAndJSONArrayRequestListener() { @Override public void onResponse(Response okHttpResponse, JSONArray response) { Log.d(TAG, "onResponse object : " + response.toString()); Log.d(TAG, "onResponse isMainThread : " + String.valueOf(Looper.myLooper() == Looper.getMainLooper())); if (okHttpResponse.isSuccessful()) { Log.d(TAG, "onResponse success headers : " + okHttpResponse.headers().toString()); } else { Log.d(TAG, "onResponse not success headers : " + okHttpResponse.headers().toString()); } } @Override public void onError(ANError anError) { Utils.logError(TAG, anError); } }); } public void getResponseOnlyIfCached(View view) { AndroidNetworking.get(ApiEndPoint.BASE_URL + ApiEndPoint.GET_JSON_ARRAY) .addPathParameter("pageNumber", "0") .addQueryParameter("limit", "3") .setTag(this) .setPriority(Priority.LOW) .getResponseOnlyIfCached() .build() .setAnalyticsListener(new AnalyticsListener() { @Override public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) { Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis); Log.d(TAG, " bytesSent : " + bytesSent); Log.d(TAG, " bytesReceived : " + bytesReceived); Log.d(TAG, " isFromCache : " + isFromCache); } }) .getAsOkHttpResponseAndJSONArray(new OkHttpResponseAndJSONArrayRequestListener() { @Override public void onResponse(Response okHttpResponse, JSONArray response) { Log.d(TAG, "onResponse object : " + response.toString()); Log.d(TAG, "onResponse isMainThread : " + String.valueOf(Looper.myLooper() == Looper.getMainLooper())); if (okHttpResponse.isSuccessful()) { Log.d(TAG, "onResponse success headers : " + okHttpResponse.headers().toString()); } else { Log.d(TAG, "onResponse not success headers : " + okHttpResponse.headers().toString()); } } @Override public void onError(ANError anError) { Utils.logError(TAG, anError); } }); } public void getResponseOnlyFromNetwork(View view) { AndroidNetworking.get(ApiEndPoint.BASE_URL + ApiEndPoint.GET_JSON_ARRAY) .addPathParameter("pageNumber", "0") .addQueryParameter("limit", "3") .setTag(this) .setPriority(Priority.LOW) .getResponseOnlyFromNetwork() .build() .setAnalyticsListener(new AnalyticsListener() { @Override public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) { Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis); Log.d(TAG, " bytesSent : " + bytesSent); Log.d(TAG, " bytesReceived : " + bytesReceived); Log.d(TAG, " isFromCache : " + isFromCache); } }) .getAsOkHttpResponseAndJSONArray(new OkHttpResponseAndJSONArrayRequestListener() { @Override public void onResponse(Response okHttpResponse, JSONArray response) { Log.d(TAG, "onResponse object : " + response.toString()); Log.d(TAG, "onResponse isMainThread : " + String.valueOf(Looper.myLooper() == Looper.getMainLooper())); if (okHttpResponse.isSuccessful()) { Log.d(TAG, "onResponse success headers : " + okHttpResponse.headers().toString()); } else { Log.d(TAG, "onResponse not success headers : " + okHttpResponse.headers().toString()); } } @Override public void onError(ANError anError) { Utils.logError(TAG, anError); } }); } public void setMaxAgeCacheControl(View view) { AndroidNetworking.get(ApiEndPoint.BASE_URL + ApiEndPoint.GET_JSON_ARRAY) .addPathParameter("pageNumber", "0") .addQueryParameter("limit", "3") .setTag(this) .setPriority(Priority.LOW) .setMaxAgeCacheControl(0, TimeUnit.SECONDS) .build() .setAnalyticsListener(new AnalyticsListener() { @Override public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) { Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis); Log.d(TAG, " bytesSent : " + bytesSent); Log.d(TAG, " bytesReceived : " + bytesReceived); Log.d(TAG, " isFromCache : " + isFromCache); } }) .getAsOkHttpResponseAndJSONArray(new OkHttpResponseAndJSONArrayRequestListener() { @Override public void onResponse(Response okHttpResponse, JSONArray response) { Log.d(TAG, "onResponse object : " + response.toString()); Log.d(TAG, "onResponse isMainThread : " + String.valueOf(Looper.myLooper() == Looper.getMainLooper())); if (okHttpResponse.isSuccessful()) { Log.d(TAG, "onResponse success headers : " + okHttpResponse.headers().toString()); } else { Log.d(TAG, "onResponse not success headers : " + okHttpResponse.headers().toString()); } } @Override public void onError(ANError anError) { Utils.logError(TAG, anError); } }); } public void setMaxStaleCacheControl(View view) { AndroidNetworking.get(ApiEndPoint.BASE_URL + ApiEndPoint.GET_JSON_ARRAY) .addPathParameter("pageNumber", "0") .addQueryParameter("limit", "3") .setTag(this) .setPriority(Priority.LOW) .setMaxStaleCacheControl(365, TimeUnit.SECONDS) .build() .setAnalyticsListener(new AnalyticsListener() { @Override public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) { Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis); Log.d(TAG, " bytesSent : " + bytesSent); Log.d(TAG, " bytesReceived : " + bytesReceived); Log.d(TAG, " isFromCache : " + isFromCache); } }) .getAsOkHttpResponseAndJSONArray(new OkHttpResponseAndJSONArrayRequestListener() { @Override public void onResponse(Response okHttpResponse, JSONArray response) { Log.d(TAG, "onResponse object : " + response.toString()); Log.d(TAG, "onResponse isMainThread : " + String.valueOf(Looper.myLooper() == Looper.getMainLooper())); if (okHttpResponse.isSuccessful()) { Log.d(TAG, "onResponse success headers : " + okHttpResponse.headers().toString()); } else { Log.d(TAG, "onResponse not success headers : " + okHttpResponse.headers().toString()); } } @Override public void onError(ANError anError) { Utils.logError(TAG, anError); } }); } public void cleanupDestinationTest(View view) { String url = "http://i.imgur.com/m6K1DCQ.jpg"; AndroidNetworking.download(url, Utils.getRootDirPath(getApplicationContext()), "cleanupDestinationTest.jpg") .setPriority(Priority.HIGH) .setTag("cleanupDestinationTest") .build() .setAnalyticsListener(new AnalyticsListener() { @Override public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) { Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis); Log.d(TAG, " bytesSent : " + bytesSent); Log.d(TAG, " bytesReceived : " + bytesReceived); Log.d(TAG, " isFromCache : " + isFromCache); } }) .setDownloadProgressListener(new DownloadProgressListener() { @Override public void onProgress(long bytesDownloaded, long totalBytes) { Log.d(TAG, "bytesDownloaded : " + bytesDownloaded + " totalBytes : " + totalBytes); Log.d(TAG, "setDownloadProgressListener isMainThread : " + String.valueOf(Looper.myLooper() == Looper.getMainLooper())); if (bytesDownloaded > 50) { AndroidNetworking.cancel("cleanupDestinationTest"); Log.d(TAG, "cancel: cleanupDestinationTest"); } } }) .startDownload(new DownloadListener() { @Override public void onDownloadComplete() { Log.d(TAG, "File download Completed"); Log.d(TAG, "onDownloadComplete isMainThread : " + String.valueOf(Looper.myLooper() == Looper.getMainLooper())); } @Override public void onError(ANError error) { if (error.getErrorCode() != 0) { // received ANError from server // error.getErrorCode() - the ANError code from server // error.getErrorBody() - the ANError body from server // error.getErrorDetail() - just an ANError detail Log.d(TAG, "onError errorCode : " + error.getErrorCode()); Log.d(TAG, "onError errorBody : " + error.getErrorBody()); Log.d(TAG, "onError errorDetail : " + error.getErrorDetail()); } else { // error.getErrorDetail() : connectionError, parseError, requestCancelledError Log.d(TAG, "onError errorDetail : " + error.getErrorDetail()); } } }); } public void disableGzipForCustomRequest(View view) { AndroidNetworking.post(ApiEndPoint.BASE_URL + ApiEndPoint.POST_CREATE_AN_USER) .addBodyParameter("firstname", "Amit") .addBodyParameter("lastname", "Shekhar") .setTag(this) .setOkHttpClient(new OkHttpClient()) .setPriority(Priority.LOW) .build() .setAnalyticsListener(new AnalyticsListener() { @Override public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) { Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis); Log.d(TAG, " bytesSent : " + bytesSent); Log.d(TAG, " bytesReceived : " + bytesReceived); Log.d(TAG, " isFromCache : " + isFromCache); } }) .getAsOkHttpResponseAndJSONObject(new OkHttpResponseAndJSONObjectRequestListener() { @Override public void onResponse(Response okHttpResponse, JSONObject response) { Log.d(TAG, "onResponse object : " + response.toString()); Log.d(TAG, "onResponse isMainThread : " + String.valueOf(Looper.myLooper() == Looper.getMainLooper())); if (okHttpResponse.isSuccessful()) { Log.d(TAG, "onResponse success headers : " + okHttpResponse.headers().toString()); } else { Log.d(TAG, "onResponse not success headers : " + okHttpResponse.headers().toString()); } } @Override public void onError(ANError anError) { Utils.logError(TAG, anError); } }); } public void checkCacheForCustomClient(View view) { String url = "http://www.colorado.edu/conflict/peace/download/peace_problem.ZIP"; AndroidNetworking.download(url, Utils.getRootDirPath(getApplicationContext()), "file1.zip") .setPriority(Priority.HIGH) .setTag(this) .setOkHttpClient(new OkHttpClient()) .build() .setAnalyticsListener(new AnalyticsListener() { @Override public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) { Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis); Log.d(TAG, " bytesSent : " + bytesSent); Log.d(TAG, " bytesReceived : " + bytesReceived); Log.d(TAG, " isFromCache : " + isFromCache); } }) .setDownloadProgressListener(new DownloadProgressListener() { @Override public void onProgress(long bytesDownloaded, long totalBytes) { Log.d(TAG, "bytesDownloaded : " + bytesDownloaded + " totalBytes : " + totalBytes); Log.d(TAG, "setDownloadProgressListener isMainThread : " + String.valueOf(Looper.myLooper() == Looper.getMainLooper())); } }) .startDownload(new DownloadListener() { @Override public void onDownloadComplete() { Log.d(TAG, "File download Completed"); Log.d(TAG, "onDownloadComplete isMainThread : " + String.valueOf(Looper.myLooper() == Looper.getMainLooper())); } @Override public void onError(ANError error) { if (error.getErrorCode() != 0) { // received ANError from server // error.getErrorCode() - the ANError code from server // error.getErrorBody() - the ANError body from server // error.getErrorDetail() - just an ANError detail Log.d(TAG, "onError errorCode : " + error.getErrorCode()); Log.d(TAG, "onError errorBody : " + error.getErrorBody()); Log.d(TAG, "onError errorDetail : " + error.getErrorDetail()); } else { // error.getErrorDetail() : connectionError, parseError, requestCancelledError Log.d(TAG, "onError errorDetail : " + error.getErrorDetail()); } } }); } public void checkOkHttpResponse(View view) { AndroidNetworking.get(ApiEndPoint.BASE_URL + ApiEndPoint.GET_JSON_ARRAY) .addPathParameter("pageNumber", "0") .addQueryParameter("limit", "3") .setTag(this) .setPriority(Priority.LOW) .build() .setAnalyticsListener(new AnalyticsListener() { @Override public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) { Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis); Log.d(TAG, " bytesSent : " + bytesSent); Log.d(TAG, " bytesReceived : " + bytesReceived); Log.d(TAG, " isFromCache : " + isFromCache); } }) .getAsOkHttpResponse(new OkHttpResponseListener() { @Override public void onResponse(Response response) { if (response != null) { if (response.isSuccessful()) { Log.d(TAG, "response is successful"); try { Log.d(TAG, "response : " + response.body().source().readUtf8()); } catch (IOException e) { e.printStackTrace(); } } else { Log.d(TAG, "response is not successful"); } } else { Log.d(TAG, "response is null"); } } @Override public void onError(ANError anError) { Utils.logError(TAG, anError); } }); AndroidNetworking.post(ApiEndPoint.BASE_URL + ApiEndPoint.POST_CREATE_AN_USER) .addBodyParameter("firstname", "Suman") .addBodyParameter("lastname", "Shekhar") .setTag(this) .setPriority(Priority.LOW) .build() .setAnalyticsListener(new AnalyticsListener() { @Override public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) { Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis); Log.d(TAG, " bytesSent : " + bytesSent); Log.d(TAG, " bytesReceived : " + bytesReceived); Log.d(TAG, " isFromCache : " + isFromCache); } }) .getAsOkHttpResponse(new OkHttpResponseListener() { @Override public void onResponse(Response response) { if (response != null) { if (response.isSuccessful()) { Log.d(TAG, "response is successful"); try { Log.d(TAG, "response : " + response.body().source().readUtf8()); } catch (IOException e) { e.printStackTrace(); } } else { Log.d(TAG, "response is not successful"); } } else { Log.d(TAG, "response is null"); } } @Override public void onError(ANError anError) { Utils.logError(TAG, anError); } }); AndroidNetworking.upload(ApiEndPoint.BASE_URL + ApiEndPoint.UPLOAD_IMAGE) .setPriority(Priority.MEDIUM) .addMultipartFile("image", new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "test.png")) .setTag(this) .build() .setAnalyticsListener(new AnalyticsListener() { @Override public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) { Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis); Log.d(TAG, " bytesSent : " + bytesSent); Log.d(TAG, " bytesReceived : " + bytesReceived); Log.d(TAG, " isFromCache : " + isFromCache); } }) .setUploadProgressListener(new UploadProgressListener() { @Override public void onProgress(long bytesUploaded, long totalBytes) { Log.d(TAG, "bytesUploaded : " + bytesUploaded + " totalBytes : " + totalBytes); Log.d(TAG, "setUploadProgressListener isMainThread : " + String.valueOf(Looper.myLooper() == Looper.getMainLooper())); } }) .getAsOkHttpResponse(new OkHttpResponseListener() { @Override public void onResponse(Response response) { if (response != null) { if (response.isSuccessful()) { Log.d(TAG, "response is successful"); try { Log.d(TAG, "response : " + response.body().source().readUtf8()); } catch (IOException e) { e.printStackTrace(); } } else { Log.d(TAG, "response is not successful"); } } else { Log.d(TAG, "response is null"); } } @Override public void onError(ANError anError) { Utils.logError(TAG, anError); } }); } public void checkSynchronousCall(View view) { new Thread(new Runnable() { @Override public void run() { String url = "http://www.colorado.edu/conflict/peace/download/peace_problem.ZIP"; ANRequest requestOne = AndroidNetworking .download(url, Utils.getRootDirPath(getApplicationContext()), "file1.zip") .setPriority(Priority.HIGH) .setTag(this) .build() .setAnalyticsListener(new AnalyticsListener() { @Override public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) { Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis); Log.d(TAG, " bytesSent : " + bytesSent); Log.d(TAG, " bytesReceived : " + bytesReceived); Log.d(TAG, " isFromCache : " + isFromCache); } }) .setDownloadProgressListener(new DownloadProgressListener() { @Override public void onProgress(long bytesDownloaded, long totalBytes) { Log.d(TAG, "bytesDownloaded : " + bytesDownloaded + " totalBytes : " + totalBytes); Log.d(TAG, "setDownloadProgressListener isMainThread : " + String.valueOf(Looper.myLooper() == Looper.getMainLooper())); } }); ANResponse responseOne = requestOne.executeForDownload(); if (responseOne.isSuccess()) { Log.d(TAG, "checkSynchronousCall : download success"); Log.d(TAG, "checkSynchronousCall : download result " + responseOne.getResult()); Response response = responseOne.getOkHttpResponse(); Log.d(TAG, "checkSynchronousCall : headers : " + response.headers().toString()); } else { Log.d(TAG, "checkSynchronousCall : download failed"); Utils.logError(TAG, responseOne.getError()); } ANRequest requestTwo = AndroidNetworking.get(ApiEndPoint.BASE_URL + ApiEndPoint.GET_JSON_ARRAY) .addPathParameter("pageNumber", "0") .addQueryParameter("limit", "3") .setTag(this) .setPriority(Priority.LOW) .build() .setAnalyticsListener(new AnalyticsListener() { @Override public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) { Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis); Log.d(TAG, " bytesSent : " + bytesSent); Log.d(TAG, " bytesReceived : " + bytesReceived); Log.d(TAG, " isFromCache : " + isFromCache); } }); ANResponse> responseTwo = requestTwo.executeForObjectList(User.class); if (responseTwo.isSuccess()) { Log.d(TAG, "checkSynchronousCall : response success"); List users = responseTwo.getResult(); Log.d(TAG, "userList size : " + users.size()); for (User user : users) { Log.d(TAG, "id : " + user.id); Log.d(TAG, "firstname : " + user.firstname); Log.d(TAG, "lastname : " + user.lastname); } Response response = responseTwo.getOkHttpResponse(); Log.d(TAG, "checkSynchronousCall : headers : " + response.headers().toString()); } else { Log.d(TAG, "checkSynchronousCall : response failed"); Utils.logError(TAG, responseTwo.getError()); } JSONObject jsonObject = new JSONObject(); try { jsonObject.put("firstname", "Rohit"); jsonObject.put("lastname", "Kumar"); } catch (JSONException e) { e.printStackTrace(); } ANRequest requestThree = AndroidNetworking.post(ApiEndPoint.BASE_URL + ApiEndPoint.POST_CREATE_AN_USER) .addJSONObjectBody(jsonObject) .setTag(this) .setPriority(Priority.LOW) .build() .setAnalyticsListener(new AnalyticsListener() { @Override public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) { Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis); Log.d(TAG, " bytesSent : " + bytesSent); Log.d(TAG, " bytesReceived : " + bytesReceived); Log.d(TAG, " isFromCache : " + isFromCache); } }); ANResponse responseThree = requestThree.executeForJSONObject(); if (responseThree.isSuccess()) { Log.d(TAG, "checkSynchronousCall : jsonObjectANResponse success"); JSONObject jsonObjectFinal = responseThree.getResult(); Log.d(TAG, "checkSynchronousCall : jsonObjectANResponse result " + jsonObjectFinal.toString()); Response response = responseThree.getOkHttpResponse(); Log.d(TAG, "checkSynchronousCall : headers : " + response.headers().toString()); } else { Log.d(TAG, "checkSynchronousCall : jsonObjectANResponse failed"); Utils.logError(TAG, responseThree.getError()); } ANRequest requestFour = AndroidNetworking.get(ApiEndPoint.BASE_URL + ApiEndPoint.GET_JSON_ARRAY) .addPathParameter("pageNumber", "0") .addQueryParameter("limit", "3") .setTag(this) .setPriority(Priority.LOW) .build() .setAnalyticsListener(new AnalyticsListener() { @Override public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) { Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis); Log.d(TAG, " bytesSent : " + bytesSent); Log.d(TAG, " bytesReceived : " + bytesReceived); Log.d(TAG, " isFromCache : " + isFromCache); } }); ANResponse responseFour = requestFour.executeForOkHttpResponse(); if (responseFour.isSuccess()) { Log.d(TAG, "checkSynchronousCall : okHttpResponse success"); Response okHttpResponse = responseFour.getResult(); if (okHttpResponse != null) { if (okHttpResponse.isSuccessful()) { Log.d(TAG, "response is successful"); try { Log.d(TAG, "response : " + okHttpResponse.body().source().readUtf8()); } catch (IOException e) { e.printStackTrace(); } } else { Log.d(TAG, "response is not successful"); } } else { Log.d(TAG, "response is null"); } } else { Log.d(TAG, "checkSynchronousCall : okHttpResponse failed"); Utils.logError(TAG, responseFour.getError()); } } }).start(); } public void checkOptionsRequest(View view) { AndroidNetworking.options("https://api.github.com/square/okhttp/issues") .build() .getAsOkHttpResponse(new OkHttpResponseListener() { @Override public void onResponse(Response response) { Log.d(TAG, "response : " + response.headers().toString()); } @Override public void onError(ANError anError) { Utils.logError(TAG, anError); } }); } public void getCurrentConnectionQuality(View view) { Log.d(TAG, "getCurrentConnectionQuality : " + AndroidNetworking.getCurrentConnectionQuality() + " currentBandwidth : " + AndroidNetworking.getCurrentBandwidth()); } } ================================================ FILE: app/src/main/java/com/networking/WebSocketActivity.java ================================================ /* * * * Copyright (C) 2016 Amit Shekhar * * Copyright (C) 2011 Android Open Source Project * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * */ package com.networking; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import java.util.concurrent.TimeUnit; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import okhttp3.WebSocket; import okhttp3.WebSocketListener; import okio.ByteString; /** * Created by amitshekhar on 09/12/16. */ public class WebSocketActivity extends AppCompatActivity { private static final String TAG = WebSocketActivity.class.getSimpleName(); private TextView textView; private WebSocket webSocket; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_web_socket); textView = (TextView) findViewById(R.id.textView); } @Override protected void onStart() { super.onStart(); connectWebSocket(); } @Override protected void onStop() { super.onStop(); disconnectWebSocket(); } private void connectWebSocket() { OkHttpClient client = new OkHttpClient.Builder() .readTimeout(0, TimeUnit.MILLISECONDS) .build(); Request request = new Request.Builder() .url("ws://echo.websocket.org") .build(); webSocket = client.newWebSocket(request, getWebSocketListener()); } private void disconnectWebSocket() { if (webSocket != null) { webSocket.cancel(); } } private WebSocketListener getWebSocketListener() { return new WebSocketListener() { @Override public void onOpen(WebSocket webSocket, Response response) { webSocket.send("Hello..."); webSocket.send("...World!"); webSocket.send(ByteString.decodeHex("deadbeef")); webSocket.close(1000, "Goodbye, World!"); } @Override public void onMessage(WebSocket webSocket, final String text) { runOnUiThread(new Runnable() { @Override public void run() { textView.append("\n"); textView.append("MESSAGE: " + text); } }); } @Override public void onMessage(WebSocket webSocket,final ByteString bytes) { runOnUiThread(new Runnable() { @Override public void run() { textView.append("\n"); textView.append("MESSAGE: " + bytes.hex()); } }); } @Override public void onClosing(WebSocket webSocket,final int code,final String reason) { webSocket.close(1000, null); runOnUiThread(new Runnable() { @Override public void run() { textView.append("\n"); textView.append("CLOSE: " + code + " " + reason); } }); } @Override public void onFailure(WebSocket webSocket, Throwable t, Response response) { t.printStackTrace(); } }; } } ================================================ FILE: app/src/main/java/com/networking/fragments/ImageGridFragment.java ================================================ /* * Copyright (C) 2016 Amit Shekhar * Copyright (C) 2011 Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.networking.fragments; import android.annotation.TargetApi; import android.content.Context; import android.os.Build; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.ImageView; import com.androidnetworking.widget.ANImageView; import com.networking.R; import com.networking.provider.Images; /** * Created by amitshekhar on 23/03/16. */ public class ImageGridFragment extends Fragment implements AdapterView.OnItemClickListener { private static final String TAG = "ImageGridFragment"; private int mImageThumbSize; private int mImageThumbSpacing; private ImageAdapter mAdapter; public ImageGridFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); mImageThumbSize = getResources().getDimensionPixelSize(R.dimen.image_thumbnail_size); mImageThumbSpacing = getResources().getDimensionPixelSize(R.dimen.image_thumbnail_spacing); mAdapter = new ImageAdapter(getActivity()); } @Override public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final View v = inflater.inflate(R.layout.image_grid_fragment, container, false); final GridView mGridView = (GridView) v.findViewById(R.id.gridView); mGridView.setAdapter(mAdapter); mGridView.setOnItemClickListener(this); mGridView.getViewTreeObserver().addOnGlobalLayoutListener( new ViewTreeObserver.OnGlobalLayoutListener() { @TargetApi(Build.VERSION_CODES.JELLY_BEAN) @Override public void onGlobalLayout() { if (mAdapter.getNumColumns() == 0) { final int numColumns = (int) Math.floor( mGridView.getWidth() / (mImageThumbSize + mImageThumbSpacing)); if (numColumns > 0) { final int columnWidth = (mGridView.getWidth() / numColumns) - mImageThumbSpacing; mAdapter.setNumColumns(numColumns); mAdapter.setItemHeight(columnWidth); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { mGridView.getViewTreeObserver() .removeOnGlobalLayoutListener(this); } else { mGridView.getViewTreeObserver() .removeGlobalOnLayoutListener(this); } } } } }); return v; } @Override public void onResume() { super.onResume(); mAdapter.notifyDataSetChanged(); } @Override public void onPause() { super.onPause(); } @Override public void onDestroy() { super.onDestroy(); } @TargetApi(Build.VERSION_CODES.JELLY_BEAN) @Override public void onItemClick(AdapterView parent, View v, int position, long id) { } private class ImageAdapter extends BaseAdapter { private final Context mContext; private int mItemHeight = 0; private int mNumColumns = 0; private int mActionBarHeight = 0; private GridView.LayoutParams mImageViewLayoutParams; public ImageAdapter(Context context) { super(); mContext = context; mImageViewLayoutParams = new GridView.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); TypedValue tv = new TypedValue(); if (context.getTheme().resolveAttribute( android.R.attr.actionBarSize, tv, true)) { mActionBarHeight = TypedValue.complexToDimensionPixelSize( tv.data, context.getResources().getDisplayMetrics()); } } @Override public int getCount() { if (getNumColumns() == 0) { return 0; } return Images.imageThumbUrls.length + mNumColumns; } @Override public Object getItem(int position) { return position < mNumColumns ? null : Images.imageThumbUrls[position - mNumColumns]; } @Override public long getItemId(int position) { return position < mNumColumns ? 0 : position - mNumColumns; } @Override public int getViewTypeCount() { return 2; } @Override public int getItemViewType(int position) { return (position < mNumColumns) ? 1 : 0; } @Override public boolean hasStableIds() { return true; } @Override public View getView(int position, View convertView, ViewGroup container) { if (position < mNumColumns) { if (convertView == null) { convertView = new View(mContext); } convertView.setLayoutParams(new AbsListView.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, mActionBarHeight)); return convertView; } ANImageView imageView; if (convertView == null) { imageView = new ANImageView(mContext); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); imageView.setLayoutParams(mImageViewLayoutParams); } else { imageView = (ANImageView) convertView; } if (imageView.getLayoutParams().height != mItemHeight) { imageView.setLayoutParams(mImageViewLayoutParams); } imageView.setDefaultImageResId(R.drawable.ic_toys_black_24dp); imageView.setErrorImageResId(R.drawable.ic_error_outline_black_24dp); imageView.setImageUrl(Images.imageThumbUrls[position - mNumColumns]); return imageView; } public void setItemHeight(int height) { if (height == mItemHeight) { return; } mItemHeight = height; mImageViewLayoutParams = new GridView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, mItemHeight); notifyDataSetChanged(); } public void setNumColumns(int numColumns) { mNumColumns = numColumns; } public int getNumColumns() { return mNumColumns; } } } ================================================ FILE: app/src/main/java/com/networking/model/User.java ================================================ /* * * * Copyright (C) 2016 Amit Shekhar * * Copyright (C) 2011 Android Open Source Project * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * */ package com.networking.model; /** * Created by amitshekhar on 31/07/16. */ public class User { public long id; public String firstname; public String lastname; public boolean isFollowing; } ================================================ FILE: app/src/main/java/com/networking/provider/Images.java ================================================ /* * Copyright (C) 2016 Amit Shekhar * Copyright (C) 2011 Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.networking.provider; /** * Created by amitshekhar on 23/03/16. */ /** * Some simple test data to use for this sample app. */ public class Images { /** * This are PicasaWeb URLs and could potentially change. Ideally the PicasaWeb API should be * used to fetch the URLs. *

* Credit to Romain Guy for the photos: * http://www.curious-creature.org/ * https://plus.google.com/109538161516040592207/about * http://www.flickr.com/photos/romainguy */ public final static String[] imageUrls = new String[]{ "https://lh6.googleusercontent.com/-55osAWw3x0Q/URquUtcFr5I/AAAAAAAAAbs/rWlj1RUKrYI/s1024/A%252520Photographer.jpg", "https://lh4.googleusercontent.com/--dq8niRp7W4/URquVgmXvgI/AAAAAAAAAbs/-gnuLQfNnBA/s1024/A%252520Song%252520of%252520Ice%252520and%252520Fire.jpg", "https://lh5.googleusercontent.com/-7qZeDtRKFKc/URquWZT1gOI/AAAAAAAAAbs/hqWgteyNXsg/s1024/Another%252520Rockaway%252520Sunset.jpg", "https://lh3.googleusercontent.com/--L0Km39l5J8/URquXHGcdNI/AAAAAAAAAbs/3ZrSJNrSomQ/s1024/Antelope%252520Butte.jpg", "https://lh6.googleusercontent.com/-8HO-4vIFnlw/URquZnsFgtI/AAAAAAAAAbs/WT8jViTF7vw/s1024/Antelope%252520Hallway.jpg", "https://lh4.googleusercontent.com/-WIuWgVcU3Qw/URqubRVcj4I/AAAAAAAAAbs/YvbwgGjwdIQ/s1024/Antelope%252520Walls.jpg", "https://lh6.googleusercontent.com/-UBmLbPELvoQ/URqucCdv0kI/AAAAAAAAAbs/IdNhr2VQoQs/s1024/Apre%2525CC%252580s%252520la%252520Pluie.jpg", "https://lh3.googleusercontent.com/-s-AFpvgSeew/URquc6dF-JI/AAAAAAAAAbs/Mt3xNGRUd68/s1024/Backlit%252520Cloud.jpg", "https://lh5.googleusercontent.com/-bvmif9a9YOQ/URquea3heHI/AAAAAAAAAbs/rcr6wyeQtAo/s1024/Bee%252520and%252520Flower.jpg", "https://lh5.googleusercontent.com/-n7mdm7I7FGs/URqueT_BT-I/AAAAAAAAAbs/9MYmXlmpSAo/s1024/Bonzai%252520Rock%252520Sunset.jpg", "https://lh6.googleusercontent.com/-4CN4X4t0M1k/URqufPozWzI/AAAAAAAAAbs/8wK41lg1KPs/s1024/Caterpillar.jpg", "https://lh3.googleusercontent.com/-rrFnVC8xQEg/URqufdrLBaI/AAAAAAAAAbs/s69WYy_fl1E/s1024/Chess.jpg", "https://lh5.googleusercontent.com/-WVpRptWH8Yw/URqugh-QmDI/AAAAAAAAAbs/E-MgBgtlUWU/s1024/Chihuly.jpg", "https://lh5.googleusercontent.com/-0BDXkYmckbo/URquhKFW84I/AAAAAAAAAbs/ogQtHCTk2JQ/s1024/Closed%252520Door.jpg", "https://lh3.googleusercontent.com/-PyggXXZRykM/URquh-kVvoI/AAAAAAAAAbs/hFtDwhtrHHQ/s1024/Colorado%252520River%252520Sunset.jpg", "https://lh3.googleusercontent.com/-ZAs4dNZtALc/URquikvOCWI/AAAAAAAAAbs/DXz4h3dll1Y/s1024/Colors%252520of%252520Autumn.jpg", "https://lh4.googleusercontent.com/-GztnWEIiMz8/URqukVCU7bI/AAAAAAAAAbs/jo2Hjv6MZ6M/s1024/Countryside.jpg", "https://lh4.googleusercontent.com/-bEg9EZ9QoiM/URquklz3FGI/AAAAAAAAAbs/UUuv8Ac2BaE/s1024/Death%252520Valley%252520-%252520Dunes.jpg", "https://lh6.googleusercontent.com/-ijQJ8W68tEE/URqulGkvFEI/AAAAAAAAAbs/zPXvIwi_rFw/s1024/Delicate%252520Arch.jpg", "https://lh5.googleusercontent.com/-Oh8mMy2ieng/URqullDwehI/AAAAAAAAAbs/TbdeEfsaIZY/s1024/Despair.jpg", "https://lh5.googleusercontent.com/-gl0y4UiAOlk/URqumC_KjBI/AAAAAAAAAbs/PM1eT7dn4oo/s1024/Eagle%252520Fall%252520Sunrise.jpg", "https://lh3.googleusercontent.com/-hYYHd2_vXPQ/URqumtJa9eI/AAAAAAAAAbs/wAalXVkbSh0/s1024/Electric%252520Storm.jpg", "https://lh5.googleusercontent.com/-PyY_yiyjPTo/URqunUOhHFI/AAAAAAAAAbs/azZoULNuJXc/s1024/False%252520Kiva.jpg", "https://lh6.googleusercontent.com/-PYvLVdvXywk/URqunwd8hfI/AAAAAAAAAbs/qiMwgkFvf6I/s1024/Fitzgerald%252520Streaks.jpg", "https://lh4.googleusercontent.com/-KIR_UobIIqY/URquoCZ9SlI/AAAAAAAAAbs/Y4d4q8sXu4c/s1024/Foggy%252520Sunset.jpg", "https://lh6.googleusercontent.com/-9lzOk_OWZH0/URquoo4xYoI/AAAAAAAAAbs/AwgzHtNVCwU/s1024/Frantic.jpg", "https://lh3.googleusercontent.com/-0X3JNaKaz48/URqupH78wpI/AAAAAAAAAbs/lHXxu_zbH8s/s1024/Golden%252520Gate%252520Afternoon.jpg", "https://lh6.googleusercontent.com/-95sb5ag7ABc/URqupl95RDI/AAAAAAAAAbs/g73R20iVTRA/s1024/Golden%252520Gate%252520Fog.jpg", "https://lh3.googleusercontent.com/-JB9v6rtgHhk/URqup21F-zI/AAAAAAAAAbs/64Fb8qMZWXk/s1024/Golden%252520Grass.jpg", "https://lh4.googleusercontent.com/-EIBGfnuLtII/URquqVHwaRI/AAAAAAAAAbs/FA4McV2u8VE/s1024/Grand%252520Teton.jpg", "https://lh4.googleusercontent.com/-WoMxZvmN9nY/URquq1v2AoI/AAAAAAAAAbs/grj5uMhL6NA/s1024/Grass%252520Closeup.jpg", "https://lh3.googleusercontent.com/-6hZiEHXx64Q/URqurxvNdqI/AAAAAAAAAbs/kWMXM3o5OVI/s1024/Green%252520Grass.jpg", "https://lh5.googleusercontent.com/-6LVb9OXtQ60/URquteBFuKI/AAAAAAAAAbs/4F4kRgecwFs/s1024/Hanging%252520Leaf.jpg", "https://lh4.googleusercontent.com/-zAvf__52ONk/URqutT_IuxI/AAAAAAAAAbs/D_bcuc0thoU/s1024/Highway%2525201.jpg", "https://lh6.googleusercontent.com/-H4SrUg615rA/URquuL27fXI/AAAAAAAAAbs/4aEqJfiMsOU/s1024/Horseshoe%252520Bend%252520Sunset.jpg", "https://lh4.googleusercontent.com/-JhFi4fb_Pqw/URquuX-QXbI/AAAAAAAAAbs/IXpYUxuweYM/s1024/Horseshoe%252520Bend.jpg", "https://lh5.googleusercontent.com/-UGgssvFRJ7g/URquueyJzGI/AAAAAAAAAbs/yYIBlLT0toM/s1024/Into%252520the%252520Blue.jpg", "https://lh3.googleusercontent.com/-CH7KoupI7uI/URquu0FF__I/AAAAAAAAAbs/R7GDmI7v_G0/s1024/Jelly%252520Fish%2525202.jpg", "https://lh4.googleusercontent.com/-pwuuw6yhg8U/URquvPxR3FI/AAAAAAAAAbs/VNGk6f-tsGE/s1024/Jelly%252520Fish%2525203.jpg", "https://lh5.googleusercontent.com/-GoUQVw1fnFw/URquv6xbC0I/AAAAAAAAAbs/zEUVTQQ43Zc/s1024/Kauai.jpg", "https://lh6.googleusercontent.com/-8QdYYQEpYjw/URquwvdh88I/AAAAAAAAAbs/cktDy-ysfHo/s1024/Kyoto%252520Sunset.jpg", "https://lh4.googleusercontent.com/-vPeekyDjOE0/URquwzJ28qI/AAAAAAAAAbs/qxcyXULsZrg/s1024/Lake%252520Tahoe%252520Colors.jpg", "https://lh4.googleusercontent.com/-xBPxWpD4yxU/URquxWHk8AI/AAAAAAAAAbs/ARDPeDYPiMY/s1024/Lava%252520from%252520the%252520Sky.jpg", "https://lh3.googleusercontent.com/-897VXrJB6RE/URquxxxd-5I/AAAAAAAAAbs/j-Cz4T4YvIw/s1024/Leica%25252050mm%252520Summilux.jpg", "https://lh5.googleusercontent.com/-qSJ4D4iXzGo/URquyDWiJ1I/AAAAAAAAAbs/k2pBXeWehOA/s1024/Leica%25252050mm%252520Summilux.jpg", "https://lh6.googleusercontent.com/-dwlPg83vzLg/URquylTVuFI/AAAAAAAAAbs/G6SyQ8b4YsI/s1024/Leica%252520M8%252520%252528Front%252529.jpg", "https://lh3.googleusercontent.com/-R3_EYAyJvfk/URquzQBv8eI/AAAAAAAAAbs/b9xhpUM3pEI/s1024/Light%252520to%252520Sand.jpg", "https://lh3.googleusercontent.com/-fHY5h67QPi0/URqu0Cp4J1I/AAAAAAAAAbs/0lG6m94Z6vM/s1024/Little%252520Bit%252520of%252520Paradise.jpg", "https://lh5.googleusercontent.com/-TzF_LwrCnRM/URqu0RddPOI/AAAAAAAAAbs/gaj2dLiuX0s/s1024/Lone%252520Pine%252520Sunset.jpg", "https://lh3.googleusercontent.com/-4HdpJ4_DXU4/URqu046dJ9I/AAAAAAAAAbs/eBOodtk2_uk/s1024/Lonely%252520Rock.jpg", "https://lh6.googleusercontent.com/-erbF--z-W4s/URqu1ajSLkI/AAAAAAAAAbs/xjDCDO1INzM/s1024/Longue%252520Vue.jpg", "https://lh6.googleusercontent.com/-0CXJRdJaqvc/URqu1opNZNI/AAAAAAAAAbs/PFB2oPUU7Lk/s1024/Look%252520Me%252520in%252520the%252520Eye.jpg", "https://lh3.googleusercontent.com/-D_5lNxnDN6g/URqu2Tk7HVI/AAAAAAAAAbs/p0ddca9W__Y/s1024/Lost%252520in%252520a%252520Field.jpg", "https://lh6.googleusercontent.com/-flsqwMrIk2Q/URqu24PcmjI/AAAAAAAAAbs/5ocIH85XofM/s1024/Marshall%252520Beach%252520Sunset.jpg", "https://lh4.googleusercontent.com/-Y4lgryEVTmU/URqu28kG3gI/AAAAAAAAAbs/OjXpekqtbJ4/s1024/Mono%252520Lake%252520Blue.jpg", "https://lh4.googleusercontent.com/-AaHAJPmcGYA/URqu3PIldHI/AAAAAAAAAbs/lcTqk1SIcRs/s1024/Monument%252520Valley%252520Overlook.jpg", "https://lh4.googleusercontent.com/-vKxfdQ83dQA/URqu31Yq_BI/AAAAAAAAAbs/OUoGk_2AyfM/s1024/Moving%252520Rock.jpg", "https://lh5.googleusercontent.com/-CG62QiPpWXg/URqu4ia4vRI/AAAAAAAAAbs/0YOdqLAlcAc/s1024/Napali%252520Coast.jpg", "https://lh6.googleusercontent.com/-wdGrP5PMmJQ/URqu5PZvn7I/AAAAAAAAAbs/m0abEcdPXe4/s1024/One%252520Wheel.jpg", "https://lh6.googleusercontent.com/-6WS5DoCGuOA/URqu5qx1UgI/AAAAAAAAAbs/giMw2ixPvrY/s1024/Open%252520Sky.jpg", "https://lh6.googleusercontent.com/-u8EHKj8G8GQ/URqu55sM6yI/AAAAAAAAAbs/lIXX_GlTdmI/s1024/Orange%252520Sunset.jpg", "https://lh6.googleusercontent.com/-74Z5qj4bTDE/URqu6LSrJrI/AAAAAAAAAbs/XzmVkw90szQ/s1024/Orchid.jpg", "https://lh6.googleusercontent.com/-lEQE4h6TePE/URqu6t_lSkI/AAAAAAAAAbs/zvGYKOea_qY/s1024/Over%252520there.jpg", "https://lh5.googleusercontent.com/-cauH-53JH2M/URqu66v_USI/AAAAAAAAAbs/EucwwqclfKQ/s1024/Plumes.jpg", "https://lh3.googleusercontent.com/-eDLT2jHDoy4/URqu7axzkAI/AAAAAAAAAbs/iVZE-xJ7lZs/s1024/Rainbokeh.jpg", "https://lh5.googleusercontent.com/-j1NLqEFIyco/URqu8L1CGcI/AAAAAAAAAbs/aqZkgX66zlI/s1024/Rainbow.jpg", "https://lh5.googleusercontent.com/-DRnqmK0t4VU/URqu8XYN9yI/AAAAAAAAAbs/LgvF_592WLU/s1024/Rice%252520Fields.jpg", "https://lh3.googleusercontent.com/-hwh1v3EOGcQ/URqu8qOaKwI/AAAAAAAAAbs/IljRJRnbJGw/s1024/Rockaway%252520Fire%252520Sky.jpg", "https://lh5.googleusercontent.com/-wjV6FQk7tlk/URqu9jCQ8sI/AAAAAAAAAbs/RyYUpdo-c9o/s1024/Rockaway%252520Flow.jpg", "https://lh6.googleusercontent.com/-6cAXNfo7D20/URqu-BdzgPI/AAAAAAAAAbs/OmsYllzJqwo/s1024/Rockaway%252520Sunset%252520Sky.jpg", "https://lh3.googleusercontent.com/-sl8fpGPS-RE/URqu_BOkfgI/AAAAAAAAAbs/Dg2Fv-JxOeg/s1024/Russian%252520Ridge%252520Sunset.jpg", "https://lh6.googleusercontent.com/-gVtY36mMBIg/URqu_q91lkI/AAAAAAAAAbs/3CiFMBcy5MA/s1024/Rust%252520Knot.jpg", "https://lh6.googleusercontent.com/-GHeImuHqJBE/URqu_FKfVLI/AAAAAAAAAbs/axuEJeqam7Q/s1024/Sailing%252520Stones.jpg", "https://lh3.googleusercontent.com/-hBbYZjTOwGc/URqu_ycpIrI/AAAAAAAAAbs/nAdJUXnGJYE/s1024/Seahorse.jpg", "https://lh3.googleusercontent.com/-Iwi6-i6IexY/URqvAYZHsVI/AAAAAAAAAbs/5ETWl4qXsFE/s1024/Shinjuku%252520Street.jpg", "https://lh6.googleusercontent.com/-amhnySTM_MY/URqvAlb5KoI/AAAAAAAAAbs/pFCFgzlKsn0/s1024/Sierra%252520Heavens.jpg", "https://lh5.googleusercontent.com/-dJgjepFrYSo/URqvBVJZrAI/AAAAAAAAAbs/v-F5QWpYO6s/s1024/Sierra%252520Sunset.jpg", "https://lh4.googleusercontent.com/-Z4zGiC5nWdc/URqvBdEwivI/AAAAAAAAAbs/ZRZR1VJ84QA/s1024/Sin%252520Lights.jpg", "https://lh4.googleusercontent.com/-_0cYiWW8ccY/URqvBz3iM4I/AAAAAAAAAbs/9N_Wq8MhLTY/s1024/Starry%252520Lake.jpg", "https://lh3.googleusercontent.com/-A9LMoRyuQUA/URqvCYx_JoI/AAAAAAAAAbs/s7sde1Bz9cI/s1024/Starry%252520Night.jpg", "https://lh3.googleusercontent.com/-KtLJ3k858eY/URqvC_2h_bI/AAAAAAAAAbs/zzEBImwDA_g/s1024/Stream.jpg", "https://lh5.googleusercontent.com/-dFB7Lad6RcA/URqvDUftwWI/AAAAAAAAAbs/BrhoUtXTN7o/s1024/Strip%252520Sunset.jpg", "https://lh5.googleusercontent.com/-at6apgFiN20/URqvDyffUZI/AAAAAAAAAbs/clABCx171bE/s1024/Sunset%252520Hills.jpg", "https://lh4.googleusercontent.com/-7-EHhtQthII/URqvEYTk4vI/AAAAAAAAAbs/QSJZoB3YjVg/s1024/Tenaya%252520Lake%2525202.jpg", "https://lh6.googleusercontent.com/-8MrjV_a-Pok/URqvFC5repI/AAAAAAAAAbs/9inKTg9fbCE/s1024/Tenaya%252520Lake.jpg", "https://lh5.googleusercontent.com/-B1HW-z4zwao/URqvFWYRwUI/AAAAAAAAAbs/8Peli53Bs8I/s1024/The%252520Cave%252520BW.jpg", "https://lh3.googleusercontent.com/-PO4E-xZKAnQ/URqvGRqjYkI/AAAAAAAAAbs/42nyADFsXag/s1024/The%252520Fisherman.jpg", "https://lh4.googleusercontent.com/-iLyZlzfdy7s/URqvG0YScdI/AAAAAAAAAbs/1J9eDKmkXtk/s1024/The%252520Night%252520is%252520Coming.jpg", "https://lh6.googleusercontent.com/-G-k7YkkUco0/URqvHhah6fI/AAAAAAAAAbs/_taQQG7t0vo/s1024/The%252520Road.jpg", "https://lh6.googleusercontent.com/-h-ALJt7kSus/URqvIThqYfI/AAAAAAAAAbs/ejiv35olWS8/s1024/Tokyo%252520Heights.jpg", "https://lh5.googleusercontent.com/-Hy9k-TbS7xg/URqvIjQMOxI/AAAAAAAAAbs/RSpmmOATSkg/s1024/Tokyo%252520Highway.jpg", "https://lh6.googleusercontent.com/-83oOvMb4OZs/URqvJL0T7lI/AAAAAAAAAbs/c5TECZ6RONM/s1024/Tokyo%252520Smog.jpg", "https://lh3.googleusercontent.com/-FB-jfgREEfI/URqvJI3EXAI/AAAAAAAAAbs/XfyweiRF4v8/s1024/Tufa%252520at%252520Night.jpg", "https://lh4.googleusercontent.com/-vngKD5Z1U8w/URqvJUCEgPI/AAAAAAAAAbs/ulxCMVcU6EU/s1024/Valley%252520Sunset.jpg", "https://lh6.googleusercontent.com/-DOz5I2E2oMQ/URqvKMND1kI/AAAAAAAAAbs/Iqf0IsInleo/s1024/Windmill%252520Sunrise.jpg", "https://lh5.googleusercontent.com/-biyiyWcJ9MU/URqvKculiAI/AAAAAAAAAbs/jyPsCplJOpE/s1024/Windmill.jpg", "https://lh4.googleusercontent.com/-PDT167_xRdA/URqvK36mLcI/AAAAAAAAAbs/oi2ik9QseMI/s1024/Windmills.jpg", "https://lh5.googleusercontent.com/-kI_QdYx7VlU/URqvLXCB6gI/AAAAAAAAAbs/N31vlZ6u89o/s1024/Yet%252520Another%252520Rockaway%252520Sunset.jpg", "https://lh4.googleusercontent.com/-e9NHZ5k5MSs/URqvMIBZjtI/AAAAAAAAAbs/1fV810rDNfQ/s1024/Yosemite%252520Tree.jpg", }; /** * This are PicasaWeb thumbnail URLs and could potentially change. Ideally the PicasaWeb API * should be used to fetch the URLs. *

* Credit to Romain Guy for the photos: * http://www.curious-creature.org/ * https://plus.google.com/109538161516040592207/about * http://www.flickr.com/photos/romainguy */ public final static String[] imageThumbUrls = new String[]{ "https://lh6.googleusercontent.com/-55osAWw3x0Q/URquUtcFr5I/AAAAAAAAAbs/rWlj1RUKrYI/s240-c/A%252520Photographer.jpg", "https://lh4.googleusercontent.com/--dq8niRp7W4/URquVgmXvgI/AAAAAAAAAbs/-gnuLQfNnBA/s240-c/A%252520Song%252520of%252520Ice%252520and%252520Fire.jpg", "https://lh5.googleusercontent.com/-7qZeDtRKFKc/URquWZT1gOI/AAAAAAAAAbs/hqWgteyNXsg/s240-c/Another%252520Rockaway%252520Sunset.jpg", "https://lh3.googleusercontent.com/--L0Km39l5J8/URquXHGcdNI/AAAAAAAAAbs/3ZrSJNrSomQ/s240-c/Antelope%252520Butte.jpg", "https://lh6.googleusercontent.com/-8HO-4vIFnlw/URquZnsFgtI/AAAAAAAAAbs/WT8jViTF7vw/s240-c/Antelope%252520Hallway.jpg", "https://lh4.googleusercontent.com/-WIuWgVcU3Qw/URqubRVcj4I/AAAAAAAAAbs/YvbwgGjwdIQ/s240-c/Antelope%252520Walls.jpg", "https://lh6.googleusercontent.com/-UBmLbPELvoQ/URqucCdv0kI/AAAAAAAAAbs/IdNhr2VQoQs/s240-c/Apre%2525CC%252580s%252520la%252520Pluie.jpg", "https://lh3.googleusercontent.com/-s-AFpvgSeew/URquc6dF-JI/AAAAAAAAAbs/Mt3xNGRUd68/s240-c/Backlit%252520Cloud.jpg", "https://lh5.googleusercontent.com/-bvmif9a9YOQ/URquea3heHI/AAAAAAAAAbs/rcr6wyeQtAo/s240-c/Bee%252520and%252520Flower.jpg", "https://lh5.googleusercontent.com/-n7mdm7I7FGs/URqueT_BT-I/AAAAAAAAAbs/9MYmXlmpSAo/s240-c/Bonzai%252520Rock%252520Sunset.jpg", "https://lh6.googleusercontent.com/-4CN4X4t0M1k/URqufPozWzI/AAAAAAAAAbs/8wK41lg1KPs/s240-c/Caterpillar.jpg", "https://lh3.googleusercontent.com/-rrFnVC8xQEg/URqufdrLBaI/AAAAAAAAAbs/s69WYy_fl1E/s240-c/Chess.jpg", "https://lh5.googleusercontent.com/-WVpRptWH8Yw/URqugh-QmDI/AAAAAAAAAbs/E-MgBgtlUWU/s240-c/Chihuly.jpg", "https://lh5.googleusercontent.com/-0BDXkYmckbo/URquhKFW84I/AAAAAAAAAbs/ogQtHCTk2JQ/s240-c/Closed%252520Door.jpg", "https://lh3.googleusercontent.com/-PyggXXZRykM/URquh-kVvoI/AAAAAAAAAbs/hFtDwhtrHHQ/s240-c/Colorado%252520River%252520Sunset.jpg", "https://lh3.googleusercontent.com/-ZAs4dNZtALc/URquikvOCWI/AAAAAAAAAbs/DXz4h3dll1Y/s240-c/Colors%252520of%252520Autumn.jpg", "https://lh4.googleusercontent.com/-GztnWEIiMz8/URqukVCU7bI/AAAAAAAAAbs/jo2Hjv6MZ6M/s240-c/Countryside.jpg", "https://lh4.googleusercontent.com/-bEg9EZ9QoiM/URquklz3FGI/AAAAAAAAAbs/UUuv8Ac2BaE/s240-c/Death%252520Valley%252520-%252520Dunes.jpg", "https://lh6.googleusercontent.com/-ijQJ8W68tEE/URqulGkvFEI/AAAAAAAAAbs/zPXvIwi_rFw/s240-c/Delicate%252520Arch.jpg", "https://lh5.googleusercontent.com/-Oh8mMy2ieng/URqullDwehI/AAAAAAAAAbs/TbdeEfsaIZY/s240-c/Despair.jpg", "https://lh5.googleusercontent.com/-gl0y4UiAOlk/URqumC_KjBI/AAAAAAAAAbs/PM1eT7dn4oo/s240-c/Eagle%252520Fall%252520Sunrise.jpg", "https://lh3.googleusercontent.com/-hYYHd2_vXPQ/URqumtJa9eI/AAAAAAAAAbs/wAalXVkbSh0/s240-c/Electric%252520Storm.jpg", "https://lh5.googleusercontent.com/-PyY_yiyjPTo/URqunUOhHFI/AAAAAAAAAbs/azZoULNuJXc/s240-c/False%252520Kiva.jpg", "https://lh6.googleusercontent.com/-PYvLVdvXywk/URqunwd8hfI/AAAAAAAAAbs/qiMwgkFvf6I/s240-c/Fitzgerald%252520Streaks.jpg", "https://lh4.googleusercontent.com/-KIR_UobIIqY/URquoCZ9SlI/AAAAAAAAAbs/Y4d4q8sXu4c/s240-c/Foggy%252520Sunset.jpg", "https://lh6.googleusercontent.com/-9lzOk_OWZH0/URquoo4xYoI/AAAAAAAAAbs/AwgzHtNVCwU/s240-c/Frantic.jpg", "https://lh3.googleusercontent.com/-0X3JNaKaz48/URqupH78wpI/AAAAAAAAAbs/lHXxu_zbH8s/s240-c/Golden%252520Gate%252520Afternoon.jpg", "https://lh6.googleusercontent.com/-95sb5ag7ABc/URqupl95RDI/AAAAAAAAAbs/g73R20iVTRA/s240-c/Golden%252520Gate%252520Fog.jpg", "https://lh3.googleusercontent.com/-JB9v6rtgHhk/URqup21F-zI/AAAAAAAAAbs/64Fb8qMZWXk/s240-c/Golden%252520Grass.jpg", "https://lh4.googleusercontent.com/-EIBGfnuLtII/URquqVHwaRI/AAAAAAAAAbs/FA4McV2u8VE/s240-c/Grand%252520Teton.jpg", "https://lh4.googleusercontent.com/-WoMxZvmN9nY/URquq1v2AoI/AAAAAAAAAbs/grj5uMhL6NA/s240-c/Grass%252520Closeup.jpg", "https://lh3.googleusercontent.com/-6hZiEHXx64Q/URqurxvNdqI/AAAAAAAAAbs/kWMXM3o5OVI/s240-c/Green%252520Grass.jpg", "https://lh5.googleusercontent.com/-6LVb9OXtQ60/URquteBFuKI/AAAAAAAAAbs/4F4kRgecwFs/s240-c/Hanging%252520Leaf.jpg", "https://lh4.googleusercontent.com/-zAvf__52ONk/URqutT_IuxI/AAAAAAAAAbs/D_bcuc0thoU/s240-c/Highway%2525201.jpg", "https://lh6.googleusercontent.com/-H4SrUg615rA/URquuL27fXI/AAAAAAAAAbs/4aEqJfiMsOU/s240-c/Horseshoe%252520Bend%252520Sunset.jpg", "https://lh4.googleusercontent.com/-JhFi4fb_Pqw/URquuX-QXbI/AAAAAAAAAbs/IXpYUxuweYM/s240-c/Horseshoe%252520Bend.jpg", "https://lh5.googleusercontent.com/-UGgssvFRJ7g/URquueyJzGI/AAAAAAAAAbs/yYIBlLT0toM/s240-c/Into%252520the%252520Blue.jpg", "https://lh3.googleusercontent.com/-CH7KoupI7uI/URquu0FF__I/AAAAAAAAAbs/R7GDmI7v_G0/s240-c/Jelly%252520Fish%2525202.jpg", "https://lh4.googleusercontent.com/-pwuuw6yhg8U/URquvPxR3FI/AAAAAAAAAbs/VNGk6f-tsGE/s240-c/Jelly%252520Fish%2525203.jpg", "https://lh5.googleusercontent.com/-GoUQVw1fnFw/URquv6xbC0I/AAAAAAAAAbs/zEUVTQQ43Zc/s240-c/Kauai.jpg", "https://lh6.googleusercontent.com/-8QdYYQEpYjw/URquwvdh88I/AAAAAAAAAbs/cktDy-ysfHo/s240-c/Kyoto%252520Sunset.jpg", "https://lh4.googleusercontent.com/-vPeekyDjOE0/URquwzJ28qI/AAAAAAAAAbs/qxcyXULsZrg/s240-c/Lake%252520Tahoe%252520Colors.jpg", "https://lh4.googleusercontent.com/-xBPxWpD4yxU/URquxWHk8AI/AAAAAAAAAbs/ARDPeDYPiMY/s240-c/Lava%252520from%252520the%252520Sky.jpg", "https://lh3.googleusercontent.com/-897VXrJB6RE/URquxxxd-5I/AAAAAAAAAbs/j-Cz4T4YvIw/s240-c/Leica%25252050mm%252520Summilux.jpg", "https://lh5.googleusercontent.com/-qSJ4D4iXzGo/URquyDWiJ1I/AAAAAAAAAbs/k2pBXeWehOA/s240-c/Leica%25252050mm%252520Summilux.jpg", "https://lh6.googleusercontent.com/-dwlPg83vzLg/URquylTVuFI/AAAAAAAAAbs/G6SyQ8b4YsI/s240-c/Leica%252520M8%252520%252528Front%252529.jpg", "https://lh3.googleusercontent.com/-R3_EYAyJvfk/URquzQBv8eI/AAAAAAAAAbs/b9xhpUM3pEI/s240-c/Light%252520to%252520Sand.jpg", "https://lh3.googleusercontent.com/-fHY5h67QPi0/URqu0Cp4J1I/AAAAAAAAAbs/0lG6m94Z6vM/s240-c/Little%252520Bit%252520of%252520Paradise.jpg", "https://lh5.googleusercontent.com/-TzF_LwrCnRM/URqu0RddPOI/AAAAAAAAAbs/gaj2dLiuX0s/s240-c/Lone%252520Pine%252520Sunset.jpg", "https://lh3.googleusercontent.com/-4HdpJ4_DXU4/URqu046dJ9I/AAAAAAAAAbs/eBOodtk2_uk/s240-c/Lonely%252520Rock.jpg", "https://lh6.googleusercontent.com/-erbF--z-W4s/URqu1ajSLkI/AAAAAAAAAbs/xjDCDO1INzM/s240-c/Longue%252520Vue.jpg", "https://lh6.googleusercontent.com/-0CXJRdJaqvc/URqu1opNZNI/AAAAAAAAAbs/PFB2oPUU7Lk/s240-c/Look%252520Me%252520in%252520the%252520Eye.jpg", "https://lh3.googleusercontent.com/-D_5lNxnDN6g/URqu2Tk7HVI/AAAAAAAAAbs/p0ddca9W__Y/s240-c/Lost%252520in%252520a%252520Field.jpg", "https://lh6.googleusercontent.com/-flsqwMrIk2Q/URqu24PcmjI/AAAAAAAAAbs/5ocIH85XofM/s240-c/Marshall%252520Beach%252520Sunset.jpg", "https://lh4.googleusercontent.com/-Y4lgryEVTmU/URqu28kG3gI/AAAAAAAAAbs/OjXpekqtbJ4/s240-c/Mono%252520Lake%252520Blue.jpg", "https://lh4.googleusercontent.com/-AaHAJPmcGYA/URqu3PIldHI/AAAAAAAAAbs/lcTqk1SIcRs/s240-c/Monument%252520Valley%252520Overlook.jpg", "https://lh4.googleusercontent.com/-vKxfdQ83dQA/URqu31Yq_BI/AAAAAAAAAbs/OUoGk_2AyfM/s240-c/Moving%252520Rock.jpg", "https://lh5.googleusercontent.com/-CG62QiPpWXg/URqu4ia4vRI/AAAAAAAAAbs/0YOdqLAlcAc/s240-c/Napali%252520Coast.jpg", "https://lh6.googleusercontent.com/-wdGrP5PMmJQ/URqu5PZvn7I/AAAAAAAAAbs/m0abEcdPXe4/s240-c/One%252520Wheel.jpg", "https://lh6.googleusercontent.com/-6WS5DoCGuOA/URqu5qx1UgI/AAAAAAAAAbs/giMw2ixPvrY/s240-c/Open%252520Sky.jpg", "https://lh6.googleusercontent.com/-u8EHKj8G8GQ/URqu55sM6yI/AAAAAAAAAbs/lIXX_GlTdmI/s240-c/Orange%252520Sunset.jpg", "https://lh6.googleusercontent.com/-74Z5qj4bTDE/URqu6LSrJrI/AAAAAAAAAbs/XzmVkw90szQ/s240-c/Orchid.jpg", "https://lh6.googleusercontent.com/-lEQE4h6TePE/URqu6t_lSkI/AAAAAAAAAbs/zvGYKOea_qY/s240-c/Over%252520there.jpg", "https://lh5.googleusercontent.com/-cauH-53JH2M/URqu66v_USI/AAAAAAAAAbs/EucwwqclfKQ/s240-c/Plumes.jpg", "https://lh3.googleusercontent.com/-eDLT2jHDoy4/URqu7axzkAI/AAAAAAAAAbs/iVZE-xJ7lZs/s240-c/Rainbokeh.jpg", "https://lh5.googleusercontent.com/-j1NLqEFIyco/URqu8L1CGcI/AAAAAAAAAbs/aqZkgX66zlI/s240-c/Rainbow.jpg", "https://lh5.googleusercontent.com/-DRnqmK0t4VU/URqu8XYN9yI/AAAAAAAAAbs/LgvF_592WLU/s240-c/Rice%252520Fields.jpg", "https://lh3.googleusercontent.com/-hwh1v3EOGcQ/URqu8qOaKwI/AAAAAAAAAbs/IljRJRnbJGw/s240-c/Rockaway%252520Fire%252520Sky.jpg", "https://lh5.googleusercontent.com/-wjV6FQk7tlk/URqu9jCQ8sI/AAAAAAAAAbs/RyYUpdo-c9o/s240-c/Rockaway%252520Flow.jpg", "https://lh6.googleusercontent.com/-6cAXNfo7D20/URqu-BdzgPI/AAAAAAAAAbs/OmsYllzJqwo/s240-c/Rockaway%252520Sunset%252520Sky.jpg", "https://lh3.googleusercontent.com/-sl8fpGPS-RE/URqu_BOkfgI/AAAAAAAAAbs/Dg2Fv-JxOeg/s240-c/Russian%252520Ridge%252520Sunset.jpg", "https://lh6.googleusercontent.com/-gVtY36mMBIg/URqu_q91lkI/AAAAAAAAAbs/3CiFMBcy5MA/s240-c/Rust%252520Knot.jpg", "https://lh6.googleusercontent.com/-GHeImuHqJBE/URqu_FKfVLI/AAAAAAAAAbs/axuEJeqam7Q/s240-c/Sailing%252520Stones.jpg", "https://lh3.googleusercontent.com/-hBbYZjTOwGc/URqu_ycpIrI/AAAAAAAAAbs/nAdJUXnGJYE/s240-c/Seahorse.jpg", "https://lh3.googleusercontent.com/-Iwi6-i6IexY/URqvAYZHsVI/AAAAAAAAAbs/5ETWl4qXsFE/s240-c/Shinjuku%252520Street.jpg", "https://lh6.googleusercontent.com/-amhnySTM_MY/URqvAlb5KoI/AAAAAAAAAbs/pFCFgzlKsn0/s240-c/Sierra%252520Heavens.jpg", "https://lh5.googleusercontent.com/-dJgjepFrYSo/URqvBVJZrAI/AAAAAAAAAbs/v-F5QWpYO6s/s240-c/Sierra%252520Sunset.jpg", "https://lh4.googleusercontent.com/-Z4zGiC5nWdc/URqvBdEwivI/AAAAAAAAAbs/ZRZR1VJ84QA/s240-c/Sin%252520Lights.jpg", "https://lh4.googleusercontent.com/-_0cYiWW8ccY/URqvBz3iM4I/AAAAAAAAAbs/9N_Wq8MhLTY/s240-c/Starry%252520Lake.jpg", "https://lh3.googleusercontent.com/-A9LMoRyuQUA/URqvCYx_JoI/AAAAAAAAAbs/s7sde1Bz9cI/s240-c/Starry%252520Night.jpg", "https://lh3.googleusercontent.com/-KtLJ3k858eY/URqvC_2h_bI/AAAAAAAAAbs/zzEBImwDA_g/s240-c/Stream.jpg", "https://lh5.googleusercontent.com/-dFB7Lad6RcA/URqvDUftwWI/AAAAAAAAAbs/BrhoUtXTN7o/s240-c/Strip%252520Sunset.jpg", "https://lh5.googleusercontent.com/-at6apgFiN20/URqvDyffUZI/AAAAAAAAAbs/clABCx171bE/s240-c/Sunset%252520Hills.jpg", "https://lh4.googleusercontent.com/-7-EHhtQthII/URqvEYTk4vI/AAAAAAAAAbs/QSJZoB3YjVg/s240-c/Tenaya%252520Lake%2525202.jpg", "https://lh6.googleusercontent.com/-8MrjV_a-Pok/URqvFC5repI/AAAAAAAAAbs/9inKTg9fbCE/s240-c/Tenaya%252520Lake.jpg", "https://lh5.googleusercontent.com/-B1HW-z4zwao/URqvFWYRwUI/AAAAAAAAAbs/8Peli53Bs8I/s240-c/The%252520Cave%252520BW.jpg", "https://lh3.googleusercontent.com/-PO4E-xZKAnQ/URqvGRqjYkI/AAAAAAAAAbs/42nyADFsXag/s240-c/The%252520Fisherman.jpg", "https://lh4.googleusercontent.com/-iLyZlzfdy7s/URqvG0YScdI/AAAAAAAAAbs/1J9eDKmkXtk/s240-c/The%252520Night%252520is%252520Coming.jpg", "https://lh6.googleusercontent.com/-G-k7YkkUco0/URqvHhah6fI/AAAAAAAAAbs/_taQQG7t0vo/s240-c/The%252520Road.jpg", "https://lh6.googleusercontent.com/-h-ALJt7kSus/URqvIThqYfI/AAAAAAAAAbs/ejiv35olWS8/s240-c/Tokyo%252520Heights.jpg", "https://lh5.googleusercontent.com/-Hy9k-TbS7xg/URqvIjQMOxI/AAAAAAAAAbs/RSpmmOATSkg/s240-c/Tokyo%252520Highway.jpg", "https://lh6.googleusercontent.com/-83oOvMb4OZs/URqvJL0T7lI/AAAAAAAAAbs/c5TECZ6RONM/s240-c/Tokyo%252520Smog.jpg", "https://lh3.googleusercontent.com/-FB-jfgREEfI/URqvJI3EXAI/AAAAAAAAAbs/XfyweiRF4v8/s240-c/Tufa%252520at%252520Night.jpg", "https://lh4.googleusercontent.com/-vngKD5Z1U8w/URqvJUCEgPI/AAAAAAAAAbs/ulxCMVcU6EU/s240-c/Valley%252520Sunset.jpg", "https://lh6.googleusercontent.com/-DOz5I2E2oMQ/URqvKMND1kI/AAAAAAAAAbs/Iqf0IsInleo/s240-c/Windmill%252520Sunrise.jpg", "https://lh5.googleusercontent.com/-biyiyWcJ9MU/URqvKculiAI/AAAAAAAAAbs/jyPsCplJOpE/s240-c/Windmill.jpg", "https://lh4.googleusercontent.com/-PDT167_xRdA/URqvK36mLcI/AAAAAAAAAbs/oi2ik9QseMI/s240-c/Windmills.jpg", "https://lh5.googleusercontent.com/-kI_QdYx7VlU/URqvLXCB6gI/AAAAAAAAAbs/N31vlZ6u89o/s240-c/Yet%252520Another%252520Rockaway%252520Sunset.jpg", "https://lh4.googleusercontent.com/-e9NHZ5k5MSs/URqvMIBZjtI/AAAAAAAAAbs/1fV810rDNfQ/s240-c/Yosemite%252520Tree.jpg", }; } ================================================ FILE: app/src/main/java/com/networking/utils/Utils.java ================================================ /* * Copyright (C) 2016 Amit Shekhar * Copyright (C) 2011 Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.networking.utils; import android.content.Context; import android.os.Environment; import android.support.v4.content.ContextCompat; import android.util.Log; import com.androidnetworking.error.ANError; import java.io.File; /** * Created by amitshekhar on 04/04/16. */ public class Utils { public static String getRootDirPath(Context context) { if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { File file = ContextCompat.getExternalFilesDirs(context.getApplicationContext(), null)[0]; return file.getAbsolutePath(); } else { return context.getApplicationContext().getFilesDir().getAbsolutePath(); } } public static void logError(String TAG,ANError error) { if (error.getErrorCode() != 0) { // received ANError from server // error.getErrorCode() - the ANError code from server // error.getErrorBody() - the ANError body from server // error.getErrorDetail() - just a ANError detail Log.d(TAG, "onError errorCode : " + error.getErrorCode()); Log.d(TAG, "onError errorBody : " + error.getErrorBody()); Log.d(TAG, "onError errorDetail : " + error.getErrorDetail()); } else { // error.getErrorDetail() : connectionError, parseError, requestCancelledError Log.d(TAG, "onError errorDetail : " + error.getErrorDetail()); } } } ================================================ FILE: app/src/main/res/drawable/photogrid_list_selector.xml ================================================ ================================================ FILE: app/src/main/res/layout/activity_api_test.xml ================================================