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