diff --git a/.classpath b/.classpath deleted file mode 100644 index 14fcf527f..000000000 --- a/.classpath +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - diff --git a/.github/workflows/gradle-wrapper-validation.yml b/.github/workflows/gradle-wrapper-validation.yml new file mode 100644 index 000000000..405a2b306 --- /dev/null +++ b/.github/workflows/gradle-wrapper-validation.yml @@ -0,0 +1,10 @@ +name: "Validate Gradle Wrapper" +on: [push, pull_request] + +jobs: + validation: + name: "Validation" + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: gradle/wrapper-validation-action@v1 diff --git a/.gitignore b/.gitignore old mode 100644 new mode 100755 index 8842bb26b..d3b225642 --- a/.gitignore +++ b/.gitignore @@ -1,11 +1,40 @@ +# Custom _site + +# Ant MANIFEST.MF ./*.jar build.num build + +# ADT +.classpath +.project +.settings local.properties -bin/ -gen/ +bin +gen _layouts +proguard.cfg + +# OSX .DS_Store + +# Github gh-pages + +# Gradle +.gradle +build + +# IDEA +*.iml +*.ipr +*.iws +out +.idea + +# Maven +target +release.properties +pom.xml.* diff --git a/.project b/.project deleted file mode 100644 index a97931397..000000000 --- a/.project +++ /dev/null @@ -1,33 +0,0 @@ - - - android-async-http - - - - - - com.android.ide.eclipse.adt.ResourceManagerBuilder - - - - - com.android.ide.eclipse.adt.PreCompilerBuilder - - - - - org.eclipse.jdt.core.javabuilder - - - - - com.android.ide.eclipse.adt.ApkBuilder - - - - - - com.android.ide.eclipse.adt.AndroidNature - org.eclipse.jdt.core.javanature - - diff --git a/.travis.yml b/.travis.yml new file mode 100755 index 000000000..ddc10848e --- /dev/null +++ b/.travis.yml @@ -0,0 +1,16 @@ +language: android +sudo: false +dist: trusty +jdk: openjdk8 +android: + components: + - platform-tools + - tools + - build-tools-28.0.3 + - android-28 + - extra-android-m2repository + - extra-google-m2repository + licenses: + - '.+' +script: + - ./gradlew clean assemble check diff --git a/AndroidManifest.xml b/AndroidManifest.xml deleted file mode 100644 index 5684532ce..000000000 --- a/AndroidManifest.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 000000000..72c4b65f6 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,161 @@ +# CHANGELOG + +## 1.4.11 + + - fix SNI issue on lower android device with Conscrypt + +## 1.4.10 + + - Fixed IP/name resolution errors #998 + - Fixed SNI compatibility + - Upgraded library HttpClient 4.5.8 from 4.3.6 + +## 1.4.9 (released 19. 9. 2015) + +Complete list of commits included is here [https://github.com/loopj/android-async-http/commits/1.4.9](https://github.com/loopj/android-async-http/commits/1.4.9) +List of closed issues is here [https://github.com/loopj/android-async-http/issues?milestone=8&state=closed](https://github.com/loopj/android-async-http/issues?milestone=8&state=closed) + + - **IMPORTANT**, We've switched library from using `org.apache.http` to use `cz.msebera.android.httpclient`, you have to update all your code + - Library is from now on using upstream version of HttpClient libraries, provided by repackaging project https://github.com/smarek/httpclient-android/ + - Achieved API23 Compatibility, see #830 for more info + - Added HeadSample into sample application, to verify Head request works as it should + - FileAsyncHttpResponseHandler now has constructor with `usePoolThread` param, which causes callbacks to be fired from ThreadPool instead of main looper + +## 1.4.8 (released 17. 7. 2015) + +Complete list of commits included is here [https://github.com/loopj/android-async-http/commits/1.4.8](https://github.com/loopj/android-async-http/commits/1.4.8) +List of closed issues is here [https://github.com/loopj/android-async-http/issues?milestone=7&state=closed](https://github.com/loopj/android-async-http/issues?milestone=7&state=closed) + + - New constructor for BinaryHttpResponseHandler which takes Looper as argument (thanks to @ScottFrank) + - SaxAsyncHttpResponseHandler can be now provided with custom charset, instead of just using default one + - Library LogCat tags now use shorter form (forced through Lint checks), appendix "ResponseHandler" shortened to "RH" + - Updated documentation on `RequestHandle.cancel(boolean)` and returning correct response according to handle state + - SaxAsyncHttpResponseHandler onFailure(int, Header[], byte[], Throwable) used wrong fallback to onSuccess(int, Header[], T), fixed to onFailure(int, Header[], T), where T extends SAX DefaultHandler + - Regression fix on onProgress(int,int) documentation + - Sample application now can be built with LeakCanary, use i.e. `gradle :sample:installWithLeakCanaryDebug` to use it + - Updated RequestParams documentation on handling arrays, sets and maps, along with new RequestParamsDebug sample + - Added BlackholeHttpResponseHandler implementation, which discards all response contents and silents all various log messages (see #416) + - Added LogInterface, it's default implementation and interface option to disable/enable logging library-wide and set logging verbosity + - Added option to TAG RequestHandle and cancel all requests matching specified TAG through `AsyncHttpClient.cancelRequestsByTAG(Object TAG)` + - Removed deprecated `getTimeout()` replaced by `getConnectTimeout()` and `getResponseTimeout()` respectively + - Removed deprecated `clearBasicAuth()` replaced by `clearCredentialsProvider()` + +## 1.4.7 (released 9. 5. 2015) + +Complete list of commits included is here [https://github.com/loopj/android-async-http/commits/1.4.7](https://github.com/loopj/android-async-http/commits/1.4.7) +List of closed issues is here [https://github.com/loopj/android-async-http/issues?milestone=6&state=closed](https://github.com/loopj/android-async-http/issues?milestone=6&state=closed) + + - Fixed crash when canceling through RequestHandle from UI Thread (NetworkOnMainThreadException) + - Fixed URL encoding feature, that was breaking whole URL, not just path and query parts + - FileAsyncHttpResponseHandler now checks that target file path is available or can be created + - DataAsyncHttpResponseHandler was sending cancel notification instead of progress notification, fixed + - Added support for HTTP PATCH requests + - Fixed Assert exception when mkdirs in FileAsyncHttpResponseHandler tries to create dirs that already exists + - Provided option to easily override ClientConnectionManager provision in AsyncHttpClient + - Changed onProgress from (int,int) to (long,long) for dealing with large transfers + - Renamed typo of `preemtive` to `preemptive` (preemptive basic auth) + - Added option to put File array in RequestParams + - RequestParams now support forcing Content-Type into `multipart/form-data` even if there are no files/streams to be multiparted + - Gradle added support for installing to local maven repository, through `gradle installArchives` task + - Added support for Json RFC5179 in JsonHttpResponseHandler + +## 1.4.6 (released 7. 9. 2014) + +Complete list of commits included is here [https://github.com/loopj/android-async-http/commits/1.4.6](https://github.com/loopj/android-async-http/commits/1.4.6) +List of closed issues is here [https://github.com/loopj/android-async-http/issues?milestone=4&state=closed](https://github.com/loopj/android-async-http/issues?milestone=2&state=closed) + + - Fixed missing boundary when passing content-type as call param along with HttpEntity + - Added warnings for not overriden calls in JsonHttpResponseHandler (and others) + - RequestParams now implement Serializable, to support storing them and passing them along + - Added option to add File part with custom file name (overriding the real file name) + - Fixed not-escaped contents in JsonStreamEntity + - Separated connect and response timeout settings + - Allowed to pass Looper into *HttpResponseHandler classes + - Fixed reporting progress on GZIP compressed down-streams + - Added more samples (eg. AsyncBackgroundThreadSample.java, ContentTypeForHttpEntitySample.java, PrePostProcessingSample.java) + - Added option to pre- and post- process data in AsyncHttpRequest.java via subclass (see PrePostProcessingSample.java) + - Fixed ConcurrentModificationException on AsyncHttpClient.cancelRequests + - Fixed handling BOM in decoding response in TextHttpResponseHandler and JsonHttpResponseHandler + +## 1.4.5 (released 22. 6. 2014) + +Complete list of commits included is here [https://github.com/loopj/android-async-http/commits/1.4.5](https://github.com/loopj/android-async-http/commits/1.4.5) +List of closed issues is here [https://github.com/loopj/android-async-http/issues?milestone=2&state=closed](https://github.com/loopj/android-async-http/issues?milestone=2&state=closed) + + - Support for circular and relative redirects + - Added support for SAX parsing, see `SaxAsyncHttpResponseHandler` + - Fixed Threading issue when used in Service or non-UI Thread context + - Fixed GZIPInputStream issue when running in StrictMode + - Removed unnecessary (ambiguous) callback methods (were deprecated in 1.4.4) + - Added JsonStreamerEntity to allow up streaming JSON data + - Added possibility to modify blacklisted/whitelisted exceptions (see `RetryHandler`) + - Using `newCachedThreadPool()` as default ExecutorService in library, with option to change it via main interface + - Added `ResponseHandlerInterface` to support completely custom implementations of response handlers + - Added `onProgress(int,int)` callback, which is used for upstream progress logging (eg. Progressbar dialogs) + - Fixed "division by zero" in default response handler + - Added DataAsyncHttpResponseHandler, which has extra callback method which receives partially received data + - Fixed problem with uploading more than 2 files (changes in SimpleMultipartEntity) + - Fixed problem where on GarbageCollectors activity there was no callback received + - Added warning for cases, where headers overwrite each other (between common headers and per-request headers) + - Safely closing IO streams (both upstream and downstream) + - Fixed PersistentCookieStore issue, where non-persistent cookies were stored and added option to delete stored cookie + - Fixed networkOnMainThreadException when canceling requests (`AsyncHttpClient#cancel(boolean)`) + - Removed default User-Agent definition from library + - Fixed handling null URLs in default interface calls + - Allowed to subclass AsyncHttpClient and simply provide custom AsyncHttpRequest object (`AsyncHttpClient#newAsyncHttpRequest`) + - Changed project structure to be default Intellij IDEA structure (eg. library/src/main/java) + - Catching UnsupportedEncodingException default Async and Text response handlers + - Added strict Lint checking for both Library and Sample application + - Added example implementations in Sample application + - Requests threading (ThreadPool usage, 6 seconds delay on response) + - Synchronous request (from Activity and IntentService) + - SAX Parsing the response + - Retry request sample + - Handling 302 redirects + - RangeResponse (working with partially received data) + - Basic usage of GET, POST, PUT, DELETE + - JSON response parsing + - GZIP compressed communication + - Binary handler (receives `byte[]` without parsing/converting) + - File response handler (saving response directly into given File) + - Self-signed CA sample (how to pin SSL certificate or add custom trust-chain for requests) + - Persistent cookies store (persisting cookies between requests) + - Post multi-part encoded Files (SimpleMultipartEntity) + - Jackson JSON integration + +## 1.4.4 (released 28. 10. 2013) + +Complete list of commits included is here [https://github.com/loopj/android-async-http/commits/1.4.4](https://github.com/loopj/android-async-http/commits/1.4.4) +List of closed issues is here [https://github.com/loopj/android-async-http/issues?milestone=1&state=closed](https://github.com/loopj/android-async-http/issues?milestone=1&state=closed) + + - Added FileAsyncHttpResponseHandler for direct saving response into File instead of device memory + - JsonHttpResponseHandler now parsing JSON in separate thread + - Interface method to allow/deny handling of http redirects + - Added method to delete previously set header (AsyncHttpClient.java) + - Not creating new Thread if call initiated outside of UI Thread (broken, fixed in 1.4.5) + - Support for changing response Charset (default still UTF-8) + - Allow setting maximum retries count (AsyncHttpClient.java) + - SimpleMultipartEntity now allows repeated usage (`HttpEntity.isRepeatable()`) + - Added custom SSLSocketFactory to allow certificate pinning and accepting self-signed or untrusted SSL certificates + - Callbacks to return HTTP status code and response Headers + - Added support for unsetting Basic Auth params + - Added support for non-standard HTTP and HTTPS ports (new constructors of `AsyncHttpClient`) + - Allowed to change dynamically allowed content-types for BinaryHttpResponseHandler per-response-handler (was static previously) + - Added support for setting proxy, optionally with authentication + - `AsyncHttpClient#setProxy(String hostname, int port, String username, String password)` + - Support for passing Maps, Sets and Lists via RequestParams + - Properly chaining callback methods (onSuccess, onFailure, ...) in descendant order by number of function params + - Fixed incorrect handling of URLs with spaces after redirect + - now sanitizes spaces within URL both on-request and on-redirect + - Added RequestHandle which can be used to cancel and/or check request status + - Is returned for each call (`.post(...)`, `.get(...)`, `.head(...)`, `.put(...)`, etc..) + - Added BaseJsonHttpResponseHandler to simplify integration with Jackson JSON, Gson and other JSON parsing libraries + - Added Sample application to demonstrate functions and usage + - Using [https://httpbin.org/](https://httpbin.org/) to test methods + - Enforcing INTERNET permission + - Support for Gradle buildscript + - Support for Travis CI (Continuous Integration) testing + - Dropped support for Eclipse ADT usage (obsolete) + - Added HTTP HEAD method support + - Releasing both AAR and JAR (+javadoc and sources) into Maven Central repository + - Added tons of mising Javadoc for both classes and methods diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 000000000..fa99f5847 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,47 @@ +CONTRIBUTING +============ +AsyncHttpClient is an open-source project made by developers for developers! + +If you would like to contribute to the project, it's really great. You can contribute in a variety of ways: + + * Help us with test cases and examples for the Wiki (and kindly follow our [Coding Standards](#coding-standards)) + * If you have a good idea/patch for the project, create a [pull request](#pull-requests) + * Found a bug? You're more than welcome to [submit an issue](#issues) + * Help other fellow developers solve their problems, you're welcome to do so in issues + +We do require certain guidelines to be followed so that the quality of the project remains top-notch: + +PULL requests +------------- +When you submit a patch or a new functionality for the project, you must open a pull request. We will get to the pull request as soon as possible, investigate what functionality or bug fixes have been added and decide whether to include it in the library or not -- for the benefit of everyone. + +**You agree that all contributions that you make to the library will be distributed further under the same license as the library itself (Apache V2).** + +Don't be discouraged if your pull request is rejected. This is not a deadline and sometimes with a proper explanation on your side, we are persuaded to merge in the request. Just remember that this is a library for everyone and as such must meet certain, generic rules that we would like to believe are following. + +ISSUES +--------- + +![Read the ISSUES?](https://i.imgur.com/LPWyLe7.jpg "Read the ISSUES?") + +The issues system is the place to report bugs and not for submitting patches or new functionality. As helpful as we would like to be, we cannot replace the developer and we certainly do not see what you're seeing. So when you come to report an issue, follow these simple rules: + + * Report bugs in the English language only + * Use Markdown to format your issue in a fashionable way (easier to read): [Familiarize yourself](https://help.github.com/articles/github-flavored-markdown) + * If the issue is due to a crash, include the stack trace -- `throwable.printStackTrace()` -- and any other detail that will shed light on the problem + * We need to see the source code (minus certain details that you think are confidential) that caused the problem in the first place, so include it too + +Opening issues without providing us with the information necessary to debug and fix it is useless; so we will close such issues within 7 days period + +CODING STANDARDS +---------------- +We need you to follow certain rules when sending source code contributions. These are the basic principles that we ourselves abide to and we require that you do so as well: + + * Do not use the Tab character (it's in first place for a reason) + * Indentation is 4 spaces + * Include the copyright info (as in other files) at the top of the class file + * You must provide proper Javadoc, including description, in English for both public and protected methods, classes and properties + * Group packages that belong to the same top-level package together, followed by an empty line + * Add an empty line after and before class/interface declarations, methods and constructors + * Add an empty line before and after a group of properties + * Do not catch generic Exception/Throwable errors, but always catch the most specific type of the exception/error diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 000000000..d64569567 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,202 @@ + + 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. diff --git a/NOTICE.txt b/NOTICE.txt new file mode 100644 index 000000000..792ce018f --- /dev/null +++ b/NOTICE.txt @@ -0,0 +1,9 @@ +Android Async Http Client library +Copyright (c) 2011-2015 James Smith +https://loopj.com + +Copyright (c) 2015-2019 Marek Sebera +htts://msebera.cz + +This product includes software developed by +The Apache Software Foundation (https://www.apache.org/). diff --git a/PUBLISHING.md b/PUBLISHING.md new file mode 100644 index 000000000..9ac180688 --- /dev/null +++ b/PUBLISHING.md @@ -0,0 +1,48 @@ +# Publish to oss.sonatype.org staging repository + +``` +gradle clean +# edit build.gradle to update allprojects.version +# edit gradle.properties to update VERSION_NAME and VERSION_CODE +# edit CHANGELOG.md and add changes for published version +# edit sample/src/main/AndroidManifest.xml and update both versionCode and versionName attributes +# edit README.md and update paths, latest version, repository links and sample codes +gradle check +# fix all possible errors and warnings before publishing +cd library +# publishing only library, so following tasks are run in "library" sub-folder +gradle generateJavadocJar +# this will create javadoc archive check the contents via following cmd (use different name and/or path if needed) +# jar -tf ./library/build/libs/android-async-http-null-Release-1.4.11-javadoc.jar +gradle publish +``` + +# Publish to maven central + +*For Nexus Repository Manager 2.14+* + + - Login into https://oss.sonatype.org/ + - Navigation, choose Build Promotion > Staging Repositories + - Explore if repo was automatically created and if contents do match expectations + - Select repository and use "Close" action, to run pre-publishing checks + - Wait a bit + - Refresh the panel with repositories + - Select repository and use "Release" action, if not available, there are issues, that need to be fixed before publishing + +# In GIT + + +**example code using 1.4.11 as released version** +``` +git tag 1.4.11 +git push origin --tags +``` + +# Github + +in *releases* https://github.com/android-async-http/android-async-http/releases + + - Create new release from appropriate tag (see GIT above) + - Describe in similar terms as in CHANGELOG.md what is being done + - Upload JAR (library, sources and javadoc) and AAR (library) along with the release + - Publish by saving form diff --git a/README.md b/README.md old mode 100644 new mode 100755 index 1602a5343..1ff6c9f85 --- a/README.md +++ b/README.md @@ -1,8 +1,22 @@ Asynchronous Http Client for Android ==================================== +[![Build Status](https://travis-ci.org/android-async-http/android-async-http.png?branch=master)](https://travis-ci.org/android-async-http/android-async-http) -An asynchronous, callback-based Http client for Android built on top of Apache's [HttpClient](http://hc.apache.org/httpcomponents-client-ga/) libraries. +An asynchronous, callback-based Http client for Android built on top of Apache's [HttpClient](https://hc.apache.org/httpcomponents-client-ga/) libraries. +Changelog +--------- + +See what is new in version 1.4.11 released on 29th June 2020 + +https://github.com/android-async-http/android-async-http/blob/1.4.11/CHANGELOG.md + +Javadoc +------- + +Latest Javadoc for 1.4.11 release are available here (also included in Maven repository): + +https://android-async-http.github.io/android-async-http/doc/ Features -------- @@ -11,15 +25,75 @@ Features - Requests use a **threadpool** to cap concurrent resource usage - GET/POST **params builder** (RequestParams) - **Multipart file uploads** with no additional third party libraries -- Tiny size overhead to your application, only **19kb** for everything +- Tiny size overhead to your application, only **60kb** for everything - Automatic smart **request retries** optimized for spotty mobile connections - Automatic **gzip** response decoding support for super-fast requests - Optional built-in response parsing into **JSON** (JsonHttpResponseHandler) - Optional **persistent cookie store**, saves cookies into your app's SharedPreferences +- Support sni with Conscrypt on older android device ([wiki](https://github.com/android-async-http/android-async-http/wiki/Support-SNI-on-lower-android-device)) + +Examples +-------- + +For inspiration and testing on device we've provided Sample Application. +See individual samples [here on Github](https://github.com/android-async-http/android-async-http/tree/1.4.11/sample/src/main/java/com/loopj/android/http/sample) +To run Sample application, simply clone the repository and run this command, to install it on connected device +```java +gradle :sample:installDebug +``` + +Maven +----- +You can now integrate this library in your project via Maven. There are available two kind of builds. + +**releases, maven central** + +https://repo1.maven.org/maven2/com/loopj/android/android-async-http/ +``` +Maven URL: https://repo1.maven.org/maven2/ +GroupId: com.loopj.android +ArtifactId: android-async-http +Version: 1.4.11 +Packaging: JAR or AAR +``` +Gradle +```groovy +repositories { + mavenCentral() +} + +dependencies { + implementation 'com.loopj.android:android-async-http:1.4.11' +} +``` + +**development snapshots** +snapshot might not be published yet + +https://oss.sonatype.org/content/repositories/snapshots/com/loopj/android/android-async-http/ +``` +Maven URL: https://oss.sonatype.org/content/repositories/snapshots/ +GroupId: com.loopj.android +ArtifactId: android-async-http +Version: 1.4.12-SNAPSHOT +Packaging: JAR or AAR +``` +Gradle +```groovy +repositories { + maven { + url 'https://oss.sonatype.org/content/repositories/snapshots/' + } +} +dependencies { + implementation 'com.loopj.android:android-async-http:1.4.11-SNAPSHOT' +} +``` Documentation, Features and Examples ------------------------------------ Full details and documentation can be found on the project page here: -http://loopj.com/android-async-http/ \ No newline at end of file +https://android-async-http.github.io/android-async-http/ + diff --git a/build.gradle b/build.gradle new file mode 100755 index 000000000..2b8e1368e --- /dev/null +++ b/build.gradle @@ -0,0 +1,40 @@ +buildscript { + repositories { + jcenter() + google() + maven { url "https://oss.sonatype.org/content/repositories/snapshots" } + maven { url "https://plugins.gradle.org/m2/" } + } + + dependencies { + classpath 'com.android.tools.build:gradle:4.0.0' + classpath 'com.vanniktech:gradle-android-javadoc-plugin:0.4.0-SNAPSHOT' + classpath 'digital.wup:android-maven-publish:3.6.2' + classpath "gradle.plugin.com.dorongold.plugins:task-tree:1.4" + } +} + +def isReleaseBuild() { + return version.contains("SNAPSHOT") == false +} + +allprojects { + group = 'com.loopj.android' + version = '1.4.11' + + repositories { + google() + jcenter() + mavenCentral() + } + + tasks.withType(JavaCompile) { + options.encoding = "UTF-8" + options.compilerArgs << "-Xlint:unchecked" + options.compilerArgs << "-Xlint:deprecation" + } +} + +apply plugin: 'android-reporting' +apply plugin: 'com.vanniktech.android.javadoc' +apply plugin: 'com.dorongold.task-tree' diff --git a/build.xml b/build.xml deleted file mode 100644 index 1cd94b37b..000000000 --- a/build.xml +++ /dev/null @@ -1,98 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/examples/ExampleUsage.java b/examples/ExampleUsage.java deleted file mode 100644 index 2b7a4fa0a..000000000 --- a/examples/ExampleUsage.java +++ /dev/null @@ -1,14 +0,0 @@ -import com.loopj.android.http.*; - -public class ExampleUsage { - public static void makeRequest() { - AsyncHttpClient client = new AsyncHttpClient(); - - client.get("http://www.google.com/", new AsyncHttpResponseHandler() { - @Override - public void onSuccess(String response) { - System.out.println(response); - } - }); - } -} \ No newline at end of file diff --git a/examples/TwitterRestClient.java b/examples/TwitterRestClient.java deleted file mode 100644 index 387a87114..000000000 --- a/examples/TwitterRestClient.java +++ /dev/null @@ -1,21 +0,0 @@ -// Static wrapper library around AsyncHttpClient - -import com.loopj.android.http.*; - -public class TwitterRestClient { - private static final String BASE_URL = "http://api.twitter.com/1/"; - - private static AsyncHttpClient client = new AsyncHttpClient(); - - public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) { - client.get(getAbsoluteUrl(url), params, responseHandler); - } - - public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) { - client.post(getAbsoluteUrl(url), params, responseHandler); - } - - private static String getAbsoluteUrl(String relativeUrl) { - return BASE_URL + relativeUrl; - } -} \ No newline at end of file diff --git a/examples/TwitterRestClientUsage.java b/examples/TwitterRestClientUsage.java deleted file mode 100644 index a4c89c8ce..000000000 --- a/examples/TwitterRestClientUsage.java +++ /dev/null @@ -1,21 +0,0 @@ -import org.json.*; -import com.loopj.android.http.*; - -class TwitterRestClientUsage { - public void getPublicTimeline() { - TwitterRestClient.get("statuses/public_timeline.json", null, new JsonHttpResponseHandler() { - @Override - public void onSuccess(JSONArray timeline) { - try { - JSONObject firstEvent = (JSONObject)timeline.get(0); - String tweetText = firstEvent.getString("text"); - - // Do something with the response - System.out.println(tweetText); - } catch(JSONException e) { - e.printStackTrace(); - } - } - }); - } -} \ No newline at end of file diff --git a/gradle.properties b/gradle.properties new file mode 100755 index 000000000..c9086631a --- /dev/null +++ b/gradle.properties @@ -0,0 +1,16 @@ +VERSION_NAME=1.4.11 +VERSION_CODE=1411 +GROUP=com.loopj.android + +POM_DESCRIPTION=An Asynchronous HTTP Library for Android +POM_URL=https://android-async-http.github.io/android-async-http/ +POM_SCM_URL=https://github.com/android-async-http/android-async-http +POM_SCM_CONNECTION=scm:git@github.com:android-async-http/android-async-http.git +POM_SCM_DEV_CONNECTION=scm:git@github.com:android-async-http/android-async-http.git +POM_LICENCE_NAME=The Apache Software License, Version 2.0 +POM_LICENCE_URL=https://www.apache.org/licenses/LICENSE-2.0.txt +POM_LICENCE_DIST=repo + +POM_DEVELOPER_ID=jamessmith +POM_DEVELOPER_NAME=James Smith + diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000..30d399d8d Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000..7bfd9f1e4 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Sun Jun 28 22:59:06 PDT 2020 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-6.1.1-all.zip diff --git a/gradlew b/gradlew new file mode 100755 index 000000000..91a7e269e --- /dev/null +++ b/gradlew @@ -0,0 +1,164 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; +esac + +# For Cygwin, ensure paths are in UNIX format before anything is touched. +if $cygwin ; then + [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` +fi + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >&- +APP_HOME="`pwd -P`" +cd "$SAVED" >&- + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 000000000..aec99730b --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,90 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windowz variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/library/build.gradle b/library/build.gradle new file mode 100755 index 000000000..d63952f0b --- /dev/null +++ b/library/build.gradle @@ -0,0 +1,109 @@ +apply plugin: 'com.android.library' +apply plugin: 'digital.wup.android-maven-publish' +apply plugin: 'signing' + +android { + compileSdkVersion 28 + + defaultConfig { + minSdkVersion 9 + targetSdkVersion 28 + consumerProguardFiles 'proguard.txt' + } + + lintOptions { + xmlReport false + warningsAsErrors true + quiet false + showAll true + disable 'OldTargetApi' + } +} + +dependencies { + api 'cz.msebera.android:httpclient:4.5.8' + compileOnly 'org.conscrypt:conscrypt-android:2.4.0' +} + +project.afterEvaluate { project -> + + android.libraryVariants.all { variant -> + def name = variant.buildType.name + def task = project.tasks.create "jar${name.capitalize()}", Jar + task.dependsOn variant.javaCompileProvider.get() + task.from variant.javaCompileProvider.get().destinationDir + } + + task sourcesJar(type: Jar) { + from android.sourceSets.main.java.srcDirs + archiveClassifier = 'sources' + } + + task javadocJar(type: Jar, dependsOn: tasks.findAll { task -> task.name.contains('Javadoc') }) { + archiveClassifier = 'javadoc' + from 'build/docs/javadoc/release/' + } + + publishing { + publications { + maven(MavenPublication) { + artifactId = POM_ARTIFACT_ID + artifact javadocJar + artifact sourcesJar + artifact jarRelease + from components.android + + pom { + name = POM_NAME + description = POM_DESCRIPTION + packaging = POM_PACKAGING + url = POM_URL + + scm { + connection = POM_SCM_CONNECTION + developerConnection = POM_SCM_DEV_CONNECTION + url = POM_SCM_URL + } + + licenses { + license { + name = POM_LICENCE_NAME + url = POM_LICENCE_URL + distribution = POM_LICENCE_DIST + } + } + + developers { + developer { + id = 'mareksebera' + name = 'Marek Sebera' + } + } + } + + pom.name = POM_NAME + pom.description = POM_DESCRIPTION + pom.url = POM_URL + pom.packaging = POM_PACKAGING + } + } + repositories { + maven { + def releaseUrl = "https://oss.sonatype.org/service/local/staging/deploy/maven2/" + def snapshotUrl = "https://oss.sonatype.org/content/repositories/snapshots/" + url = version.endsWith('SNAPSHOT') ? snapshotUrl : releaseUrl + credentials { + def NexusUsername = project.hasProperty('NEXUS_USERNAME') ? NEXUS_USERNAME : '' + def NexusPassword = project.hasProperty('NEXUS_PASSWORD') ? NEXUS_PASSWORD : '' + username NexusUsername + password NexusPassword + } + } + } + } + + signing { + sign publishing.publications.maven + } +} + diff --git a/library/gradle.properties b/library/gradle.properties new file mode 100755 index 000000000..96e35d668 --- /dev/null +++ b/library/gradle.properties @@ -0,0 +1,3 @@ +POM_NAME=android-async-http Library +POM_ARTIFACT_ID=android-async-http +POM_PACKAGING=aar diff --git a/library/proguard.txt b/library/proguard.txt new file mode 100644 index 000000000..e3ab81252 --- /dev/null +++ b/library/proguard.txt @@ -0,0 +1,2 @@ +-keep class cz.msebera.android.httpclient.** { *; } +-keep class com.loopj.android.http.** { *; } diff --git a/library/src/main/AndroidManifest.xml b/library/src/main/AndroidManifest.xml new file mode 100755 index 000000000..7af3e5711 --- /dev/null +++ b/library/src/main/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + + + diff --git a/library/src/main/java/com/loopj/android/http/AsyncHttpClient.java b/library/src/main/java/com/loopj/android/http/AsyncHttpClient.java new file mode 100755 index 000000000..f38c4fe10 --- /dev/null +++ b/library/src/main/java/com/loopj/android/http/AsyncHttpClient.java @@ -0,0 +1,1696 @@ +package com.loopj.android.http; + +/* + Android Asynchronous Http Client + Copyright (c) 2011 James Smith + https://github.com/android-async-http/android-async-http + 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 + https://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. +*/ + +import android.content.Context; +import android.os.Looper; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.PushbackInputStream; +import java.lang.reflect.Field; +import java.net.URI; +import java.net.URL; +import java.net.URLDecoder; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.WeakHashMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.zip.GZIPInputStream; + +import cz.msebera.android.httpclient.Header; +import cz.msebera.android.httpclient.HeaderElement; +import cz.msebera.android.httpclient.HttpEntity; +import cz.msebera.android.httpclient.HttpException; +import cz.msebera.android.httpclient.HttpHost; +import cz.msebera.android.httpclient.HttpRequest; +import cz.msebera.android.httpclient.HttpRequestInterceptor; +import cz.msebera.android.httpclient.HttpResponse; +import cz.msebera.android.httpclient.HttpResponseInterceptor; +import cz.msebera.android.httpclient.HttpVersion; +import cz.msebera.android.httpclient.auth.AuthSchemeRegistry; +import cz.msebera.android.httpclient.auth.AuthScope; +import cz.msebera.android.httpclient.auth.AuthState; +import cz.msebera.android.httpclient.auth.Credentials; +import cz.msebera.android.httpclient.auth.UsernamePasswordCredentials; +import cz.msebera.android.httpclient.client.CookieStore; +import cz.msebera.android.httpclient.client.CredentialsProvider; +import cz.msebera.android.httpclient.client.HttpClient; +import cz.msebera.android.httpclient.client.RedirectHandler; +import cz.msebera.android.httpclient.client.methods.HttpEntityEnclosingRequestBase; +import cz.msebera.android.httpclient.client.methods.HttpHead; +import cz.msebera.android.httpclient.client.methods.HttpOptions; +import cz.msebera.android.httpclient.client.methods.HttpPatch; +import cz.msebera.android.httpclient.client.methods.HttpPost; +import cz.msebera.android.httpclient.client.methods.HttpPut; +import cz.msebera.android.httpclient.client.methods.HttpUriRequest; +import cz.msebera.android.httpclient.client.params.ClientPNames; +import cz.msebera.android.httpclient.client.protocol.ClientContext; +import cz.msebera.android.httpclient.conn.ClientConnectionManager; +import cz.msebera.android.httpclient.conn.params.ConnManagerParams; +import cz.msebera.android.httpclient.conn.params.ConnPerRouteBean; +import cz.msebera.android.httpclient.conn.params.ConnRoutePNames; +import cz.msebera.android.httpclient.conn.scheme.PlainSocketFactory; +import cz.msebera.android.httpclient.conn.scheme.Scheme; +import cz.msebera.android.httpclient.conn.scheme.SchemeRegistry; +import cz.msebera.android.httpclient.conn.ssl.SSLSocketFactory; +import cz.msebera.android.httpclient.entity.HttpEntityWrapper; +import cz.msebera.android.httpclient.impl.auth.BasicScheme; +import cz.msebera.android.httpclient.impl.client.DefaultHttpClient; +import cz.msebera.android.httpclient.impl.conn.tsccm.ThreadSafeClientConnManager; +import cz.msebera.android.httpclient.params.BasicHttpParams; +import cz.msebera.android.httpclient.params.HttpConnectionParams; +import cz.msebera.android.httpclient.params.HttpParams; +import cz.msebera.android.httpclient.params.HttpProtocolParams; +import cz.msebera.android.httpclient.protocol.BasicHttpContext; +import cz.msebera.android.httpclient.protocol.ExecutionContext; +import cz.msebera.android.httpclient.protocol.HttpContext; +import cz.msebera.android.httpclient.protocol.SyncBasicHttpContext; + + +/** + * The AsyncHttpClient can be used to make asynchronous GET, POST, PUT and DELETE HTTP requests in + * your Android applications. Requests can be made with additional parameters by passing a {@link + * RequestParams} instance, and responses can be handled by passing an anonymously overridden {@link + * ResponseHandlerInterface} instance.

 

For example:

 

+ *
+ * AsyncHttpClient client = new AsyncHttpClient();
+ * client.get("https://www.google.com/", new AsyncHttpResponseHandler() {
+ *     @Override
+ *     public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
+ *          System.out.println(response);
+ *     }
+ *     @Override
+ *     public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable
+ * error)
+ * {
+ *          error.printStackTrace(System.out);
+ *     }
+ * });
+ * 
+ * + * @see com.loopj.android.http.AsyncHttpResponseHandler + * @see com.loopj.android.http.ResponseHandlerInterface + * @see com.loopj.android.http.RequestParams + */ +public class AsyncHttpClient { + + public static final String LOG_TAG = "AsyncHttpClient"; + + public static final String HEADER_CONTENT_TYPE = "Content-Type"; + public static final String HEADER_CONTENT_RANGE = "Content-Range"; + public static final String HEADER_CONTENT_ENCODING = "Content-Encoding"; + public static final String HEADER_CONTENT_DISPOSITION = "Content-Disposition"; + public static final String HEADER_ACCEPT_ENCODING = "Accept-Encoding"; + public static final String ENCODING_GZIP = "gzip"; + + public static final int DEFAULT_MAX_CONNECTIONS = 10; + public static final int DEFAULT_SOCKET_TIMEOUT = 10 * 1000; + public static final int DEFAULT_MAX_RETRIES = 5; + public static final int DEFAULT_RETRY_SLEEP_TIME_MILLIS = 1500; + public static final int DEFAULT_SOCKET_BUFFER_SIZE = 8192; + public static LogInterface log = new LogHandler(); + private final DefaultHttpClient httpClient; + private final HttpContext httpContext; + private final Map> requestMap; + private final Map clientHeaderMap; + private int maxConnections = DEFAULT_MAX_CONNECTIONS; + private int connectTimeout = DEFAULT_SOCKET_TIMEOUT; + private int responseTimeout = DEFAULT_SOCKET_TIMEOUT; + private ExecutorService threadPool; + private boolean isUrlEncodingEnabled = true; + + /** + * Creates a new AsyncHttpClient with default constructor arguments values + */ + public AsyncHttpClient() { + this(false, 80, 443); + } + + /** + * Creates a new AsyncHttpClient. + * + * @param httpPort non-standard HTTP-only port + */ + public AsyncHttpClient(int httpPort) { + this(false, httpPort, 443); + } + + /** + * Creates a new AsyncHttpClient. + * + * @param httpPort non-standard HTTP-only port + * @param httpsPort non-standard HTTPS-only port + */ + public AsyncHttpClient(int httpPort, int httpsPort) { + this(false, httpPort, httpsPort); + } + + /** + * Creates new AsyncHttpClient using given params + * + * @param fixNoHttpResponseException Whether to fix issue or not, by omitting SSL verification + * @param httpPort HTTP port to be used, must be greater than 0 + * @param httpsPort HTTPS port to be used, must be greater than 0 + */ + public AsyncHttpClient(boolean fixNoHttpResponseException, int httpPort, int httpsPort) { + this(getDefaultSchemeRegistry(fixNoHttpResponseException, httpPort, httpsPort)); + } + + /** + * Creates a new AsyncHttpClient. + * + * @param schemeRegistry SchemeRegistry to be used + */ + public AsyncHttpClient(SchemeRegistry schemeRegistry) { + + BasicHttpParams httpParams = new BasicHttpParams(); + + ConnManagerParams.setTimeout(httpParams, connectTimeout); + ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections)); + ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS); + + HttpConnectionParams.setSoTimeout(httpParams, responseTimeout); + HttpConnectionParams.setConnectionTimeout(httpParams, connectTimeout); + HttpConnectionParams.setTcpNoDelay(httpParams, true); + HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE); + + HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1); + + ClientConnectionManager cm = createConnectionManager(schemeRegistry, httpParams); + Utils.asserts(cm != null, "Custom implementation of #createConnectionManager(SchemeRegistry, BasicHttpParams) returned null"); + + threadPool = getDefaultThreadPool(); + requestMap = Collections.synchronizedMap(new WeakHashMap>()); + clientHeaderMap = new HashMap(); + + httpContext = new SyncBasicHttpContext(new BasicHttpContext()); + httpClient = new DefaultHttpClient(cm, httpParams); + httpClient.addRequestInterceptor(new HttpRequestInterceptor() { + @Override + public void process(HttpRequest request, HttpContext context) { + if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) { + request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP); + } + for (String header : clientHeaderMap.keySet()) { + if (request.containsHeader(header)) { + Header overwritten = request.getFirstHeader(header); + log.d(LOG_TAG, + String.format("Headers were overwritten! (%s | %s) overwrites (%s | %s)", + header, clientHeaderMap.get(header), + overwritten.getName(), overwritten.getValue()) + ); + + //remove the overwritten header + request.removeHeader(overwritten); + } + request.addHeader(header, clientHeaderMap.get(header)); + } + } + }); + + httpClient.addResponseInterceptor(new HttpResponseInterceptor() { + @Override + public void process(HttpResponse response, HttpContext context) { + final HttpEntity entity = response.getEntity(); + if (entity == null) { + return; + } + final Header encoding = entity.getContentEncoding(); + if (encoding != null) { + for (HeaderElement element : encoding.getElements()) { + if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) { + response.setEntity(new InflatingEntity(entity)); + break; + } + } + } + } + }); + + httpClient.addRequestInterceptor(new HttpRequestInterceptor() { + @Override + public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { + + AuthSchemeRegistry authSchemeRegistry = new AuthSchemeRegistry(); + authSchemeRegistry.register("Bearer", new BearerAuthSchemeFactory()); + context.setAttribute(ClientContext.AUTHSCHEME_REGISTRY, authSchemeRegistry); + + AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE); + CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute( + ClientContext.CREDS_PROVIDER); + HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); + + if (authState.getAuthScheme() == null) { + AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); + Credentials creds = credsProvider.getCredentials(authScope); + if (creds instanceof TokenCredentials) { + authState.setAuthScheme(new BearerAuthSchemeFactory.BearerAuthScheme()); + authState.setCredentials(creds); + } else if (creds != null) { + authState.setAuthScheme(new BasicScheme()); + authState.setCredentials(creds); + } + } + } + }, 0); + + httpClient.setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES, DEFAULT_RETRY_SLEEP_TIME_MILLIS)); + } + + /** + * Returns default instance of SchemeRegistry + * + * @param fixNoHttpResponseException Whether to fix issue or not, by omitting SSL verification + * @param httpPort HTTP port to be used, must be greater than 0 + * @param httpsPort HTTPS port to be used, must be greater than 0 + */ + private static SchemeRegistry getDefaultSchemeRegistry(boolean fixNoHttpResponseException, int httpPort, int httpsPort) { + if (fixNoHttpResponseException) { + log.d(LOG_TAG, "Beware! Using the fix is insecure, as it doesn't verify SSL certificates."); + } + + if (httpPort < 1) { + httpPort = 80; + log.d(LOG_TAG, "Invalid HTTP port number specified, defaulting to 80"); + } + + if (httpsPort < 1) { + httpsPort = 443; + log.d(LOG_TAG, "Invalid HTTPS port number specified, defaulting to 443"); + } + + // Fix to SSL flaw in API < ICS + // See https://code.google.com/p/android/issues/detail?id=13117 + SSLSocketFactory sslSocketFactory; + if (fixNoHttpResponseException) { + sslSocketFactory = MySSLSocketFactory.getFixedSocketFactory(); + } else { + sslSocketFactory = SSLSocketFactory.getSocketFactory(); + } + + SchemeRegistry schemeRegistry = new SchemeRegistry(); + schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), httpPort)); + schemeRegistry.register(new Scheme("https", sslSocketFactory, httpsPort)); + + return schemeRegistry; + } + + public static void allowRetryExceptionClass(Class cls) { + if (cls != null) { + RetryHandler.addClassToWhitelist(cls); + } + } + + public static void blockRetryExceptionClass(Class cls) { + if (cls != null) { + RetryHandler.addClassToBlacklist(cls); + } + } + + /** + * Will encode url, if not disabled, and adds params on the end of it + * + * @param url String with URL, should be valid URL without params + * @param params RequestParams to be appended on the end of URL + * @param shouldEncodeUrl whether url should be encoded (replaces spaces with %20) + * @return encoded url if requested with params appended if any available + */ + public static String getUrlWithQueryString(boolean shouldEncodeUrl, String url, RequestParams params) { + if (url == null) + return null; + + if (shouldEncodeUrl) { + try { + String decodedURL = URLDecoder.decode(url, "UTF-8"); + URL _url = new URL(decodedURL); + URI _uri = new URI(_url.getProtocol(), _url.getUserInfo(), _url.getHost(), _url.getPort(), _url.getPath(), _url.getQuery(), _url.getRef()); + url = _uri.toASCIIString(); + } catch (Exception ex) { + // Should not really happen, added just for sake of validity + log.e(LOG_TAG, "getUrlWithQueryString encoding URL", ex); + } + } + + if (params != null) { + // Construct the query string and trim it, in case it + // includes any excessive white spaces. + String paramString = params.getParamString().trim(); + + // Only add the query string if it isn't empty and it + // isn't equal to '?'. + if (!paramString.equals("") && !paramString.equals("?")) { + url += url.contains("?") ? "&" : "?"; + url += paramString; + } + } + + return url; + } + + /** + * Checks the InputStream if it contains GZIP compressed data + * + * @param inputStream InputStream to be checked + * @return true or false if the stream contains GZIP compressed data + * @throws java.io.IOException if read from inputStream fails + */ + public static boolean isInputStreamGZIPCompressed(final PushbackInputStream inputStream) throws IOException { + if (inputStream == null) + return false; + + byte[] signature = new byte[2]; + int count = 0; + try { + while (count < 2) { + int readCount = inputStream.read(signature, count, 2 - count); + if (readCount < 0) return false; + count = count + readCount; + } + } finally { + inputStream.unread(signature, 0, count); + } + int streamHeader = ((int) signature[0] & 0xff) | ((signature[1] << 8) & 0xff00); + return GZIPInputStream.GZIP_MAGIC == streamHeader; + } + + /** + * A utility function to close an input stream without raising an exception. + * + * @param is input stream to close safely + */ + public static void silentCloseInputStream(InputStream is) { + try { + if (is != null) { + is.close(); + } + } catch (IOException e) { + log.w(LOG_TAG, "Cannot close input stream", e); + } + } + + /** + * A utility function to close an output stream without raising an exception. + * + * @param os output stream to close safely + */ + public static void silentCloseOutputStream(OutputStream os) { + try { + if (os != null) { + os.close(); + } + } catch (IOException e) { + log.w(LOG_TAG, "Cannot close output stream", e); + } + } + + /** + * This horrible hack is required on Android, due to implementation of BasicManagedEntity, which + * doesn't chain call consumeContent on underlying wrapped HttpEntity + * + * @param entity HttpEntity, may be null + */ + public static void endEntityViaReflection(HttpEntity entity) { + if (entity instanceof HttpEntityWrapper) { + try { + Field f = null; + Field[] fields = HttpEntityWrapper.class.getDeclaredFields(); + for (Field ff : fields) { + if (ff.getName().equals("wrappedEntity")) { + f = ff; + break; + } + } + if (f != null) { + f.setAccessible(true); + HttpEntity wrapped = (HttpEntity) f.get(entity); + if (wrapped != null) { + wrapped.consumeContent(); + } + } + } catch (Throwable t) { + log.e(LOG_TAG, "wrappedEntity consume", t); + } + } + } + + /** + * Get the underlying HttpClient instance. This is useful for setting additional fine-grained + * settings for requests by accessing the client's ConnectionManager, HttpParams and + * SchemeRegistry. + * + * @return underlying HttpClient instance + */ + public HttpClient getHttpClient() { + return this.httpClient; + } + + /** + * Get the underlying HttpContext instance. This is useful for getting and setting fine-grained + * settings for requests by accessing the context's attributes such as the CookieStore. + * + * @return underlying HttpContext instance + */ + public HttpContext getHttpContext() { + return this.httpContext; + } + + /** + * Returns logging enabled flag from underlying LogInterface instance + * Default setting is logging enabled. + * + * @return boolean whether is logging across the library currently enabled + */ + public boolean isLoggingEnabled() { + return log.isLoggingEnabled(); + } + + /** + * Will set logging enabled flag on underlying LogInterface instance. + * Default setting is logging enabled. + * + * @param loggingEnabled whether the logging should be enabled or not + */ + public void setLoggingEnabled(boolean loggingEnabled) { + log.setLoggingEnabled(loggingEnabled); + } + + /** + * Retrieves current log level from underlying LogInterface instance. + * Default setting is VERBOSE log level. + * + * @return int log level currently in effect + */ + public int getLoggingLevel() { + return log.getLoggingLevel(); + } + + /** + * Sets log level to be used across all library default implementation + * Default setting is VERBOSE log level. + * + * @param logLevel int log level, either from LogInterface interface or from {@link android.util.Log} + */ + public void setLoggingLevel(int logLevel) { + log.setLoggingLevel(logLevel); + } + + /** + * Will return current LogInterface used in AsyncHttpClient instance + * + * @return LogInterface currently used by AsyncHttpClient instance + */ + public LogInterface getLogInterface() { + return log; + } + + /** + * Sets default LogInterface (similar to std Android Log util class) instance, + * to be used in AsyncHttpClient instance + * + * @param logInterfaceInstance LogInterface instance, if null, nothing is done + */ + public void setLogInterface(LogInterface logInterfaceInstance) { + if (logInterfaceInstance != null) { + log = logInterfaceInstance; + } + } + + /** + * Sets an optional CookieStore to use when making requests + * + * @param cookieStore The CookieStore implementation to use, usually an instance of {@link + * PersistentCookieStore} + */ + public void setCookieStore(CookieStore cookieStore) { + httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); + } + + /** + * Returns the current executor service used. By default, Executors.newCachedThreadPool() is + * used. + * + * @return current executor service used + */ + public ExecutorService getThreadPool() { + return threadPool; + } + + /** + * Overrides the threadpool implementation used when queuing/pooling requests. By default, + * Executors.newCachedThreadPool() is used. + * + * @param threadPool an instance of {@link ExecutorService} to use for queuing/pooling + * requests. + */ + public void setThreadPool(ExecutorService threadPool) { + this.threadPool = threadPool; + } + + /** + * Get the default threading pool to be used for this HTTP client. + * + * @return The default threading pool to be used + */ + protected ExecutorService getDefaultThreadPool() { + return Executors.newCachedThreadPool(); + } + + /** + * Provided so it is easier for developers to provide custom ThreadSafeClientConnManager implementation + * + * @param schemeRegistry SchemeRegistry, usually provided by {@link #getDefaultSchemeRegistry(boolean, int, int)} + * @param httpParams BasicHttpParams + * @return ClientConnectionManager instance + */ + protected ClientConnectionManager createConnectionManager(SchemeRegistry schemeRegistry, BasicHttpParams httpParams) { + return new ThreadSafeClientConnManager(httpParams, schemeRegistry); + } + + /** + * Simple interface method, to enable or disable redirects. If you set manually RedirectHandler + * on underlying HttpClient, effects of this method will be canceled.

 

Default + * setting is to disallow redirects. + * + * @param enableRedirects boolean + * @param enableRelativeRedirects boolean + * @param enableCircularRedirects boolean + */ + public void setEnableRedirects(final boolean enableRedirects, final boolean enableRelativeRedirects, final boolean enableCircularRedirects) { + httpClient.getParams().setBooleanParameter(ClientPNames.REJECT_RELATIVE_REDIRECT, !enableRelativeRedirects); + httpClient.getParams().setBooleanParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, enableCircularRedirects); + httpClient.setRedirectHandler(new MyRedirectHandler(enableRedirects)); + } + + /** + * Circular redirects are enabled by default + * + * @param enableRedirects boolean + * @param enableRelativeRedirects boolean + * @see #setEnableRedirects(boolean, boolean, boolean) + */ + public void setEnableRedirects(final boolean enableRedirects, final boolean enableRelativeRedirects) { + setEnableRedirects(enableRedirects, enableRelativeRedirects, true); + } + + /** + * @param enableRedirects boolean + * @see #setEnableRedirects(boolean, boolean, boolean) + */ + public void setEnableRedirects(final boolean enableRedirects) { + setEnableRedirects(enableRedirects, enableRedirects, enableRedirects); + } + + /** + * Allows you to set custom RedirectHandler implementation, if the default provided doesn't suit + * your needs + * + * @param customRedirectHandler RedirectHandler instance + * @see com.loopj.android.http.MyRedirectHandler + */ + public void setRedirectHandler(final RedirectHandler customRedirectHandler) { + httpClient.setRedirectHandler(customRedirectHandler); + } + + /** + * Sets the User-Agent header to be sent with each request. By default, "Android Asynchronous + * Http Client/VERSION (https://github.com/android-async-http/android-async-http/)" is used. + * + * @param userAgent the string to use in the User-Agent header. + */ + public void setUserAgent(String userAgent) { + HttpProtocolParams.setUserAgent(this.httpClient.getParams(), userAgent); + } + + /** + * Returns current limit of parallel connections + * + * @return maximum limit of parallel connections, default is 10 + */ + public int getMaxConnections() { + return maxConnections; + } + + /** + * Sets maximum limit of parallel connections + * + * @param maxConnections maximum parallel connections, must be at least 1 + */ + public void setMaxConnections(int maxConnections) { + if (maxConnections < 1) + maxConnections = DEFAULT_MAX_CONNECTIONS; + this.maxConnections = maxConnections; + final HttpParams httpParams = this.httpClient.getParams(); + ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(this.maxConnections)); + } + + /** + * Set both the connection and socket timeouts. By default, both are set to + * 10 seconds. + * + * @param value the connect/socket timeout in milliseconds, at least 1 second + * @see #setConnectTimeout(int) + * @see #setResponseTimeout(int) + */ + public void setTimeout(int value) { + value = value < 1000 ? DEFAULT_SOCKET_TIMEOUT : value; + setConnectTimeout(value); + setResponseTimeout(value); + } + + /** + * Returns current connection timeout limit (milliseconds). By default, this + * is set to 10 seconds. + * + * @return Connection timeout limit in milliseconds + */ + public int getConnectTimeout() { + return connectTimeout; + } + + /** + * Set connection timeout limit (milliseconds). By default, this is set to + * 10 seconds. + * + * @param value Connection timeout in milliseconds, minimal value is 1000 (1 second). + */ + public void setConnectTimeout(int value) { + connectTimeout = value < 1000 ? DEFAULT_SOCKET_TIMEOUT : value; + final HttpParams httpParams = httpClient.getParams(); + ConnManagerParams.setTimeout(httpParams, connectTimeout); + HttpConnectionParams.setConnectionTimeout(httpParams, connectTimeout); + } + + /** + * Returns current response timeout limit (milliseconds). By default, this + * is set to 10 seconds. + * + * @return Response timeout limit in milliseconds + */ + public int getResponseTimeout() { + return responseTimeout; + } + + /** + * Set response timeout limit (milliseconds). By default, this is set to + * 10 seconds. + * + * @param value Response timeout in milliseconds, minimal value is 1000 (1 second). + */ + public void setResponseTimeout(int value) { + responseTimeout = value < 1000 ? DEFAULT_SOCKET_TIMEOUT : value; + final HttpParams httpParams = httpClient.getParams(); + HttpConnectionParams.setSoTimeout(httpParams, responseTimeout); + } + + /** + * Sets the Proxy by it's hostname and port + * + * @param hostname the hostname (IP or DNS name) + * @param port the port number. -1 indicates the scheme default port. + */ + public void setProxy(String hostname, int port) { + final HttpHost proxy = new HttpHost(hostname, port); + final HttpParams httpParams = this.httpClient.getParams(); + httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); + } + + /** + * Sets the Proxy by it's hostname,port,username and password + * + * @param hostname the hostname (IP or DNS name) + * @param port the port number. -1 indicates the scheme default port. + * @param username the username + * @param password the password + */ + public void setProxy(String hostname, int port, String username, String password) { + httpClient.getCredentialsProvider().setCredentials( + new AuthScope(hostname, port), + new UsernamePasswordCredentials(username, password)); + final HttpHost proxy = new HttpHost(hostname, port); + final HttpParams httpParams = this.httpClient.getParams(); + httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); + } + + /** + * Sets the SSLSocketFactory to user when making requests. By default, a new, default + * SSLSocketFactory is used. + * + * @param sslSocketFactory the socket factory to use for https requests. + */ + public void setSSLSocketFactory(SSLSocketFactory sslSocketFactory) { + this.httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", sslSocketFactory, 443)); + } + + /** + * Sets the maximum number of retries and timeout for a particular Request. + * + * @param retries maximum number of retries per request + * @param timeout sleep between retries in milliseconds + */ + public void setMaxRetriesAndTimeout(int retries, int timeout) { + this.httpClient.setHttpRequestRetryHandler(new RetryHandler(retries, timeout)); + } + + /** + * Will, before sending, remove all headers currently present in AsyncHttpClient instance, which + * applies on all requests this client makes + */ + public void removeAllHeaders() { + clientHeaderMap.clear(); + } + + /** + * Sets headers that will be added to all requests this client makes (before sending). + * + * @param header the name of the header + * @param value the contents of the header + */ + public void addHeader(String header, String value) { + clientHeaderMap.put(header, value); + } + + /** + * Remove header from all requests this client makes (before sending). + * + * @param header the name of the header + */ + public void removeHeader(String header) { + clientHeaderMap.remove(header); + } + + /** + * Sets bearer authentication for the request. Uses AuthScope.ANY. This is the same as + * setBearerAuth('token',AuthScope.ANY, false) + * + * @param token Bearer Token + */ + public void setBearerAuth(String token) { + setBearerAuth(token, AuthScope.ANY, false); + } + + + /** + * Sets bearer authentication for the request. You should pass in your AuthScope for security. It + * should be like this setBearerAuth("token", new AuthScope("host",port,AuthScope.ANY_REALM), false) + * + * @param token Bearer Token + * @param scope an AuthScope object + * @param preemptive sets authorization in preemptive manner + */ + public void setBearerAuth(String token, AuthScope scope, boolean preemptive) { + TokenCredentials credentials = new TokenCredentials(token); + setCredentials(scope, credentials); + setAuthenticationPreemptive(preemptive); + } + + /** + * Sets basic authentication for the request. Uses AuthScope.ANY. This is the same as + * setBasicAuth('username','password',AuthScope.ANY) + * + * @param username Basic Auth username + * @param password Basic Auth password + */ + public void setBasicAuth(String username, String password) { + setBasicAuth(username, password, false); + } + + /** + * Sets basic authentication for the request. Uses AuthScope.ANY. This is the same as + * setBasicAuth('username','password',AuthScope.ANY) + * + * @param username Basic Auth username + * @param password Basic Auth password + * @param preemptive sets authorization in preemptive manner + */ + public void setBasicAuth(String username, String password, boolean preemptive) { + setBasicAuth(username, password, null, preemptive); + } + + /** + * Sets basic authentication for the request. You should pass in your AuthScope for security. It + * should be like this setBasicAuth("username","password", new AuthScope("host",port,AuthScope.ANY_REALM)) + * + * @param username Basic Auth username + * @param password Basic Auth password + * @param scope - an AuthScope object + */ + public void setBasicAuth(String username, String password, AuthScope scope) { + setBasicAuth(username, password, scope, false); + } + + /** + * Sets basic authentication for the request. You should pass in your AuthScope for security. It + * should be like this setBasicAuth("username","password", new AuthScope("host",port,AuthScope.ANY_REALM)) + * + * @param username Basic Auth username + * @param password Basic Auth password + * @param scope an AuthScope object + * @param preemptive sets authorization in preemptive manner + */ + public void setBasicAuth(String username, String password, AuthScope scope, boolean preemptive) { + UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password); + setCredentials(scope, credentials); + setAuthenticationPreemptive(preemptive); + } + + public void setCredentials(AuthScope authScope, Credentials credentials) { + if (credentials == null) { + log.d(LOG_TAG, "Provided credentials are null, not setting"); + return; + } + this.httpClient.getCredentialsProvider().setCredentials(authScope == null ? AuthScope.ANY : authScope, credentials); + } + + /** + * Sets HttpRequestInterceptor which handles authorization in preemptive way, as workaround you + * can use call `AsyncHttpClient.addHeader("Authorization","Basic base64OfUsernameAndPassword==")` + * + * @param isPreemptive whether the authorization is processed in preemptive way + */ + public void setAuthenticationPreemptive(boolean isPreemptive) { + if (isPreemptive) { + httpClient.addRequestInterceptor(new PreemptiveAuthorizationHttpRequestInterceptor(), 0); + } else { + httpClient.removeRequestInterceptorByClass(PreemptiveAuthorizationHttpRequestInterceptor.class); + } + } + + // [+] HTTP HEAD + + /** + * Removes previously set auth credentials + */ + public void clearCredentialsProvider() { + this.httpClient.getCredentialsProvider().clear(); + } + + /** + * Cancels any pending (or potentially active) requests associated with the passed Context. + *

 

Note: This will only affect requests which were created with a non-null + * android Context. This method is intended to be used in the onDestroy method of your android + * activities to destroy all requests which are no longer required. + * + * @param context the android Context instance associated to the request. + * @param mayInterruptIfRunning specifies if active requests should be cancelled along with + * pending requests. + */ + public void cancelRequests(final Context context, final boolean mayInterruptIfRunning) { + if (context == null) { + log.e(LOG_TAG, "Passed null Context to cancelRequests"); + return; + } + + final List requestList = requestMap.get(context); + requestMap.remove(context); + + if (Looper.myLooper() == Looper.getMainLooper()) { + Runnable runnable = new Runnable() { + @Override + public void run() { + cancelRequests(requestList, mayInterruptIfRunning); + } + }; + threadPool.submit(runnable); + } else { + cancelRequests(requestList, mayInterruptIfRunning); + } + } + + private void cancelRequests(final List requestList, final boolean mayInterruptIfRunning) { + if (requestList != null) { + for (RequestHandle requestHandle : requestList) { + requestHandle.cancel(mayInterruptIfRunning); + } + } + } + + /** + * Cancels all pending (or potentially active) requests.

 

Note: This will + * only affect requests which were created with a non-null android Context. This method is + * intended to be used in the onDestroy method of your android activities to destroy all + * requests which are no longer required. + * + * @param mayInterruptIfRunning specifies if active requests should be cancelled along with + * pending requests. + */ + public void cancelAllRequests(boolean mayInterruptIfRunning) { + for (List requestList : requestMap.values()) { + if (requestList != null) { + for (RequestHandle requestHandle : requestList) { + requestHandle.cancel(mayInterruptIfRunning); + } + } + } + requestMap.clear(); + } + + /** + * Allows you to cancel all requests currently in queue or running, by set TAG, + * if passed TAG is null, will not attempt to cancel any requests, if TAG is null + * on RequestHandle, it cannot be canceled by this call + * + * @param TAG TAG to be matched in RequestHandle + * @param mayInterruptIfRunning specifies if active requests should be cancelled along with + * pending requests. + */ + public void cancelRequestsByTAG(Object TAG, boolean mayInterruptIfRunning) { + if (TAG == null) { + log.d(LOG_TAG, "cancelRequestsByTAG, passed TAG is null, cannot proceed"); + return; + } + for (List requestList : requestMap.values()) { + if (requestList != null) { + for (RequestHandle requestHandle : requestList) { + if (TAG.equals(requestHandle.getTag())) + requestHandle.cancel(mayInterruptIfRunning); + } + } + } + } + + // [-] HTTP HEAD + // [+] HTTP OPTIONS + + /** + * Perform a HTTP OPTIONS request, without any parameters. + * + * @param url the URL to send the request to. + * @param responseHandler the response handler instance that should handle the response. + * @return RequestHandle of future request process + */ + public RequestHandle options(String url, ResponseHandlerInterface responseHandler) { + return options(null, url, null, responseHandler); + } + + public RequestHandle options(Context context, String url, RequestParams params, ResponseHandlerInterface responseHandler) { + return sendRequest(httpClient, httpContext, new HttpOptions(getUrlWithQueryString(isUrlEncodingEnabled(), url, params)), null, responseHandler, context); + } + + // [-] HTTP OPTIONS + // [+] HTTP GET + + /** + * Perform a HTTP HEAD request, without any parameters. + * + * @param url the URL to send the request to. + * @param responseHandler the response handler instance that should handle the response. + * @return RequestHandle of future request process + */ + public RequestHandle head(String url, ResponseHandlerInterface responseHandler) { + return head(null, url, null, responseHandler); + } + + /** + * Perform a HTTP HEAD request with parameters. + * + * @param url the URL to send the request to. + * @param params additional HEAD parameters to send with the request. + * @param responseHandler the response handler instance that should handle the response. + * @return RequestHandle of future request process + */ + public RequestHandle head(String url, RequestParams params, ResponseHandlerInterface responseHandler) { + return head(null, url, params, responseHandler); + } + + /** + * Perform a HTTP HEAD request without any parameters and track the Android Context which + * initiated the request. + * + * @param context the Android Context which initiated the request. + * @param url the URL to send the request to. + * @param responseHandler the response handler instance that should handle the response. + * @return RequestHandle of future request process + */ + public RequestHandle head(Context context, String url, ResponseHandlerInterface responseHandler) { + return head(context, url, null, responseHandler); + } + + /** + * Perform a HTTP HEAD request and track the Android Context which initiated the request. + * + * @param context the Android Context which initiated the request. + * @param url the URL to send the request to. + * @param params additional HEAD parameters to send with the request. + * @param responseHandler the response handler instance that should handle the response. + * @return RequestHandle of future request process + */ + public RequestHandle head(Context context, String url, RequestParams params, ResponseHandlerInterface responseHandler) { + return sendRequest(httpClient, httpContext, new HttpHead(getUrlWithQueryString(isUrlEncodingEnabled, url, params)), null, responseHandler, context); + } + + /** + * Perform a HTTP HEAD request and track the Android Context which initiated the request with + * customized headers + * + * @param context Context to execute request against + * @param url the URL to send the request to. + * @param headers set headers only for this request + * @param params additional HEAD parameters to send with the request. + * @param responseHandler the response handler instance that should handle the response. + * @return RequestHandle of future request process + */ + public RequestHandle head(Context context, String url, Header[] headers, RequestParams params, ResponseHandlerInterface responseHandler) { + HttpUriRequest request = new HttpHead(getUrlWithQueryString(isUrlEncodingEnabled, url, params)); + if (headers != null) request.setHeaders(headers); + return sendRequest(httpClient, httpContext, request, null, responseHandler, + context); + } + + /** + * Perform a HTTP GET request, without any parameters. + * + * @param url the URL to send the request to. + * @param responseHandler the response handler instance that should handle the response. + * @return RequestHandle of future request process + */ + public RequestHandle get(String url, ResponseHandlerInterface responseHandler) { + return get(null, url, null, responseHandler); + } + + // [-] HTTP GET + // [+] HTTP POST + + /** + * Perform a HTTP GET request with parameters. + * + * @param url the URL to send the request to. + * @param params additional GET parameters to send with the request. + * @param responseHandler the response handler instance that should handle the response. + * @return RequestHandle of future request process + */ + public RequestHandle get(String url, RequestParams params, ResponseHandlerInterface responseHandler) { + return get(null, url, params, responseHandler); + } + + /** + * Perform a HTTP GET request without any parameters and track the Android Context which + * initiated the request. + * + * @param context the Android Context which initiated the request. + * @param url the URL to send the request to. + * @param responseHandler the response handler instance that should handle the response. + * @return RequestHandle of future request process + */ + public RequestHandle get(Context context, String url, ResponseHandlerInterface responseHandler) { + return get(context, url, null, responseHandler); + } + + /** + * Perform a HTTP GET request and track the Android Context which initiated the request. + * + * @param context the Android Context which initiated the request. + * @param url the URL to send the request to. + * @param params additional GET parameters to send with the request. + * @param responseHandler the response handler instance that should handle the response. + * @return RequestHandle of future request process + */ + public RequestHandle get(Context context, String url, RequestParams params, ResponseHandlerInterface responseHandler) { + return sendRequest(httpClient, httpContext, new HttpGet(getUrlWithQueryString(isUrlEncodingEnabled, url, params)), null, responseHandler, context); + } + + /** + * Perform a HTTP GET request and track the Android Context which initiated the request with + * customized headers + * + * @param context Context to execute request against + * @param url the URL to send the request to. + * @param headers set headers only for this request + * @param params additional GET parameters to send with the request. + * @param responseHandler the response handler instance that should handle the response. + * @return RequestHandle of future request process + */ + public RequestHandle get(Context context, String url, Header[] headers, RequestParams params, ResponseHandlerInterface responseHandler) { + HttpUriRequest request = new HttpGet(getUrlWithQueryString(isUrlEncodingEnabled, url, params)); + if (headers != null) request.setHeaders(headers); + return sendRequest(httpClient, httpContext, request, null, responseHandler, + context); + } + + /** + * Perform a HTTP GET request and track the Android Context which initiated the request. + * + * @param context the Android Context which initiated the request. + * @param url the URL to send the request to. + * @param entity a raw {@link cz.msebera.android.httpclient.HttpEntity} to send with the request, for + * example, use this to send string/json/xml payloads to a server by + * passing a {@link cz.msebera.android.httpclient.entity.StringEntity}. + * @param contentType the content type of the payload you are sending, for example + * application/json if sending a json payload. + * @param responseHandler the response ha ndler instance that should handle the response. + * @return RequestHandle of future request process + */ + public RequestHandle get(Context context, String url, HttpEntity entity, String contentType, ResponseHandlerInterface responseHandler) { + return sendRequest(httpClient, httpContext, addEntityToRequestBase(new HttpGet(URI.create(url).normalize()), entity), contentType, responseHandler, context); + } + + /** + * Perform a HTTP POST request, without any parameters. + * + * @param url the URL to send the request to. + * @param responseHandler the response handler instance that should handle the response. + * @return RequestHandle of future request process + */ + public RequestHandle post(String url, ResponseHandlerInterface responseHandler) { + return post(null, url, null, responseHandler); + } + + // [-] HTTP POST + // [+] HTTP PUT + + /** + * Perform a HTTP POST request with parameters. + * + * @param url the URL to send the request to. + * @param params additional POST parameters or files to send with the request. + * @param responseHandler the response handler instance that should handle the response. + * @return RequestHandle of future request process + */ + public RequestHandle post(String url, RequestParams params, ResponseHandlerInterface responseHandler) { + return post(null, url, params, responseHandler); + } + + /** + * Perform a HTTP POST request and track the Android Context which initiated the request. + * + * @param context the Android Context which initiated the request. + * @param url the URL to send the request to. + * @param params additional POST parameters or files to send with the request. + * @param responseHandler the response handler instance that should handle the response. + * @return RequestHandle of future request process + */ + public RequestHandle post(Context context, String url, RequestParams params, ResponseHandlerInterface responseHandler) { + return post(context, url, paramsToEntity(params, responseHandler), null, responseHandler); + } + + /** + * Perform a HTTP POST request and track the Android Context which initiated the request. + * + * @param context the Android Context which initiated the request. + * @param url the URL to send the request to. + * @param entity a raw {@link cz.msebera.android.httpclient.HttpEntity} to send with the request, for + * example, use this to send string/json/xml payloads to a server by + * passing a {@link cz.msebera.android.httpclient.entity.StringEntity}. + * @param contentType the content type of the payload you are sending, for example + * application/json if sending a json payload. + * @param responseHandler the response ha ndler instance that should handle the response. + * @return RequestHandle of future request process + */ + public RequestHandle post(Context context, String url, HttpEntity entity, String contentType, ResponseHandlerInterface responseHandler) { + return sendRequest(httpClient, httpContext, addEntityToRequestBase(new HttpPost(getURI(url)), entity), contentType, responseHandler, context); + } + + /** + * Perform a HTTP POST request and track the Android Context which initiated the request. Set + * headers only for this request + * + * @param context the Android Context which initiated the request. + * @param url the URL to send the request to. + * @param headers set headers only for this request + * @param params additional POST parameters to send with the request. + * @param contentType the content type of the payload you are sending, for example + * application/json if sending a json payload. + * @param responseHandler the response handler instance that should handle the response. + * @return RequestHandle of future request process + */ + public RequestHandle post(Context context, String url, Header[] headers, RequestParams params, String contentType, + ResponseHandlerInterface responseHandler) { + HttpEntityEnclosingRequestBase request = new HttpPost(getURI(url)); + if (params != null) request.setEntity(paramsToEntity(params, responseHandler)); + if (headers != null) request.setHeaders(headers); + return sendRequest(httpClient, httpContext, request, contentType, + responseHandler, context); + } + + /** + * Perform a HTTP POST request and track the Android Context which initiated the request. Set + * headers only for this request + * + * @param context the Android Context which initiated the request. + * @param url the URL to send the request to. + * @param headers set headers only for this request + * @param entity a raw {@link HttpEntity} to send with the request, for example, use + * this to send string/json/xml payloads to a server by passing a {@link + * cz.msebera.android.httpclient.entity.StringEntity}. + * @param contentType the content type of the payload you are sending, for example + * application/json if sending a json payload. + * @param responseHandler the response handler instance that should handle the response. + * @return RequestHandle of future request process + */ + public RequestHandle post(Context context, String url, Header[] headers, HttpEntity entity, String contentType, + ResponseHandlerInterface responseHandler) { + HttpEntityEnclosingRequestBase request = addEntityToRequestBase(new HttpPost(getURI(url)), entity); + if (headers != null) request.setHeaders(headers); + return sendRequest(httpClient, httpContext, request, contentType, responseHandler, context); + } + + /** + * Perform a HTTP PUT request, without any parameters. + * + * @param url the URL to send the request to. + * @param responseHandler the response handler instance that should handle the response. + * @return RequestHandle of future request process + */ + public RequestHandle put(String url, ResponseHandlerInterface responseHandler) { + return put(null, url, null, responseHandler); + } + + /** + * Perform a HTTP PUT request with parameters. + * + * @param url the URL to send the request to. + * @param params additional PUT parameters or files to send with the request. + * @param responseHandler the response handler instance that should handle the response. + * @return RequestHandle of future request process + */ + public RequestHandle put(String url, RequestParams params, ResponseHandlerInterface responseHandler) { + return put(null, url, params, responseHandler); + } + + /** + * Perform a HTTP PUT request and track the Android Context which initiated the request. + * + * @param context the Android Context which initiated the request. + * @param url the URL to send the request to. + * @param params additional PUT parameters or files to send with the request. + * @param responseHandler the response handler instance that should handle the response. + * @return RequestHandle of future request process + */ + public RequestHandle put(Context context, String url, RequestParams params, ResponseHandlerInterface responseHandler) { + return put(context, url, paramsToEntity(params, responseHandler), null, responseHandler); + } + + /** + * Perform a HTTP PUT request and track the Android Context which initiated the request. And set + * one-time headers for the request + * + * @param context the Android Context which initiated the request. + * @param url the URL to send the request to. + * @param entity a raw {@link HttpEntity} to send with the request, for example, use + * this to send string/json/xml payloads to a server by passing a {@link + * cz.msebera.android.httpclient.entity.StringEntity}. + * @param contentType the content type of the payload you are sending, for example + * application/json if sending a json payload. + * @param responseHandler the response handler instance that should handle the response. + * @return RequestHandle of future request process + */ + public RequestHandle put(Context context, String url, HttpEntity entity, String contentType, ResponseHandlerInterface responseHandler) { + return sendRequest(httpClient, httpContext, addEntityToRequestBase(new HttpPut(getURI(url)), entity), contentType, responseHandler, context); + } + + /** + * Perform a HTTP PUT request and track the Android Context which initiated the request. And set + * one-time headers for the request + * + * @param context the Android Context which initiated the request. + * @param url the URL to send the request to. + * @param headers set one-time headers for this request + * @param entity a raw {@link HttpEntity} to send with the request, for example, use + * this to send string/json/xml payloads to a server by passing a {@link + * cz.msebera.android.httpclient.entity.StringEntity}. + * @param contentType the content type of the payload you are sending, for example + * application/json if sending a json payload. + * @param responseHandler the response handler instance that should handle the response. + * @return RequestHandle of future request process + */ + public RequestHandle put(Context context, String url, Header[] headers, HttpEntity entity, String contentType, ResponseHandlerInterface responseHandler) { + HttpEntityEnclosingRequestBase request = addEntityToRequestBase(new HttpPut(getURI(url)), entity); + if (headers != null) request.setHeaders(headers); + return sendRequest(httpClient, httpContext, request, contentType, responseHandler, context); + } + + // [-] HTTP PUT + // [+] HTTP DELETE + + /** + * Perform a HTTP + * request, without any parameters. + * + * @param url the URL to send the request to. + * @param responseHandler the response handler instance that should handle the response. + * @return RequestHandle of future request process + */ + public RequestHandle patch(String url, ResponseHandlerInterface responseHandler) { + return patch(null, url, null, responseHandler); + } + + /** + * Perform a HTTP PATCH request with parameters. + * + * @param url the URL to send the request to. + * @param params additional PUT parameters or files to send with the request. + * @param responseHandler the response handler instance that should handle the response. + * @return RequestHandle of future request process + */ + public RequestHandle patch(String url, RequestParams params, ResponseHandlerInterface responseHandler) { + return patch(null, url, params, responseHandler); + } + + /** + * Perform a HTTP PATCH request and track the Android Context which initiated the request. + * + * @param context the Android Context which initiated the request. + * @param url the URL to send the request to. + * @param params additional PUT parameters or files to send with the request. + * @param responseHandler the response handler instance that should handle the response. + * @return RequestHandle of future request process + */ + public RequestHandle patch(Context context, String url, RequestParams params, ResponseHandlerInterface responseHandler) { + return patch(context, url, paramsToEntity(params, responseHandler), null, responseHandler); + } + + /** + * Perform a HTTP PATCH request and track the Android Context which initiated the request. + * + * @param context the Android Context which initiated the request. + * @param url the URL to send the request to. + * @param responseHandler the response handler instance that should handle the response. + * @param entity a raw {@link HttpEntity} to send with the request, for example, use + * this to send string/json/xml payloads to a server by passing a {@link + * cz.msebera.android.httpclient.entity.StringEntity} + * @param contentType the content type of the payload you are sending, for example + * "application/json" if sending a json payload. + * @return RequestHandle of future request process + */ + public RequestHandle patch(Context context, String url, HttpEntity entity, String contentType, ResponseHandlerInterface responseHandler) { + return sendRequest(httpClient, httpContext, addEntityToRequestBase(new HttpPatch(getURI(url)), entity), contentType, responseHandler, context); + } + + /** + * Perform a HTTP PATCH request and track the Android Context which initiated the request. And set + * one-time headers for the request + * + * @param context the Android Context which initiated the request. + * @param url the URL to send the request to. + * @param headers set one-time headers for this request + * @param entity a raw {@link HttpEntity} to send with the request, for example, use + * this to send string/json/xml payloads to a server by passing a {@link + * cz.msebera.android.httpclient.entity.StringEntity}. + * @param contentType the content type of the payload you are sending, for example + * application/json if sending a json payload. + * @param responseHandler the response handler instance that should handle the response. + * @return RequestHandle of future request process + */ + public RequestHandle patch(Context context, String url, Header[] headers, HttpEntity entity, String contentType, ResponseHandlerInterface responseHandler) { + HttpEntityEnclosingRequestBase request = addEntityToRequestBase(new HttpPatch(getURI(url)), entity); + if (headers != null) request.setHeaders(headers); + return sendRequest(httpClient, httpContext, request, contentType, responseHandler, context); + } + + /** + * Perform a HTTP DELETE request. + * + * @param url the URL to send the request to. + * @param responseHandler the response handler instance that should handle the response. + * @return RequestHandle of future request process + */ + public RequestHandle delete(String url, ResponseHandlerInterface responseHandler) { + return delete(null, url, responseHandler); + } + + // [-] HTTP DELETE + + /** + * Perform a HTTP DELETE request. + * + * @param context the Android Context which initiated the request. + * @param url the URL to send the request to. + * @param responseHandler the response handler instance that should handle the response. + * @return RequestHandle of future request process + */ + public RequestHandle delete(Context context, String url, ResponseHandlerInterface responseHandler) { + final HttpDelete delete = new HttpDelete(getURI(url)); + return sendRequest(httpClient, httpContext, delete, null, responseHandler, context); + } + + /** + * Perform a HTTP DELETE request. + * + * @param context the Android Context which initiated the request. + * @param url the URL to send the request to. + * @param headers set one-time headers for this request + * @param responseHandler the response handler instance that should handle the response. + * @return RequestHandle of future request process + */ + public RequestHandle delete(Context context, String url, Header[] headers, ResponseHandlerInterface responseHandler) { + final HttpDelete delete = new HttpDelete(getURI(url)); + if (headers != null) delete.setHeaders(headers); + return sendRequest(httpClient, httpContext, delete, null, responseHandler, context); + } + + /** + * Perform a HTTP DELETE request. + * + * @param url the URL to send the request to. + * @param params additional DELETE parameters or files to send with the request. + * @param responseHandler the response handler instance that should handle the response. + * @return RequestHandle of future request process + */ + public RequestHandle delete(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) { + final HttpDelete delete = new HttpDelete(getUrlWithQueryString(isUrlEncodingEnabled, url, params)); + return sendRequest(httpClient, httpContext, delete, null, responseHandler, null); + } + + /** + * Perform a HTTP DELETE request. + * + * @param context the Android Context which initiated the request. + * @param url the URL to send the request to. + * @param headers set one-time headers for this request + * @param params additional DELETE parameters or files to send along with request + * @param responseHandler the response handler instance that should handle the response. + * @return RequestHandle of future request process + */ + public RequestHandle delete(Context context, String url, Header[] headers, RequestParams params, ResponseHandlerInterface responseHandler) { + HttpDelete httpDelete = new HttpDelete(getUrlWithQueryString(isUrlEncodingEnabled, url, params)); + if (headers != null) httpDelete.setHeaders(headers); + return sendRequest(httpClient, httpContext, httpDelete, null, responseHandler, context); + } + + /** + * Perform a HTTP DELETE request and track the Android Context which initiated the request. + * + * @param context the Android Context which initiated the request. + * @param url the URL to send the request to. + * @param entity a raw {@link cz.msebera.android.httpclient.HttpEntity} to send with the request, for + * example, use this to send string/json/xml payloads to a server by + * passing a {@link cz.msebera.android.httpclient.entity.StringEntity}. + * @param contentType the content type of the payload you are sending, for example + * application/json if sending a json payload. + * @param responseHandler the response ha ndler instance that should handle the response. + * @return RequestHandle of future request process + */ + public RequestHandle delete(Context context, String url, HttpEntity entity, String contentType, ResponseHandlerInterface responseHandler) { + return sendRequest(httpClient, httpContext, addEntityToRequestBase(new HttpDelete(URI.create(url).normalize()), entity), contentType, responseHandler, context); + } + + /** + * Instantiate a new asynchronous HTTP request for the passed parameters. + * + * @param client HttpClient to be used for request, can differ in single requests + * @param contentType MIME body type, for POST and PUT requests, may be null + * @param context Context of Android application, to hold the reference of request + * @param httpContext HttpContext in which the request will be executed + * @param responseHandler ResponseHandler or its subclass to put the response into + * @param uriRequest instance of HttpUriRequest, which means it must be of HttpDelete, + * HttpPost, HttpGet, HttpPut, etc. + * @return AsyncHttpRequest ready to be dispatched + */ + protected AsyncHttpRequest newAsyncHttpRequest(DefaultHttpClient client, HttpContext httpContext, HttpUriRequest uriRequest, String contentType, ResponseHandlerInterface responseHandler, Context context) { + return new AsyncHttpRequest(client, httpContext, uriRequest, responseHandler); + } + + /** + * Puts a new request in queue as a new thread in pool to be executed + * + * @param client HttpClient to be used for request, can differ in single requests + * @param contentType MIME body type, for POST and PUT requests, may be null + * @param context Context of Android application, to hold the reference of request + * @param httpContext HttpContext in which the request will be executed + * @param responseHandler ResponseHandler or its subclass to put the response into + * @param uriRequest instance of HttpUriRequest, which means it must be of HttpDelete, + * HttpPost, HttpGet, HttpPut, etc. + * @return RequestHandle of future request process + */ + protected RequestHandle sendRequest(DefaultHttpClient client, HttpContext httpContext, HttpUriRequest uriRequest, String contentType, ResponseHandlerInterface responseHandler, Context context) { + if (uriRequest == null) { + throw new IllegalArgumentException("HttpUriRequest must not be null"); + } + + if (responseHandler == null) { + throw new IllegalArgumentException("ResponseHandler must not be null"); + } + + if (responseHandler.getUseSynchronousMode() && !responseHandler.getUsePoolThread()) { + throw new IllegalArgumentException("Synchronous ResponseHandler used in AsyncHttpClient. You should create your response handler in a looper thread or use SyncHttpClient instead."); + } + + if (contentType != null) { + if (uriRequest instanceof HttpEntityEnclosingRequestBase && ((HttpEntityEnclosingRequestBase) uriRequest).getEntity() != null && uriRequest.containsHeader(HEADER_CONTENT_TYPE)) { + log.w(LOG_TAG, "Passed contentType will be ignored because HttpEntity sets content type"); + } else { + uriRequest.setHeader(HEADER_CONTENT_TYPE, contentType); + } + } + + responseHandler.setRequestHeaders(uriRequest.getAllHeaders()); + responseHandler.setRequestURI(uriRequest.getURI()); + + AsyncHttpRequest request = newAsyncHttpRequest(client, httpContext, uriRequest, contentType, responseHandler, context); + threadPool.submit(request); + RequestHandle requestHandle = new RequestHandle(request); + + if (context != null) { + List requestList; + // Add request to request map + synchronized (requestMap) { + requestList = requestMap.get(context); + if (requestList == null) { + requestList = Collections.synchronizedList(new LinkedList()); + requestMap.put(context, requestList); + } + } + + requestList.add(requestHandle); + + Iterator iterator = requestList.iterator(); + while (iterator.hasNext()) { + if (iterator.next().shouldBeGarbageCollected()) { + iterator.remove(); + } + } + } + + return requestHandle; + } + + /** + * Returns a {@link URI} instance for the specified, absolute URL string. + * + * @param url absolute URL string, containing scheme, host and path + * @return URI instance for the URL string + */ + protected URI getURI(String url) { + return URI.create(url).normalize(); + } + + /** + * Sets state of URL encoding feature, see bug #227, this method allows you to turn off and on + * this auto-magic feature on-demand. + * + * @param enabled desired state of feature + */ + public void setURLEncodingEnabled(boolean enabled) { + this.isUrlEncodingEnabled = enabled; + } + + /** + * Returns HttpEntity containing data from RequestParams included with request declaration. + * Allows also passing progress from upload via provided ResponseHandler + * + * @param params additional request params + * @param responseHandler ResponseHandlerInterface or its subclass to be notified on progress + */ + private HttpEntity paramsToEntity(RequestParams params, ResponseHandlerInterface responseHandler) { + HttpEntity entity = null; + + try { + if (params != null) { + entity = params.getEntity(responseHandler); + } + } catch (IOException e) { + if (responseHandler != null) { + responseHandler.sendFailureMessage(0, null, null, e); + } else { + e.printStackTrace(); + } + } + + return entity; + } + + public boolean isUrlEncodingEnabled() { + return isUrlEncodingEnabled; + } + + /** + * Applicable only to HttpRequest methods extending HttpEntityEnclosingRequestBase, which is for + * example not DELETE + * + * @param entity entity to be included within the request + * @param requestBase HttpRequest instance, must not be null + */ + private HttpEntityEnclosingRequestBase addEntityToRequestBase(HttpEntityEnclosingRequestBase requestBase, HttpEntity entity) { + if (entity != null) { + requestBase.setEntity(entity); + } + + return requestBase; + } + + /** + * Enclosing entity to hold stream of gzip decoded data for accessing HttpEntity contents + */ + private static class InflatingEntity extends HttpEntityWrapper { + + InputStream wrappedStream; + PushbackInputStream pushbackStream; + GZIPInputStream gzippedStream; + + public InflatingEntity(HttpEntity wrapped) { + super(wrapped); + } + + @Override + public InputStream getContent() throws IOException { + wrappedStream = wrappedEntity.getContent(); + pushbackStream = new PushbackInputStream(wrappedStream, 2); + if (isInputStreamGZIPCompressed(pushbackStream)) { + gzippedStream = new GZIPInputStream(pushbackStream); + return gzippedStream; + } else { + return pushbackStream; + } + } + + @Override + public long getContentLength() { + return wrappedEntity == null ? 0 : wrappedEntity.getContentLength(); + } + + @Override + public void consumeContent() throws IOException { + AsyncHttpClient.silentCloseInputStream(wrappedStream); + AsyncHttpClient.silentCloseInputStream(pushbackStream); + AsyncHttpClient.silentCloseInputStream(gzippedStream); + super.consumeContent(); + } + } + + /** + * Call this method if your app target android below 4.4 + * This method enable sni in android below 4.4 + */ + public static void useConscryptSSLProvider(){ + ConscryptSSLProvider.install(); + } +} diff --git a/library/src/main/java/com/loopj/android/http/AsyncHttpRequest.java b/library/src/main/java/com/loopj/android/http/AsyncHttpRequest.java new file mode 100755 index 000000000..346cde73e --- /dev/null +++ b/library/src/main/java/com/loopj/android/http/AsyncHttpRequest.java @@ -0,0 +1,257 @@ +/* + Android Asynchronous Http Client + Copyright (c) 2011 James Smith + https://github.com/android-async-http/android-async-http + + 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 + + https://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.loopj.android.http; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.UnknownHostException; +import java.util.concurrent.atomic.AtomicBoolean; + +import cz.msebera.android.httpclient.HttpResponse; +import cz.msebera.android.httpclient.client.HttpRequestRetryHandler; +import cz.msebera.android.httpclient.client.methods.HttpUriRequest; +import cz.msebera.android.httpclient.impl.client.AbstractHttpClient; +import cz.msebera.android.httpclient.protocol.HttpContext; + +/** + * Internal class, representing the HttpRequest, done in asynchronous manner + */ +public class AsyncHttpRequest implements Runnable { + private final AbstractHttpClient client; + private final HttpContext context; + private final HttpUriRequest request; + private final ResponseHandlerInterface responseHandler; + private final AtomicBoolean isCancelled = new AtomicBoolean(); + private int executionCount; + private boolean cancelIsNotified; + private volatile boolean isFinished; + private boolean isRequestPreProcessed; + + public AsyncHttpRequest(AbstractHttpClient client, HttpContext context, HttpUriRequest request, ResponseHandlerInterface responseHandler) { + this.client = Utils.notNull(client, "client"); + this.context = Utils.notNull(context, "context"); + this.request = Utils.notNull(request, "request"); + this.responseHandler = Utils.notNull(responseHandler, "responseHandler"); + } + + /** + * This method is called once by the system when the request is about to be + * processed by the system. The library makes sure that a single request + * is pre-processed only once. + *

 

+ * Please note: pre-processing does NOT run on the main thread, and thus + * any UI activities that you must perform should be properly dispatched to + * the app's UI thread. + * + * @param request The request to pre-process + */ + public void onPreProcessRequest(AsyncHttpRequest request) { + // default action is to do nothing... + } + + /** + * This method is called once by the system when the request has been fully + * sent, handled and finished. The library makes sure that a single request + * is post-processed only once. + *

 

+ * Please note: post-processing does NOT run on the main thread, and thus + * any UI activities that you must perform should be properly dispatched to + * the app's UI thread. + * + * @param request The request to post-process + */ + public void onPostProcessRequest(AsyncHttpRequest request) { + // default action is to do nothing... + } + + @Override + public void run() { + if (isCancelled()) { + return; + } + + // Carry out pre-processing for this request only once. + if (!isRequestPreProcessed) { + isRequestPreProcessed = true; + onPreProcessRequest(this); + } + + if (isCancelled()) { + return; + } + + responseHandler.sendStartMessage(); + + if (isCancelled()) { + return; + } + + try { + makeRequestWithRetries(); + } catch (IOException e) { + if (!isCancelled()) { + responseHandler.sendFailureMessage(0, null, null, e); + } else { + AsyncHttpClient.log.e("AsyncHttpRequest", "makeRequestWithRetries returned error", e); + } + } + + if (isCancelled()) { + return; + } + + responseHandler.sendFinishMessage(); + + if (isCancelled()) { + return; + } + + // Carry out post-processing for this request. + onPostProcessRequest(this); + + isFinished = true; + } + + private void makeRequest() throws IOException { + if (isCancelled()) { + return; + } + + // Fixes #115 + if (request.getURI().getScheme() == null) { + // subclass of IOException so processed in the caller + throw new MalformedURLException("No valid URI scheme was provided"); + } + + if (responseHandler instanceof RangeFileAsyncHttpResponseHandler) { + ((RangeFileAsyncHttpResponseHandler) responseHandler).updateRequestHeaders(request); + } + + HttpResponse response = client.execute(request, context); + + if (isCancelled()) { + return; + } + + // Carry out pre-processing for this response. + responseHandler.onPreProcessResponse(responseHandler, response); + + if (isCancelled()) { + return; + } + + // The response is ready, handle it. + responseHandler.sendResponseMessage(response); + + if (isCancelled()) { + return; + } + + // Carry out post-processing for this response. + responseHandler.onPostProcessResponse(responseHandler, response); + } + + private void makeRequestWithRetries() throws IOException { + boolean retry = true; + IOException cause = null; + HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler(); + try { + while (retry) { + try { + makeRequest(); + return; + } catch (UnknownHostException e) { + // switching between WI-FI and mobile data networks can cause a retry which then results in an UnknownHostException + // while the WI-FI is initialising. The retry logic will be invoked here, if this is NOT the first retry + // (to assist in genuine cases of unknown host) which seems better than outright failure + cause = new IOException("UnknownHostException exception: " + e.getMessage(), e); + retry = (executionCount > 0) && retryHandler.retryRequest(e, ++executionCount, context); + } catch (NullPointerException e) { + // there's a bug in HttpClient 4.0.x that on some occasions causes + // DefaultRequestExecutor to throw an NPE, see + // https://code.google.com/p/android/issues/detail?id=5255 + cause = new IOException("NPE in HttpClient: " + e.getMessage()); + retry = retryHandler.retryRequest(cause, ++executionCount, context); + } catch (IOException e) { + if (isCancelled()) { + // Eating exception, as the request was cancelled + return; + } + cause = e; + retry = retryHandler.retryRequest(cause, ++executionCount, context); + } + if (retry) { + responseHandler.sendRetryMessage(executionCount); + } + } + } catch (Exception e) { + // catch anything else to ensure failure message is propagated + AsyncHttpClient.log.e("AsyncHttpRequest", "Unhandled exception origin cause", e); + cause = new IOException("Unhandled exception: " + e.getMessage(), cause); + } + + // cleaned up to throw IOException + throw (cause); + } + + public boolean isCancelled() { + boolean cancelled = isCancelled.get(); + if (cancelled) { + sendCancelNotification(); + } + return cancelled; + } + + private synchronized void sendCancelNotification() { + if (!isFinished && isCancelled.get() && !cancelIsNotified) { + cancelIsNotified = true; + responseHandler.sendCancelMessage(); + } + } + + public boolean isDone() { + return isCancelled() || isFinished; + } + + public boolean cancel(boolean mayInterruptIfRunning) { + isCancelled.set(true); + request.abort(); + return isCancelled(); + } + + /** + * Will set Object as TAG to this request, wrapped by WeakReference + * + * @param TAG Object used as TAG to this RequestHandle + * @return this AsyncHttpRequest to allow fluid syntax + */ + public AsyncHttpRequest setRequestTag(Object TAG) { + this.responseHandler.setTag(TAG); + return this; + } + + /** + * Will return TAG of this AsyncHttpRequest + * + * @return Object TAG, can be null, if it's been already garbage collected + */ + public Object getTag() { + return this.responseHandler.getTag(); + } +} diff --git a/library/src/main/java/com/loopj/android/http/AsyncHttpResponseHandler.java b/library/src/main/java/com/loopj/android/http/AsyncHttpResponseHandler.java new file mode 100755 index 000000000..096020d9e --- /dev/null +++ b/library/src/main/java/com/loopj/android/http/AsyncHttpResponseHandler.java @@ -0,0 +1,516 @@ +/* + Android Asynchronous Http Client + Copyright (c) 2011 James Smith + https://github.com/android-async-http/android-async-http + + 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 + + https://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.loopj.android.http; + +import android.os.Handler; +import android.os.Looper; +import android.os.Message; + +import java.io.IOException; +import java.io.InputStream; +import java.lang.ref.WeakReference; +import java.net.URI; +import java.util.Locale; + +import cz.msebera.android.httpclient.Header; +import cz.msebera.android.httpclient.HttpEntity; +import cz.msebera.android.httpclient.HttpResponse; +import cz.msebera.android.httpclient.StatusLine; +import cz.msebera.android.httpclient.client.HttpResponseException; +import cz.msebera.android.httpclient.util.ByteArrayBuffer; + +/** + * Used to intercept and handle the responses from requests made using {@link AsyncHttpClient}. The + * {@link #onSuccess(int, cz.msebera.android.httpclient.Header[], byte[])} method is designed to be anonymously + * overridden with your own response handling code.

 

Additionally, you can override the + * {@link #onFailure(int, cz.msebera.android.httpclient.Header[], byte[], Throwable)}, {@link #onStart()}, {@link + * #onFinish()}, {@link #onRetry(int)} and {@link #onProgress(long, long)} methods as required. + *

 

For example:

 

+ *
+ * AsyncHttpClient client = new AsyncHttpClient();
+ * client.get("https://www.google.com/", new AsyncHttpResponseHandler() {
+ *     @Override
+ *     public void onStart() {
+ *         // Initiated the request
+ *     }
+ *
+ *     @Override
+ *     public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
+ *         // Successfully got a response
+ *     }
+ *
+ *     @Override
+ *     public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable
+ * error)
+ * {
+ *         // Response failed :(
+ *     }
+ *
+ *     @Override
+ *     public void onRetry(int retryNo) {
+ *         // Request was retried
+ *     }
+ *
+ *     @Override
+ *     public void onProgress(long bytesWritten, long totalSize) {
+ *         // Progress notification
+ *     }
+ *
+ *     @Override
+ *     public void onFinish() {
+ *         // Completed the request (either success or failure)
+ *     }
+ * });
+ * 
+ */ +@SuppressWarnings("DesignForExtension") +public abstract class AsyncHttpResponseHandler implements ResponseHandlerInterface { + + public static final String DEFAULT_CHARSET = "UTF-8"; + public static final String UTF8_BOM = "\uFEFF"; + protected static final int SUCCESS_MESSAGE = 0; + protected static final int FAILURE_MESSAGE = 1; + protected static final int START_MESSAGE = 2; + protected static final int FINISH_MESSAGE = 3; + protected static final int PROGRESS_MESSAGE = 4; + protected static final int RETRY_MESSAGE = 5; + protected static final int CANCEL_MESSAGE = 6; + protected static final int BUFFER_SIZE = 4096; + private static final String LOG_TAG = "AsyncHttpRH"; + private String responseCharset = DEFAULT_CHARSET; + private Handler handler; + private boolean useSynchronousMode; + private boolean usePoolThread; + + private URI requestURI = null; + private Header[] requestHeaders = null; + private Looper looper = null; + private WeakReference TAG = new WeakReference(null); + + /** + * Creates a new AsyncHttpResponseHandler + */ + public AsyncHttpResponseHandler() { + this(null); + } + + /** + * Creates a new AsyncHttpResponseHandler with a user-supplied looper. If + * the passed looper is null, the looper attached to the current thread will + * be used. + * + * @param looper The looper to work with + */ + public AsyncHttpResponseHandler(Looper looper) { + // Do not use the pool's thread to fire callbacks by default. + this(looper == null ? Looper.myLooper() : looper, false); + } + + /** + * Creates a new AsyncHttpResponseHandler and decide whether the callbacks + * will be fired on current thread's looper or the pool thread's. + * + * @param usePoolThread Whether to use the pool's thread to fire callbacks + */ + public AsyncHttpResponseHandler(boolean usePoolThread) { + this(usePoolThread ? null : Looper.myLooper(), usePoolThread); + } + + private AsyncHttpResponseHandler(Looper looper, boolean usePoolThread) { + if (!usePoolThread) { + Utils.asserts(looper != null, "use looper thread, must call Looper.prepare() first!"); + this.looper = looper; + // Create a handler on current thread to submit tasks + this.handler = new ResponderHandler(this, looper); + } else { + Utils.asserts(looper == null, "use pool thread, looper should be null!"); + // If pool thread is to be used, there's no point in keeping a reference + // to the looper and handler. + this.looper = null; + this.handler = null; + } + + this.usePoolThread = usePoolThread; + } + + @Override + public Object getTag() { + return this.TAG.get(); + } + + @Override + public void setTag(Object TAG) { + this.TAG = new WeakReference(TAG); + } + + @Override + public URI getRequestURI() { + return this.requestURI; + } + + @Override + public void setRequestURI(URI requestURI) { + this.requestURI = requestURI; + } + + @Override + public Header[] getRequestHeaders() { + return this.requestHeaders; + } + + @Override + public void setRequestHeaders(Header[] requestHeaders) { + this.requestHeaders = requestHeaders; + } + + @Override + public boolean getUseSynchronousMode() { + return useSynchronousMode; + } + + @Override + public void setUseSynchronousMode(boolean sync) { + // A looper must be prepared before setting asynchronous mode. + if (!sync && looper == null) { + sync = true; + AsyncHttpClient.log.w(LOG_TAG, "Current thread has not called Looper.prepare(). Forcing synchronous mode."); + } + + // If using asynchronous mode. + if (!sync && handler == null) { + // Create a handler on current thread to submit tasks + handler = new ResponderHandler(this, looper); + } else if (sync && handler != null) { + // TODO: Consider adding a flag to remove all queued messages. + handler = null; + } + + useSynchronousMode = sync; + } + + @Override + public boolean getUsePoolThread() { + return usePoolThread; + } + + @Override + public void setUsePoolThread(boolean pool) { + // If pool thread is to be used, there's no point in keeping a reference + // to the looper and no need for a handler. + if (pool) { + looper = null; + handler = null; + } + + usePoolThread = pool; + } + + public String getCharset() { + return this.responseCharset == null ? DEFAULT_CHARSET : this.responseCharset; + } + + /** + * Sets the charset for the response string. If not set, the default is UTF-8. + * + * @param charset to be used for the response string. + * @see Charset + */ + public void setCharset(final String charset) { + this.responseCharset = charset; + } + + /** + * Fired when the request progress, override to handle in your own code + * + * @param bytesWritten offset from start of file + * @param totalSize total size of file + */ + public void onProgress(long bytesWritten, long totalSize) { + AsyncHttpClient.log.v(LOG_TAG, String.format(Locale.US, "Progress %d from %d (%2.0f%%)", bytesWritten, totalSize, (totalSize > 0) ? (bytesWritten * 1.0 / totalSize) * 100 : -1)); + } + + /** + * Fired when the request is started, override to handle in your own code + */ + public void onStart() { + // default log warning is not necessary, because this method is just optional notification + } + + /** + * Fired in all cases when the request is finished, after both success and failure, override to + * handle in your own code + */ + public void onFinish() { + // default log warning is not necessary, because this method is just optional notification + } + + @Override + public void onPreProcessResponse(ResponseHandlerInterface instance, HttpResponse response) { + // default action is to do nothing... + } + + @Override + public void onPostProcessResponse(ResponseHandlerInterface instance, HttpResponse response) { + // default action is to do nothing... + } + + /** + * Fired when a request returns successfully, override to handle in your own code + * + * @param statusCode the status code of the response + * @param headers return headers, if any + * @param responseBody the body of the HTTP response from the server + */ + public abstract void onSuccess(int statusCode, Header[] headers, byte[] responseBody); + + /** + * Fired when a request fails to complete, override to handle in your own code + * + * @param statusCode return HTTP status code + * @param headers return headers, if any + * @param responseBody the response body, if any + * @param error the underlying cause of the failure + */ + public abstract void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error); + + /** + * Fired when a retry occurs, override to handle in your own code + * + * @param retryNo number of retry + */ + public void onRetry(int retryNo) { + AsyncHttpClient.log.d(LOG_TAG, String.format(Locale.US, "Request retry no. %d", retryNo)); + } + + public void onCancel() { + AsyncHttpClient.log.d(LOG_TAG, "Request got cancelled"); + } + + public void onUserException(Throwable error) { + AsyncHttpClient.log.e(LOG_TAG, "User-space exception detected!", error); + throw new RuntimeException(error); + } + + @Override + final public void sendProgressMessage(long bytesWritten, long bytesTotal) { + sendMessage(obtainMessage(PROGRESS_MESSAGE, new Object[]{bytesWritten, bytesTotal})); + } + + @Override + final public void sendSuccessMessage(int statusCode, Header[] headers, byte[] responseBytes) { + sendMessage(obtainMessage(SUCCESS_MESSAGE, new Object[]{statusCode, headers, responseBytes})); + } + + @Override + final public void sendFailureMessage(int statusCode, Header[] headers, byte[] responseBody, Throwable throwable) { + sendMessage(obtainMessage(FAILURE_MESSAGE, new Object[]{statusCode, headers, responseBody, throwable})); + } + + @Override + final public void sendStartMessage() { + sendMessage(obtainMessage(START_MESSAGE, null)); + } + + @Override + final public void sendFinishMessage() { + sendMessage(obtainMessage(FINISH_MESSAGE, null)); + } + + @Override + final public void sendRetryMessage(int retryNo) { + sendMessage(obtainMessage(RETRY_MESSAGE, new Object[]{retryNo})); + } + + @Override + final public void sendCancelMessage() { + sendMessage(obtainMessage(CANCEL_MESSAGE, null)); + } + + // Methods which emulate android's Handler and Message methods + protected void handleMessage(Message message) { + Object[] response; + + try { + switch (message.what) { + case SUCCESS_MESSAGE: + response = (Object[]) message.obj; + if (response != null && response.length >= 3) { + onSuccess((Integer) response[0], (Header[]) response[1], (byte[]) response[2]); + } else { + AsyncHttpClient.log.e(LOG_TAG, "SUCCESS_MESSAGE didn't got enough params"); + } + break; + case FAILURE_MESSAGE: + response = (Object[]) message.obj; + if (response != null && response.length >= 4) { + onFailure((Integer) response[0], (Header[]) response[1], (byte[]) response[2], (Throwable) response[3]); + } else { + AsyncHttpClient.log.e(LOG_TAG, "FAILURE_MESSAGE didn't got enough params"); + } + break; + case START_MESSAGE: + onStart(); + break; + case FINISH_MESSAGE: + onFinish(); + break; + case PROGRESS_MESSAGE: + response = (Object[]) message.obj; + if (response != null && response.length >= 2) { + try { + onProgress((Long) response[0], (Long) response[1]); + } catch (Throwable t) { + AsyncHttpClient.log.e(LOG_TAG, "custom onProgress contains an error", t); + } + } else { + AsyncHttpClient.log.e(LOG_TAG, "PROGRESS_MESSAGE didn't got enough params"); + } + break; + case RETRY_MESSAGE: + response = (Object[]) message.obj; + if (response != null && response.length == 1) { + onRetry((Integer) response[0]); + } else { + AsyncHttpClient.log.e(LOG_TAG, "RETRY_MESSAGE didn't get enough params"); + } + break; + case CANCEL_MESSAGE: + onCancel(); + break; + } + } catch (Throwable error) { + onUserException(error); + } + } + + protected void sendMessage(Message msg) { + if (getUseSynchronousMode() || handler == null) { + handleMessage(msg); + } else if (!Thread.currentThread().isInterrupted()) { // do not send messages if request has been cancelled + Utils.asserts(handler != null, "handler should not be null!"); + handler.sendMessage(msg); + } + } + + /** + * Helper method to send runnable into local handler loop + * + * @param runnable runnable instance, can be null + */ + protected void postRunnable(Runnable runnable) { + if (runnable != null) { + if (getUseSynchronousMode() || handler == null) { + // This response handler is synchronous, run on current thread + runnable.run(); + } else { + // Otherwise, run on provided handler + handler.post(runnable); + } + } + } + + /** + * Helper method to create Message instance from handler + * + * @param responseMessageId constant to identify Handler message + * @param responseMessageData object to be passed to message receiver + * @return Message instance, should not be null + */ + protected Message obtainMessage(int responseMessageId, Object responseMessageData) { + return Message.obtain(handler, responseMessageId, responseMessageData); + } + + @Override + public void sendResponseMessage(HttpResponse response) throws IOException { + // do not process if request has been cancelled + if (!Thread.currentThread().isInterrupted()) { + StatusLine status = response.getStatusLine(); + byte[] responseBody; + responseBody = getResponseData(response.getEntity()); + // additional cancellation check as getResponseData() can take non-zero time to process + if (!Thread.currentThread().isInterrupted()) { + if (status.getStatusCode() >= 300) { + sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), responseBody, new HttpResponseException(status.getStatusCode(), status.getReasonPhrase())); + } else { + sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), responseBody); + } + } + } + } + + /** + * Returns byte array of response HttpEntity contents + * + * @param entity can be null + * @return response entity body or null + * @throws java.io.IOException if reading entity or creating byte array failed + */ + byte[] getResponseData(HttpEntity entity) throws IOException { + byte[] responseBody = null; + if (entity != null) { + InputStream instream = entity.getContent(); + if (instream != null) { + long contentLength = entity.getContentLength(); + if (contentLength > Integer.MAX_VALUE) { + throw new IllegalArgumentException("HTTP entity too large to be buffered in memory"); + } + int buffersize = (contentLength <= 0) ? BUFFER_SIZE : (int) contentLength; + try { + ByteArrayBuffer buffer = new ByteArrayBuffer(buffersize); + try { + byte[] tmp = new byte[BUFFER_SIZE]; + long count = 0; + int l; + // do not send messages if request has been cancelled + while ((l = instream.read(tmp)) != -1 && !Thread.currentThread().isInterrupted()) { + count += l; + buffer.append(tmp, 0, l); + sendProgressMessage(count, (contentLength <= 0 ? 1 : contentLength)); + } + } finally { + AsyncHttpClient.silentCloseInputStream(instream); + AsyncHttpClient.endEntityViaReflection(entity); + } + responseBody = buffer.toByteArray(); + } catch (OutOfMemoryError e) { + System.gc(); + throw new IOException("File too large to fit into available memory"); + } + } + } + return responseBody; + } + + /** + * Avoid leaks by using a non-anonymous handler class. + */ + private static class ResponderHandler extends Handler { + private final AsyncHttpResponseHandler mResponder; + + ResponderHandler(AsyncHttpResponseHandler mResponder, Looper looper) { + super(looper); + this.mResponder = mResponder; + } + + @Override + public void handleMessage(Message msg) { + mResponder.handleMessage(msg); + } + } +} diff --git a/library/src/main/java/com/loopj/android/http/Base64.java b/library/src/main/java/com/loopj/android/http/Base64.java new file mode 100755 index 000000000..045b46ead --- /dev/null +++ b/library/src/main/java/com/loopj/android/http/Base64.java @@ -0,0 +1,714 @@ +/* + * Copyright (C) 2010 The 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 + * + * https://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.loopj.android.http; + +import java.io.UnsupportedEncodingException; + +/** + * Utilities for encoding and decoding the Base64 representation of binary data. See RFCs 2045 and 3548. + */ +public class Base64 { + /** + * Default values for encoder/decoder flags. + */ + public static final int DEFAULT = 0; + + /** + * Encoder flag bit to omit the padding '=' characters at the end of the output (if any). + */ + public static final int NO_PADDING = 1; + + /** + * Encoder flag bit to omit all line terminators (i.e., the output will be on one long line). + */ + public static final int NO_WRAP = 2; + + /** + * Encoder flag bit to indicate lines should be terminated with a CRLF pair instead of just an + * LF. Has no effect if {@code NO_WRAP} is specified as well. + */ + public static final int CRLF = 4; + + /** + * Encoder/decoder flag bit to indicate using the "URL and filename safe" variant of Base64 (see + * RFC 3548 section 4) where {@code -} and {@code _} are used in place of {@code +} and {@code + * /}. + */ + public static final int URL_SAFE = 8; + + /** + * Flag to pass to {@link Base64OutputStream} to indicate that it should not close the output + * stream it is wrapping when it itself is closed. + */ + public static final int NO_CLOSE = 16; + + // -------------------------------------------------------- + // shared code + // -------------------------------------------------------- + + private Base64() { + } // don't instantiate + + // -------------------------------------------------------- + // decoding + // -------------------------------------------------------- + + /** + * Decode the Base64-encoded data in input and return the data in a new byte array. + *

 

The padding '=' characters at the end are considered optional, but if any + * are present, there must be the correct number of them. + * + * @param str the input String to decode, which is converted to bytes using the default + * charset + * @param flags controls certain features of the decoded output. Pass {@code DEFAULT} to decode + * standard Base64. + * @return decoded bytes + * @throws IllegalArgumentException if the input contains incorrect padding + */ + public static byte[] decode(String str, int flags) { + return decode(str.getBytes(), flags); + } + + /** + * Decode the Base64-encoded data in input and return the data in a new byte array. + *

 

The padding '=' characters at the end are considered optional, but if any + * are present, there must be the correct number of them. + * + * @param input the input array to decode + * @param flags controls certain features of the decoded output. Pass {@code DEFAULT} to decode + * standard Base64. + * @return decoded bytes + * @throws IllegalArgumentException if the input contains incorrect padding + */ + public static byte[] decode(byte[] input, int flags) { + return decode(input, 0, input.length, flags); + } + + /** + * Decode the Base64-encoded data in input and return the data in a new byte array. + *

 

The padding '=' characters at the end are considered optional, but if any + * are present, there must be the correct number of them. + * + * @param input the data to decode + * @param offset the position within the input array at which to start + * @param len the number of bytes of input to decode + * @param flags controls certain features of the decoded output. Pass {@code DEFAULT} to decode + * standard Base64. + * @return decoded bytes for given offset and length + * @throws IllegalArgumentException if the input contains incorrect padding + */ + public static byte[] decode(byte[] input, int offset, int len, int flags) { + // Allocate space for the most data the input could represent. + // (It could contain less if it contains whitespace, etc.) + Decoder decoder = new Decoder(flags, new byte[len * 3 / 4]); + + if (!decoder.process(input, offset, len, true)) { + throw new IllegalArgumentException("bad base-64"); + } + + // Maybe we got lucky and allocated exactly enough output space. + if (decoder.op == decoder.output.length) { + return decoder.output; + } + + // Need to shorten the array, so allocate a new one of the + // right size and copy. + byte[] temp = new byte[decoder.op]; + System.arraycopy(decoder.output, 0, temp, 0, decoder.op); + return temp; + } + + /** + * Base64-encode the given data and return a newly allocated String with the result. + * + * @param input the data to encode + * @param flags controls certain features of the encoded output. Passing {@code DEFAULT} results + * in output that adheres to RFC 2045. + * @return base64 string containing encoded input + */ + public static String encodeToString(byte[] input, int flags) { + try { + return new String(encode(input, flags), "US-ASCII"); + } catch (UnsupportedEncodingException e) { + // US-ASCII is guaranteed to be available. + throw new AssertionError(e); + } + } + + // -------------------------------------------------------- + // encoding + // -------------------------------------------------------- + + /** + * Base64-encode the given data and return a newly allocated String with the result. + * + * @param input the data to encode + * @param offset the position within the input array at which to start + * @param len the number of bytes of input to encode + * @param flags controls certain features of the encoded output. Passing {@code DEFAULT} + * results in output that adheres to RFC 2045. + * @return base64 string containing encoded range of input + */ + public static String encodeToString(byte[] input, int offset, int len, int flags) { + try { + return new String(encode(input, offset, len, flags), "US-ASCII"); + } catch (UnsupportedEncodingException e) { + // US-ASCII is guaranteed to be available. + throw new AssertionError(e); + } + } + + /** + * Base64-encode the given data and return a newly allocated byte[] with the result. + * + * @param input the data to encode + * @param flags controls certain features of the encoded output. Passing {@code DEFAULT} results + * in output that adheres to RFC 2045. + * @return base64 encoded input as bytes + */ + public static byte[] encode(byte[] input, int flags) { + return encode(input, 0, input.length, flags); + } + + /** + * Base64-encode the given data and return a newly allocated byte[] with the result. + * + * @param input the data to encode + * @param offset the position within the input array at which to start + * @param len the number of bytes of input to encode + * @param flags controls certain features of the encoded output. Passing {@code DEFAULT} + * results in output that adheres to RFC 2045. + * @return base64 encoded input as bytes + */ + public static byte[] encode(byte[] input, int offset, int len, int flags) { + Encoder encoder = new Encoder(flags, null); + + // Compute the exact length of the array we will produce. + int output_len = len / 3 * 4; + + // Account for the tail of the data and the padding bytes, if any. + if (encoder.do_padding) { + if (len % 3 > 0) { + output_len += 4; + } + } else { + switch (len % 3) { + case 0: + break; + case 1: + output_len += 2; + break; + case 2: + output_len += 3; + break; + } + } + + // Account for the newlines, if any. + if (encoder.do_newline && len > 0) { + output_len += (((len - 1) / (3 * Encoder.LINE_GROUPS)) + 1) * + (encoder.do_cr ? 2 : 1); + } + + encoder.output = new byte[output_len]; + encoder.process(input, offset, len, true); + + if (BuildConfig.DEBUG && encoder.op != output_len) { + throw new AssertionError(); + } + + return encoder.output; + } + + /* package */ static abstract class Coder { + public byte[] output; + public int op; + + /** + * Encode/decode another block of input data. this.output is provided by the caller, and + * must be big enough to hold all the coded data. On exit, this.opwill be set to the length + * of the coded data. + * + * @param finish true if this is the final call to process for this object. Will finalize + * the coder state and include any final bytes in the output. + * @return true if the input so far is good; false if some error has been detected in the + * input stream.. + */ + public abstract boolean process(byte[] input, int offset, int len, boolean finish); + + /** + * @return the maximum number of bytes a call to process() could produce for the given + * number of input bytes. This may be an overestimate. + */ + public abstract int maxOutputSize(int len); + } + + /* package */ static class Decoder extends Coder { + /** + * Lookup table for turning bytes into their position in the Base64 alphabet. + */ + private static final int DECODE[] = { + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, + 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -2, -1, -1, + -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, + 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, + -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, + 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + }; + + /** + * Decode lookup table for the "web safe" variant (RFC 3548 sec. 4) where - and _ replace + + * and /. + */ + private static final int DECODE_WEBSAFE[] = { + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, + 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -2, -1, -1, + -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, + 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, 63, + -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, + 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + }; + + /** + * Non-data values in the DECODE arrays. + */ + private static final int SKIP = -1; + private static final int EQUALS = -2; + final private int[] alphabet; + /** + * States 0-3 are reading through the next input tuple. State 4 is having read one '=' and + * expecting exactly one more. State 5 is expecting no more data or padding characters in + * the input. State 6 is the error state; an error has been detected in the input and no + * future input can "fix" it. + */ + private int state; // state number (0 to 6) + private int value; + + public Decoder(int flags, byte[] output) { + this.output = output; + + alphabet = ((flags & URL_SAFE) == 0) ? DECODE : DECODE_WEBSAFE; + state = 0; + value = 0; + } + + /** + * @return an overestimate for the number of bytes {@code len} bytes could decode to. + */ + public int maxOutputSize(int len) { + return len * 3 / 4 + 10; + } + + /** + * Decode another block of input data. + * + * @return true if the state machine is still healthy. false if bad base-64 data has been + * detected in the input stream. + */ + public boolean process(byte[] input, int offset, int len, boolean finish) { + if (this.state == 6) return false; + + int p = offset; + len += offset; + + // Using local variables makes the decoder about 12% + // faster than if we manipulate the member variables in + // the loop. (Even alphabet makes a measurable + // difference, which is somewhat surprising to me since + // the member variable is final.) + int state = this.state; + int value = this.value; + int op = 0; + final byte[] output = this.output; + final int[] alphabet = this.alphabet; + + while (p < len) { + // Try the fast path: we're starting a new tuple and the + // next four bytes of the input stream are all data + // bytes. This corresponds to going through states + // 0-1-2-3-0. We expect to use this method for most of + // the data. + // + // If any of the next four bytes of input are non-data + // (whitespace, etc.), value will end up negative. (All + // the non-data values in decode are small negative + // numbers, so shifting any of them up and or'ing them + // together will result in a value with its top bit set.) + // + // You can remove this whole block and the output should + // be the same, just slower. + if (state == 0) { + while (p + 4 <= len && + (value = ((alphabet[input[p] & 0xff] << 18) | + (alphabet[input[p + 1] & 0xff] << 12) | + (alphabet[input[p + 2] & 0xff] << 6) | + (alphabet[input[p + 3] & 0xff]))) >= 0) { + output[op + 2] = (byte) value; + output[op + 1] = (byte) (value >> 8); + output[op] = (byte) (value >> 16); + op += 3; + p += 4; + } + if (p >= len) break; + } + + // The fast path isn't available -- either we've read a + // partial tuple, or the next four input bytes aren't all + // data, or whatever. Fall back to the slower state + // machine implementation. + + int d = alphabet[input[p++] & 0xff]; + + switch (state) { + case 0: + if (d >= 0) { + value = d; + ++state; + } else if (d != SKIP) { + this.state = 6; + return false; + } + break; + + case 1: + if (d >= 0) { + value = (value << 6) | d; + ++state; + } else if (d != SKIP) { + this.state = 6; + return false; + } + break; + + case 2: + if (d >= 0) { + value = (value << 6) | d; + ++state; + } else if (d == EQUALS) { + // Emit the last (partial) output tuple; + // expect exactly one more padding character. + output[op++] = (byte) (value >> 4); + state = 4; + } else if (d != SKIP) { + this.state = 6; + return false; + } + break; + + case 3: + if (d >= 0) { + // Emit the output triple and return to state 0. + value = (value << 6) | d; + output[op + 2] = (byte) value; + output[op + 1] = (byte) (value >> 8); + output[op] = (byte) (value >> 16); + op += 3; + state = 0; + } else if (d == EQUALS) { + // Emit the last (partial) output tuple; + // expect no further data or padding characters. + output[op + 1] = (byte) (value >> 2); + output[op] = (byte) (value >> 10); + op += 2; + state = 5; + } else if (d != SKIP) { + this.state = 6; + return false; + } + break; + + case 4: + if (d == EQUALS) { + ++state; + } else if (d != SKIP) { + this.state = 6; + return false; + } + break; + + case 5: + if (d != SKIP) { + this.state = 6; + return false; + } + break; + } + } + + if (!finish) { + // We're out of input, but a future call could provide + // more. + this.state = state; + this.value = value; + this.op = op; + return true; + } + + // Done reading input. Now figure out where we are left in + // the state machine and finish up. + + switch (state) { + case 0: + // Output length is a multiple of three. Fine. + break; + case 1: + // Read one extra input byte, which isn't enough to + // make another output byte. Illegal. + this.state = 6; + return false; + case 2: + // Read two extra input bytes, enough to emit 1 more + // output byte. Fine. + output[op++] = (byte) (value >> 4); + break; + case 3: + // Read three extra input bytes, enough to emit 2 more + // output bytes. Fine. + output[op++] = (byte) (value >> 10); + output[op++] = (byte) (value >> 2); + break; + case 4: + // Read one padding '=' when we expected 2. Illegal. + this.state = 6; + return false; + case 5: + // Read all the padding '='s we expected and no more. + // Fine. + break; + } + + this.state = state; + this.op = op; + return true; + } + } + + /* package */ static class Encoder extends Coder { + /** + * Emit a new line every this many output tuples. Corresponds to a 76-character line length + * (the maximum allowable according to RFC + * 2045). + */ + public static final int LINE_GROUPS = 19; + + /** + * Lookup table for turning Base64 alphabet positions (6 bits) into output bytes. + */ + private static final byte ENCODE[] = { + 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', + 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', + 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', + 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/', + }; + + /** + * Lookup table for turning Base64 alphabet positions (6 bits) into output bytes. + */ + private static final byte ENCODE_WEBSAFE[] = { + 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', + 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', + 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', + 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '_', + }; + final public boolean do_padding; + final public boolean do_newline; + final public boolean do_cr; + final private byte[] tail; + final private byte[] alphabet; + /* package */ int tailLen; + private int count; + + public Encoder(int flags, byte[] output) { + this.output = output; + + do_padding = (flags & NO_PADDING) == 0; + do_newline = (flags & NO_WRAP) == 0; + do_cr = (flags & CRLF) != 0; + alphabet = ((flags & URL_SAFE) == 0) ? ENCODE : ENCODE_WEBSAFE; + + tail = new byte[2]; + tailLen = 0; + + count = do_newline ? LINE_GROUPS : -1; + } + + /** + * @return an overestimate for the number of bytes {@code len} bytes could encode to. + */ + public int maxOutputSize(int len) { + return len * 8 / 5 + 10; + } + + public boolean process(byte[] input, int offset, int len, boolean finish) { + // Using local variables makes the encoder about 9% faster. + final byte[] alphabet = this.alphabet; + final byte[] output = this.output; + int op = 0; + int count = this.count; + + int p = offset; + len += offset; + int v = -1; + + // First we need to concatenate the tail of the previous call + // with any input bytes available now and see if we can empty + // the tail. + + switch (tailLen) { + case 0: + // There was no tail. + break; + + case 1: + if (p + 2 <= len) { + // A 1-byte tail with at least 2 bytes of + // input available now. + v = ((tail[0] & 0xff) << 16) | + ((input[p++] & 0xff) << 8) | + (input[p++] & 0xff); + tailLen = 0; + } + break; + + case 2: + if (p + 1 <= len) { + // A 2-byte tail with at least 1 byte of input. + v = ((tail[0] & 0xff) << 16) | + ((tail[1] & 0xff) << 8) | + (input[p++] & 0xff); + tailLen = 0; + } + break; + } + + if (v != -1) { + output[op++] = alphabet[(v >> 18) & 0x3f]; + output[op++] = alphabet[(v >> 12) & 0x3f]; + output[op++] = alphabet[(v >> 6) & 0x3f]; + output[op++] = alphabet[v & 0x3f]; + if (--count == 0) { + if (do_cr) output[op++] = '\r'; + output[op++] = '\n'; + count = LINE_GROUPS; + } + } + + // At this point either there is no tail, or there are fewer + // than 3 bytes of input available. + + // The main loop, turning 3 input bytes into 4 output bytes on + // each iteration. + while (p + 3 <= len) { + v = ((input[p] & 0xff) << 16) | + ((input[p + 1] & 0xff) << 8) | + (input[p + 2] & 0xff); + output[op] = alphabet[(v >> 18) & 0x3f]; + output[op + 1] = alphabet[(v >> 12) & 0x3f]; + output[op + 2] = alphabet[(v >> 6) & 0x3f]; + output[op + 3] = alphabet[v & 0x3f]; + p += 3; + op += 4; + if (--count == 0) { + if (do_cr) output[op++] = '\r'; + output[op++] = '\n'; + count = LINE_GROUPS; + } + } + + if (finish) { + // Finish up the tail of the input. Note that we need to + // consume any bytes in tail before any bytes + // remaining in input; there should be at most two bytes + // total. + + if (p - tailLen == len - 1) { + int t = 0; + v = ((tailLen > 0 ? tail[t++] : input[p++]) & 0xff) << 4; + tailLen -= t; + output[op++] = alphabet[(v >> 6) & 0x3f]; + output[op++] = alphabet[v & 0x3f]; + if (do_padding) { + output[op++] = '='; + output[op++] = '='; + } + if (do_newline) { + if (do_cr) output[op++] = '\r'; + output[op++] = '\n'; + } + } else if (p - tailLen == len - 2) { + int t = 0; + v = (((tailLen > 1 ? tail[t++] : input[p++]) & 0xff) << 10) | + (((tailLen > 0 ? tail[t++] : input[p++]) & 0xff) << 2); + tailLen -= t; + output[op++] = alphabet[(v >> 12) & 0x3f]; + output[op++] = alphabet[(v >> 6) & 0x3f]; + output[op++] = alphabet[v & 0x3f]; + if (do_padding) { + output[op++] = '='; + } + if (do_newline) { + if (do_cr) output[op++] = '\r'; + output[op++] = '\n'; + } + } else if (do_newline && op > 0 && count != LINE_GROUPS) { + if (do_cr) output[op++] = '\r'; + output[op++] = '\n'; + } + + if (BuildConfig.DEBUG && (tailLen != 0 || p != len)) { + throw new AssertionError(); + } + } else { + // Save the leftovers in tail to be consumed on the next + // call to encodeInternal. + + if (p == len - 1) { + tail[tailLen++] = input[p]; + } else if (p == len - 2) { + tail[tailLen++] = input[p]; + tail[tailLen++] = input[p + 1]; + } + } + + this.op = op; + this.count = count; + + return true; + } + } +} diff --git a/library/src/main/java/com/loopj/android/http/Base64DataException.java b/library/src/main/java/com/loopj/android/http/Base64DataException.java new file mode 100755 index 000000000..50127c1f4 --- /dev/null +++ b/library/src/main/java/com/loopj/android/http/Base64DataException.java @@ -0,0 +1,25 @@ +/* + * Copyright (C) 2010 The 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 + * + * https://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.loopj.android.http; + +import java.io.IOException; + +public class Base64DataException extends IOException { + public Base64DataException(String detailMessage) { + super(detailMessage); + } +} \ No newline at end of file diff --git a/library/src/main/java/com/loopj/android/http/Base64OutputStream.java b/library/src/main/java/com/loopj/android/http/Base64OutputStream.java new file mode 100755 index 000000000..07fb6f7cd --- /dev/null +++ b/library/src/main/java/com/loopj/android/http/Base64OutputStream.java @@ -0,0 +1,146 @@ +/* + * Copyright (C) 2010 The 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 + * + * https://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.loopj.android.http; + +import java.io.FilterOutputStream; +import java.io.IOException; +import java.io.OutputStream; + +public class Base64OutputStream extends FilterOutputStream { + private static final byte[] EMPTY = new byte[0]; + private final Base64.Coder coder; + private final int flags; + private byte[] buffer = null; + private int bpos = 0; + + /** + * Performs Base64 encoding on the data written to the stream, writing the encoded data to + * another OutputStream. + * + * @param out the OutputStream to write the encoded data to + * @param flags bit flags for controlling the encoder; see the constants in {@link Base64} + */ + public Base64OutputStream(OutputStream out, int flags) { + this(out, flags, true); + } + + /** + * Performs Base64 encoding or decoding on the data written to the stream, writing the + * encoded/decoded data to another OutputStream. + * + * @param out the OutputStream to write the encoded data to + * @param flags bit flags for controlling the encoder; see the constants in {@link Base64} + * @param encode true to encode, false to decode + */ + public Base64OutputStream(OutputStream out, int flags, boolean encode) { + super(out); + this.flags = flags; + if (encode) { + coder = new Base64.Encoder(flags, null); + } else { + coder = new Base64.Decoder(flags, null); + } + } + + @Override + public void write(int b) throws IOException { + // To avoid invoking the encoder/decoder routines for single + // bytes, we buffer up calls to write(int) in an internal + // byte array to transform them into writes of decently-sized + // arrays. + + if (buffer == null) { + buffer = new byte[1024]; + } + if (bpos >= buffer.length) { + // internal buffer full; write it out. + internalWrite(buffer, 0, bpos, false); + bpos = 0; + } + buffer[bpos++] = (byte) b; + } + + /** + * Flush any buffered data from calls to write(int). Needed before doing a write(byte[], int, + * int) or a close(). + */ + private void flushBuffer() throws IOException { + if (bpos > 0) { + internalWrite(buffer, 0, bpos, false); + bpos = 0; + } + } + + @Override + public void write(byte[] b, int off, int len) throws IOException { + if (len <= 0) return; + flushBuffer(); + internalWrite(b, off, len, false); + } + + @Override + public void close() throws IOException { + IOException thrown = null; + try { + flushBuffer(); + internalWrite(EMPTY, 0, 0, true); + } catch (IOException e) { + thrown = e; + } + + try { + if ((flags & Base64.NO_CLOSE) == 0) { + out.close(); + } else { + out.flush(); + } + } catch (IOException e) { + if (thrown != null) { + thrown = e; + } + } + + if (thrown != null) { + throw thrown; + } + } + + /** + * Write the given bytes to the encoder/decoder. + * + * @param finish true if this is the last batch of input, to cause encoder/decoder state to be + * finalized. + */ + private void internalWrite(byte[] b, int off, int len, boolean finish) throws IOException { + coder.output = embiggen(coder.output, coder.maxOutputSize(len)); + if (!coder.process(b, off, len, finish)) { + throw new Base64DataException("bad base-64"); + } + out.write(coder.output, 0, coder.op); + } + + /** + * If b.length is at least len, return b. Otherwise return a new byte array of length len. + */ + private byte[] embiggen(byte[] b, int len) { + if (b == null || b.length < len) { + return new byte[len]; + } else { + return b; + } + } +} \ No newline at end of file diff --git a/library/src/main/java/com/loopj/android/http/BaseJsonHttpResponseHandler.java b/library/src/main/java/com/loopj/android/http/BaseJsonHttpResponseHandler.java new file mode 100755 index 000000000..69349f1d0 --- /dev/null +++ b/library/src/main/java/com/loopj/android/http/BaseJsonHttpResponseHandler.java @@ -0,0 +1,155 @@ +/* + Android Asynchronous Http Client + Copyright (c) 2011 James Smith + https://github.com/android-async-http/android-async-http + + 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 + + https://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.loopj.android.http; + +import cz.msebera.android.httpclient.Header; +import cz.msebera.android.httpclient.HttpStatus; + +/** + * Class meant to be used with custom JSON parser (such as GSON or Jackson JSON)

 

+ * {@link #parseResponse(String, boolean)} should be overriden and must return type of generic param + * class, response will be then handled to implementation of abstract methods {@link #onSuccess(int, + * cz.msebera.android.httpclient.Header[], String, Object)} or {@link #onFailure(int, cz.msebera.android.httpclient.Header[], + * Throwable, String, Object)}, depending of response HTTP status line (result http code) + * + * @param Generic type meant to be returned in callback + */ +public abstract class BaseJsonHttpResponseHandler extends TextHttpResponseHandler { + private static final String LOG_TAG = "BaseJsonHttpRH"; + + /** + * Creates a new JsonHttpResponseHandler with default charset "UTF-8" + */ + public BaseJsonHttpResponseHandler() { + this(DEFAULT_CHARSET); + } + + /** + * Creates a new JsonHttpResponseHandler with given string encoding + * + * @param encoding result string encoding, see Charset + */ + public BaseJsonHttpResponseHandler(String encoding) { + super(encoding); + } + + /** + * Base abstract method, handling defined generic type + * + * @param statusCode HTTP status line + * @param headers response headers + * @param rawJsonResponse string of response, can be null + * @param response response returned by {@link #parseResponse(String, boolean)} + */ + public abstract void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, JSON_TYPE response); + + /** + * Base abstract method, handling defined generic type + * + * @param statusCode HTTP status line + * @param headers response headers + * @param throwable error thrown while processing request + * @param rawJsonData raw string data returned if any + * @param errorResponse response returned by {@link #parseResponse(String, boolean)} + */ + public abstract void onFailure(int statusCode, Header[] headers, Throwable throwable, String rawJsonData, JSON_TYPE errorResponse); + + @Override + public final void onSuccess(final int statusCode, final Header[] headers, final String responseString) { + if (statusCode != HttpStatus.SC_NO_CONTENT) { + Runnable parser = new Runnable() { + @Override + public void run() { + try { + final JSON_TYPE jsonResponse = parseResponse(responseString, false); + postRunnable(new Runnable() { + @Override + public void run() { + onSuccess(statusCode, headers, responseString, jsonResponse); + } + }); + } catch (final Throwable t) { + AsyncHttpClient.log.d(LOG_TAG, "parseResponse thrown an problem", t); + postRunnable(new Runnable() { + @Override + public void run() { + onFailure(statusCode, headers, t, responseString, null); + } + }); + } + } + }; + if (!getUseSynchronousMode() && !getUsePoolThread()) { + new Thread(parser).start(); + } else { + // In synchronous mode everything should be run on one thread + parser.run(); + } + } else { + onSuccess(statusCode, headers, null, null); + } + } + + @Override + public final void onFailure(final int statusCode, final Header[] headers, final String responseString, final Throwable throwable) { + if (responseString != null) { + Runnable parser = new Runnable() { + @Override + public void run() { + try { + final JSON_TYPE jsonResponse = parseResponse(responseString, true); + postRunnable(new Runnable() { + @Override + public void run() { + onFailure(statusCode, headers, throwable, responseString, jsonResponse); + } + }); + } catch (Throwable t) { + AsyncHttpClient.log.d(LOG_TAG, "parseResponse thrown an problem", t); + postRunnable(new Runnable() { + @Override + public void run() { + onFailure(statusCode, headers, throwable, responseString, null); + } + }); + } + } + }; + if (!getUseSynchronousMode() && !getUsePoolThread()) { + new Thread(parser).start(); + } else { + // In synchronous mode everything should be run on one thread + parser.run(); + } + } else { + onFailure(statusCode, headers, throwable, null, null); + } + } + + /** + * Should return deserialized instance of generic type, may return object for more vague + * handling + * + * @param rawJsonData response string, may be null + * @param isFailure indicating if this method is called from onFailure or not + * @return object of generic type or possibly null if you choose so + * @throws Throwable allows you to throw anything from within deserializing JSON response + */ + protected abstract JSON_TYPE parseResponse(String rawJsonData, boolean isFailure) throws Throwable; +} diff --git a/library/src/main/java/com/loopj/android/http/BearerAuthSchemeFactory.java b/library/src/main/java/com/loopj/android/http/BearerAuthSchemeFactory.java new file mode 100644 index 000000000..3d17ea294 --- /dev/null +++ b/library/src/main/java/com/loopj/android/http/BearerAuthSchemeFactory.java @@ -0,0 +1,89 @@ +/* + Android Asynchronous Http Client + Copyright (c) 2011 James Smith + https://github.com/android-async-http/android-async-http + + 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 + + https://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.loopj.android.http; + +import cz.msebera.android.httpclient.Header; +import cz.msebera.android.httpclient.HttpRequest; +import cz.msebera.android.httpclient.auth.AUTH; +import cz.msebera.android.httpclient.auth.AuthScheme; +import cz.msebera.android.httpclient.auth.AuthSchemeFactory; +import cz.msebera.android.httpclient.auth.AuthenticationException; +import cz.msebera.android.httpclient.auth.ContextAwareAuthScheme; +import cz.msebera.android.httpclient.auth.Credentials; +import cz.msebera.android.httpclient.auth.MalformedChallengeException; +import cz.msebera.android.httpclient.message.BufferedHeader; +import cz.msebera.android.httpclient.params.HttpParams; +import cz.msebera.android.httpclient.protocol.HttpContext; +import cz.msebera.android.httpclient.util.CharArrayBuffer; + +public class BearerAuthSchemeFactory implements AuthSchemeFactory { + + @Override + public AuthScheme newInstance(HttpParams params) { + return new BearerAuthScheme(); + } + + public static class BearerAuthScheme implements ContextAwareAuthScheme { + private boolean complete = false; + + @Override + public void processChallenge(Header header) throws MalformedChallengeException { + this.complete = true; + } + + @Override + public Header authenticate(Credentials credentials, HttpRequest request) throws AuthenticationException { + return authenticate(credentials, request, null); + } + + @Override + public Header authenticate(Credentials credentials, HttpRequest request, HttpContext httpContext) + throws AuthenticationException { + CharArrayBuffer buffer = new CharArrayBuffer(32); + buffer.append(AUTH.WWW_AUTH_RESP); + buffer.append(": Bearer "); + buffer.append(credentials.getUserPrincipal().getName()); + return new BufferedHeader(buffer); + } + + @Override + public String getSchemeName() { + return "Bearer"; + } + + @Override + public String getParameter(String name) { + return null; + } + + @Override + public String getRealm() { + return null; + } + + @Override + public boolean isConnectionBased() { + return false; + } + + @Override + public boolean isComplete() { + return this.complete; + } + } +} \ No newline at end of file diff --git a/library/src/main/java/com/loopj/android/http/BinaryHttpResponseHandler.java b/library/src/main/java/com/loopj/android/http/BinaryHttpResponseHandler.java new file mode 100755 index 000000000..2372a94e4 --- /dev/null +++ b/library/src/main/java/com/loopj/android/http/BinaryHttpResponseHandler.java @@ -0,0 +1,160 @@ +/* + Android Asynchronous Http Client + Copyright (c) 2011 James Smith + https://github.com/android-async-http/android-async-http + + 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 + + https://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.loopj.android.http; + +import android.os.Looper; + +import java.io.IOException; +import java.util.regex.Pattern; +import java.util.regex.PatternSyntaxException; + +import cz.msebera.android.httpclient.Header; +import cz.msebera.android.httpclient.HttpResponse; +import cz.msebera.android.httpclient.StatusLine; +import cz.msebera.android.httpclient.client.HttpResponseException; + +/** + * Used to intercept and handle the responses from requests made using {@link AsyncHttpClient}. + * Receives response body as byte array with a content-type whitelist. (e.g. checks Content-Type + * against allowed list, Content-length).

 

For example:

 

+ *
+ * AsyncHttpClient client = new AsyncHttpClient();
+ * String[] allowedTypes = new String[] { "image/png" };
+ * client.get("https://www.example.com/image.png", new BinaryHttpResponseHandler(allowedTypes) {
+ *     @Override
+ *     public void onSuccess(byte[] imageData) {
+ *         // Successfully got a response
+ *     }
+ *
+ *     @Override
+ *     public void onFailure(Throwable e, byte[] imageData) {
+ *         // Response failed :(
+ *     }
+ * });
+ * 
+ */ +public abstract class BinaryHttpResponseHandler extends AsyncHttpResponseHandler { + + private static final String LOG_TAG = "BinaryHttpRH"; + + private String[] mAllowedContentTypes = new String[]{ + RequestParams.APPLICATION_OCTET_STREAM, + "image/jpeg", + "image/png", + "image/gif" + }; + + /** + * Creates a new BinaryHttpResponseHandler + */ + public BinaryHttpResponseHandler() { + super(); + } + + /** + * Creates a new BinaryHttpResponseHandler, and overrides the default allowed content types with + * passed String array (hopefully) of content types. + * + * @param allowedContentTypes content types array, eg. 'image/jpeg' or pattern '.*' + */ + public BinaryHttpResponseHandler(String[] allowedContentTypes) { + super(); + if (allowedContentTypes != null) { + mAllowedContentTypes = allowedContentTypes; + } else { + AsyncHttpClient.log.e(LOG_TAG, "Constructor passed allowedContentTypes was null !"); + } + } + + /** + * Creates a new BinaryHttpResponseHandler with a user-supplied looper, and overrides the default allowed content types with + * passed String array (hopefully) of content types. + * + * @param allowedContentTypes content types array, eg. 'image/jpeg' or pattern '.*' + * @param looper The looper to work with + */ + public BinaryHttpResponseHandler(String[] allowedContentTypes, Looper looper) { + super(looper); + if (allowedContentTypes != null) { + mAllowedContentTypes = allowedContentTypes; + } else { + AsyncHttpClient.log.e(LOG_TAG, "Constructor passed allowedContentTypes was null !"); + } + } + + /** + * Method can be overriden to return allowed content types, can be sometimes better than passing + * data in constructor + * + * @return array of content-types or Pattern string templates (eg. '.*' to match every response) + */ + public String[] getAllowedContentTypes() { + return mAllowedContentTypes; + } + + @Override + public abstract void onSuccess(int statusCode, Header[] headers, byte[] binaryData); + + @Override + public abstract void onFailure(int statusCode, Header[] headers, byte[] binaryData, Throwable error); + + @Override + public final void sendResponseMessage(HttpResponse response) throws IOException { + StatusLine status = response.getStatusLine(); + Header[] contentTypeHeaders = response.getHeaders(AsyncHttpClient.HEADER_CONTENT_TYPE); + if (contentTypeHeaders.length != 1) { + //malformed/ambiguous HTTP Header, ABORT! + sendFailureMessage( + status.getStatusCode(), + response.getAllHeaders(), + null, + new HttpResponseException( + status.getStatusCode(), + "None, or more than one, Content-Type Header found!" + ) + ); + return; + } + Header contentTypeHeader = contentTypeHeaders[0]; + boolean foundAllowedContentType = false; + for (String anAllowedContentType : getAllowedContentTypes()) { + try { + if (Pattern.matches(anAllowedContentType, contentTypeHeader.getValue())) { + foundAllowedContentType = true; + } + } catch (PatternSyntaxException e) { + AsyncHttpClient.log.e(LOG_TAG, "Given pattern is not valid: " + anAllowedContentType, e); + } + } + if (!foundAllowedContentType) { + //Content-Type not in allowed list, ABORT! + sendFailureMessage( + status.getStatusCode(), + response.getAllHeaders(), + null, + new HttpResponseException( + status.getStatusCode(), + "Content-Type (" + contentTypeHeader.getValue() + ") not allowed!" + ) + ); + return; + } + super.sendResponseMessage(response); + } +} diff --git a/library/src/main/java/com/loopj/android/http/BlackholeHttpResponseHandler.java b/library/src/main/java/com/loopj/android/http/BlackholeHttpResponseHandler.java new file mode 100644 index 000000000..a3e7b914e --- /dev/null +++ b/library/src/main/java/com/loopj/android/http/BlackholeHttpResponseHandler.java @@ -0,0 +1,64 @@ +package com.loopj.android.http; + +import cz.msebera.android.httpclient.Header; +import cz.msebera.android.httpclient.HttpResponse; + +/** + * Blank implementation of ResponseHandlerInterface, which ignores all contents returned by + * remote HTTP endpoint, and discards all various log messages + *

 

+ * Use this implementation, if you deliberately want to ignore all response, because you cannot + * pass null ResponseHandlerInterface into AsyncHttpClient implementation + */ +public class BlackholeHttpResponseHandler extends AsyncHttpResponseHandler { + + @Override + public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { + + } + + @Override + public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { + + } + + @Override + public void onProgress(long bytesWritten, long totalSize) { + + } + + @Override + public void onCancel() { + + } + + @Override + public void onFinish() { + + } + + @Override + public void onPostProcessResponse(ResponseHandlerInterface instance, HttpResponse response) { + + } + + @Override + public void onPreProcessResponse(ResponseHandlerInterface instance, HttpResponse response) { + + } + + @Override + public void onRetry(int retryNo) { + + } + + @Override + public void onStart() { + + } + + @Override + public void onUserException(Throwable error) { + + } +} diff --git a/library/src/main/java/com/loopj/android/http/ConscryptSSLProvider.java b/library/src/main/java/com/loopj/android/http/ConscryptSSLProvider.java new file mode 100644 index 000000000..67ee69060 --- /dev/null +++ b/library/src/main/java/com/loopj/android/http/ConscryptSSLProvider.java @@ -0,0 +1,18 @@ +package com.loopj.android.http; + +import android.util.Log; + +import org.conscrypt.Conscrypt; + +import java.security.Security; + +public class ConscryptSSLProvider { + public static void install(){ + try { + Security.insertProviderAt(Conscrypt.newProviderBuilder().build(),1); + }catch (NoClassDefFoundError ex){ + Log.e(AsyncHttpClient.LOG_TAG, "java.lang.NoClassDefFoundError: org.conscrypt.Conscrypt, Please add org.conscrypt.Conscrypt to your dependency"); + } + + } +} diff --git a/library/src/main/java/com/loopj/android/http/DataAsyncHttpResponseHandler.java b/library/src/main/java/com/loopj/android/http/DataAsyncHttpResponseHandler.java new file mode 100755 index 000000000..a8d43a189 --- /dev/null +++ b/library/src/main/java/com/loopj/android/http/DataAsyncHttpResponseHandler.java @@ -0,0 +1,151 @@ +/* + Android Asynchronous Http Client + Copyright (c) 2011 James Smith + https://github.com/android-async-http/android-async-http + + 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 + + https://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.loopj.android.http; + +import android.os.Message; + +import java.io.IOException; +import java.io.InputStream; + +import cz.msebera.android.httpclient.HttpEntity; +import cz.msebera.android.httpclient.util.ByteArrayBuffer; + +@SuppressWarnings("ALL") +public abstract class DataAsyncHttpResponseHandler extends AsyncHttpResponseHandler { + protected static final int PROGRESS_DATA_MESSAGE = 7; + private static final String LOG_TAG = "DataAsyncHttpRH"; + + /** + * Creates a new AsyncHttpResponseHandler + */ + public DataAsyncHttpResponseHandler() { + super(); + } + + /** + * Copies elements from {@code original} into a new array, from indexes start (inclusive) to end + * (exclusive). The original order of elements is preserved. If {@code end} is greater than + * {@code original.length}, the result is padded with the value {@code (byte) 0}. + * + * @param original the original array + * @param start the start index, inclusive + * @param end the end index, exclusive + * @return the new array + * @throws ArrayIndexOutOfBoundsException if {@code start < 0 || start > original.length} + * @throws IllegalArgumentException if {@code start > end} + * @throws NullPointerException if {@code original == null} + * @see java.util.Arrays + * @since 1.6 + */ + public static byte[] copyOfRange(byte[] original, int start, int end) throws ArrayIndexOutOfBoundsException, IllegalArgumentException, NullPointerException { + if (start > end) { + throw new IllegalArgumentException(); + } + int originalLength = original.length; + if (start < 0 || start > originalLength) { + throw new ArrayIndexOutOfBoundsException(); + } + int resultLength = end - start; + int copyLength = Math.min(resultLength, originalLength - start); + byte[] result = new byte[resultLength]; + System.arraycopy(original, start, result, 0, copyLength); + return result; + } + + /** + * Fired when the request progress, override to handle in your own code + * + * @param responseBody response body received so far + */ + public void onProgressData(byte[] responseBody) { + AsyncHttpClient.log.d(LOG_TAG, "onProgressData(byte[]) was not overriden, but callback was received"); + } + + final public void sendProgressDataMessage(byte[] responseBytes) { + sendMessage(obtainMessage(PROGRESS_DATA_MESSAGE, new Object[]{responseBytes})); + } + + // Methods which emulate android's Handler and Message methods + @Override + protected void handleMessage(Message message) { + super.handleMessage(message); + Object[] response; + + switch (message.what) { + case PROGRESS_DATA_MESSAGE: + response = (Object[]) message.obj; + if (response != null && response.length >= 1) { + try { + onProgressData((byte[]) response[0]); + } catch (Throwable t) { + AsyncHttpClient.log.e(LOG_TAG, "custom onProgressData contains an error", t); + } + } else { + AsyncHttpClient.log.e(LOG_TAG, "PROGRESS_DATA_MESSAGE didn't got enough params"); + } + break; + } + } + + /** + * Returns byte array of response HttpEntity contents + * + * @param entity can be null + * @return response entity body or null + * @throws java.io.IOException if reading entity or creating byte array failed + */ + @Override + byte[] getResponseData(HttpEntity entity) throws IOException { + + byte[] responseBody = null; + if (entity != null) { + InputStream instream = entity.getContent(); + if (instream != null) { + long contentLength = entity.getContentLength(); + if (contentLength > Integer.MAX_VALUE) { + throw new IllegalArgumentException("HTTP entity too large to be buffered in memory"); + } + if (contentLength < 0) { + contentLength = BUFFER_SIZE; + } + try { + ByteArrayBuffer buffer = new ByteArrayBuffer((int) contentLength); + try { + byte[] tmp = new byte[BUFFER_SIZE]; + int l, count = 0; + // do not send messages if request has been cancelled + while ((l = instream.read(tmp)) != -1 && !Thread.currentThread().isInterrupted()) { + buffer.append(tmp, 0, l); + sendProgressDataMessage(copyOfRange(tmp, 0, l)); + sendProgressMessage(count, contentLength); + } + } finally { + AsyncHttpClient.silentCloseInputStream(instream); + } + responseBody = buffer.toByteArray(); + } catch (OutOfMemoryError e) { + System.gc(); + throw new IOException("File too large to fit into available memory"); + } + } + } + return responseBody; + } +} + diff --git a/library/src/main/java/com/loopj/android/http/FileAsyncHttpResponseHandler.java b/library/src/main/java/com/loopj/android/http/FileAsyncHttpResponseHandler.java new file mode 100755 index 000000000..ee0d5b2c5 --- /dev/null +++ b/library/src/main/java/com/loopj/android/http/FileAsyncHttpResponseHandler.java @@ -0,0 +1,241 @@ +/* + Android Asynchronous Http Client + Copyright (c) 2011 James Smith + https://github.com/android-async-http/android-async-http + + 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 + + https://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.loopj.android.http; + +import android.content.Context; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; + +import cz.msebera.android.httpclient.Header; +import cz.msebera.android.httpclient.HttpEntity; + +public abstract class FileAsyncHttpResponseHandler extends AsyncHttpResponseHandler { + + private static final String LOG_TAG = "FileAsyncHttpRH"; + protected final File file; + protected final boolean append; + protected final boolean renameIfExists; + protected File frontendFile; + + /** + * Obtains new FileAsyncHttpResponseHandler and stores response in passed file + * + * @param file File to store response within, must not be null + */ + public FileAsyncHttpResponseHandler(File file) { + this(file, false); + } + + /** + * Obtains new FileAsyncHttpResponseHandler and stores response in passed file + * + * @param file File to store response within, must not be null + * @param append whether data should be appended to existing file + */ + public FileAsyncHttpResponseHandler(File file, boolean append) { + this(file, append, false); + } + + /** + * Obtains new FileAsyncHttpResponseHandler and stores response in passed file + * + * @param file File to store response within, must not be null + * @param append whether data should be appended to existing file + * @param renameTargetFileIfExists whether target file should be renamed if it already exists + */ + public FileAsyncHttpResponseHandler(File file, boolean append, boolean renameTargetFileIfExists) { + this(file,append,renameTargetFileIfExists,false); + } + + + /** + * Obtains new FileAsyncHttpResponseHandler and stores response in passed file + * + * @param file File to store response within, must not be null + * @param append whether data should be appended to existing file + * @param renameTargetFileIfExists whether target file should be renamed if it already exists + * @param usePoolThread Whether to use the pool's thread to fire callbacks + */ + public FileAsyncHttpResponseHandler(File file, boolean append, boolean renameTargetFileIfExists,boolean usePoolThread) { + super(usePoolThread); + Utils.asserts(file != null, "File passed into FileAsyncHttpResponseHandler constructor must not be null"); + if (!file.isDirectory() && !file.getParentFile().isDirectory()) { + Utils.asserts(file.getParentFile().mkdirs(), "Cannot create parent directories for requested File location"); + } + if (file.isDirectory()) { + if (!file.mkdirs()) { + AsyncHttpClient.log.d(LOG_TAG, "Cannot create directories for requested Directory location, might not be a problem"); + } + } + this.file = file; + this.append = append; + this.renameIfExists = renameTargetFileIfExists; + } + + /** + * Obtains new FileAsyncHttpResponseHandler against context with target being temporary file + * + * @param context Context, must not be null + */ + public FileAsyncHttpResponseHandler(Context context) { + super(); + this.file = getTemporaryFile(context); + this.append = false; + this.renameIfExists = false; + } + + /** + * Attempts to delete file with stored response + * + * @return false if the file does not exist or is null, true if it was successfully deleted + */ + public boolean deleteTargetFile() { + return getTargetFile() != null && getTargetFile().delete(); + } + + /** + * Used when there is no file to be used when calling constructor + * + * @param context Context, must not be null + * @return temporary file or null if creating file failed + */ + protected File getTemporaryFile(Context context) { + Utils.asserts(context != null, "Tried creating temporary file without having Context"); + try { + return File.createTempFile("temp_", "_handled", context.getCacheDir()); + } catch (IOException e) { + AsyncHttpClient.log.e(LOG_TAG, "Cannot create temporary file", e); + } + return null; + } + + /** + * Retrieves File object in which the response is stored + * + * @return File file in which the response was to be stored + */ + protected File getOriginalFile() { + Utils.asserts(file != null, "Target file is null, fatal!"); + return file; + } + + /** + * Retrieves File which represents response final location after possible renaming + * + * @return File final target file + */ + public File getTargetFile() { + if (frontendFile == null) { + frontendFile = getOriginalFile().isDirectory() ? getTargetFileByParsingURL() : getOriginalFile(); + } + return frontendFile; + } + + /** + * Will return File instance for file representing last URL segment in given folder. + * If file already exists and renameTargetFileIfExists was set as true, will try to find file + * which doesn't exist, naming template for such cases is "filename.ext" => "filename (%d).ext", + * or without extension "filename" => "filename (%d)" + * + * @return File in given directory constructed by last segment of request URL + */ + protected File getTargetFileByParsingURL() { + Utils.asserts(getOriginalFile().isDirectory(), "Target file is not a directory, cannot proceed"); + Utils.asserts(getRequestURI() != null, "RequestURI is null, cannot proceed"); + String requestURL = getRequestURI().toString(); + String filename = requestURL.substring(requestURL.lastIndexOf('/') + 1, requestURL.length()); + File targetFileRtn = new File(getOriginalFile(), filename); + if (targetFileRtn.exists() && renameIfExists) { + String format; + if (!filename.contains(".")) { + format = filename + " (%d)"; + } else { + format = filename.substring(0, filename.lastIndexOf('.')) + " (%d)" + filename.substring(filename.lastIndexOf('.'), filename.length()); + } + int index = 0; + while (true) { + targetFileRtn = new File(getOriginalFile(), String.format(format, index)); + if (!targetFileRtn.exists()) + return targetFileRtn; + index++; + } + } + return targetFileRtn; + } + + @Override + public final void onFailure(int statusCode, Header[] headers, byte[] responseBytes, Throwable throwable) { + onFailure(statusCode, headers, throwable, getTargetFile()); + } + + /** + * Method to be overriden, receives as much of file as possible Called when the file is + * considered failure or if there is error when retrieving file + * + * @param statusCode http file status line + * @param headers file http headers if any + * @param throwable returned throwable + * @param file file in which the file is stored + */ + public abstract void onFailure(int statusCode, Header[] headers, Throwable throwable, File file); + + @Override + public final void onSuccess(int statusCode, Header[] headers, byte[] responseBytes) { + onSuccess(statusCode, headers, getTargetFile()); + } + + /** + * Method to be overriden, receives as much of response as possible + * + * @param statusCode http response status line + * @param headers response http headers if any + * @param file file in which the response is stored + */ + public abstract void onSuccess(int statusCode, Header[] headers, File file); + + @Override + protected byte[] getResponseData(HttpEntity entity) throws IOException { + if (entity != null) { + InputStream instream = entity.getContent(); + long contentLength = entity.getContentLength(); + FileOutputStream buffer = new FileOutputStream(getTargetFile(), this.append); + if (instream != null) { + try { + byte[] tmp = new byte[BUFFER_SIZE]; + int l, count = 0; + // do not send messages if request has been cancelled + while ((l = instream.read(tmp)) != -1 && !Thread.currentThread().isInterrupted()) { + count += l; + buffer.write(tmp, 0, l); + sendProgressMessage(count, contentLength); + } + } finally { + AsyncHttpClient.silentCloseInputStream(instream); + buffer.flush(); + AsyncHttpClient.silentCloseOutputStream(buffer); + } + } + } + return null; + } + +} diff --git a/library/src/main/java/com/loopj/android/http/HttpDelete.java b/library/src/main/java/com/loopj/android/http/HttpDelete.java new file mode 100644 index 000000000..5a426a76b --- /dev/null +++ b/library/src/main/java/com/loopj/android/http/HttpDelete.java @@ -0,0 +1,59 @@ +/* + Android Asynchronous Http Client + Copyright (c) 2011 James Smith + https://github.com/android-async-http/android-async-http + + 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 + + https://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.loopj.android.http; + +import java.net.URI; + +import cz.msebera.android.httpclient.client.methods.HttpEntityEnclosingRequestBase; + +/** + * The current Android (API level 21) bundled version of the Apache Http Client does not implement + * a HttpEntityEnclosingRequestBase type of HTTP DELETE method. + * Until the Android version is updated this can serve in it's stead. + * This implementation can and should go away when the official solution arrives. + */ +public final class HttpDelete extends HttpEntityEnclosingRequestBase { + public final static String METHOD_NAME = "DELETE"; + + public HttpDelete() { + super(); + } + + /** + * @param uri target url as URI + */ + public HttpDelete(final URI uri) { + super(); + setURI(uri); + } + + /** + * @param uri target url as String + * @throws IllegalArgumentException if the uri is invalid. + */ + public HttpDelete(final String uri) { + super(); + setURI(URI.create(uri)); + } + + @Override + public String getMethod() { + return METHOD_NAME; + } +} diff --git a/library/src/main/java/com/loopj/android/http/HttpGet.java b/library/src/main/java/com/loopj/android/http/HttpGet.java new file mode 100644 index 000000000..7fd882a52 --- /dev/null +++ b/library/src/main/java/com/loopj/android/http/HttpGet.java @@ -0,0 +1,60 @@ +/* + Android Asynchronous Http Client + Copyright (c) 2011 James Smith + https://github.com/android-async-http/android-async-http + + 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 + + https://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.loopj.android.http; + +import java.net.URI; + +import cz.msebera.android.httpclient.client.methods.HttpEntityEnclosingRequestBase; + +/** + * The current Android (API level 21) bundled version of the Apache Http Client does not implement + * a HttpEntityEnclosingRequestBase type of HTTP GET method. + * Until the Android version is updated this can serve in it's stead. + * This implementation can and should go away when the official solution arrives. + */ +public final class HttpGet extends HttpEntityEnclosingRequestBase { + + public final static String METHOD_NAME = "GET"; + + public HttpGet() { + super(); + } + + /** + * @param uri target url as URI + */ + public HttpGet(final URI uri) { + super(); + setURI(uri); + } + + /** + * @param uri target url as String + * @throws IllegalArgumentException if the uri is invalid. + */ + public HttpGet(final String uri) { + super(); + setURI(URI.create(uri)); + } + + @Override + public String getMethod() { + return METHOD_NAME; + } +} diff --git a/library/src/main/java/com/loopj/android/http/JsonHttpResponseHandler.java b/library/src/main/java/com/loopj/android/http/JsonHttpResponseHandler.java new file mode 100755 index 000000000..28af16d28 --- /dev/null +++ b/library/src/main/java/com/loopj/android/http/JsonHttpResponseHandler.java @@ -0,0 +1,285 @@ +/* + Android Asynchronous Http Client + Copyright (c) 2011 James Smith + https://github.com/android-async-http/android-async-http + + 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 + + https://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.loopj.android.http; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.json.JSONTokener; + +import cz.msebera.android.httpclient.Header; +import cz.msebera.android.httpclient.HttpStatus; + +/** + * Used to intercept and handle the responses from requests made using {@link AsyncHttpClient}, with + * automatic parsing into a {@link JSONObject} or {@link JSONArray}.

 

This class is + * designed to be passed to get, post, put and delete requests with the {@link #onSuccess(int, + * cz.msebera.android.httpclient.Header[], org.json.JSONArray)} or {@link #onSuccess(int, + * cz.msebera.android.httpclient.Header[], org.json.JSONObject)} methods anonymously overridden.

 

+ * Additionally, you can override the other event methods from the parent class. + */ +public class JsonHttpResponseHandler extends TextHttpResponseHandler { + + private static final String LOG_TAG = "JsonHttpRH"; + + + private boolean useRFC5179CompatibilityMode = true; + + /** + * Creates new JsonHttpResponseHandler, with JSON String encoding UTF-8 + */ + public JsonHttpResponseHandler() { + super(DEFAULT_CHARSET); + } + + /** + * Creates new JsonHttpResponseHandler with given JSON String encoding + * + * @param encoding String encoding to be used when parsing JSON + */ + public JsonHttpResponseHandler(String encoding) { + super(encoding); + } + + /** + * Creates new JsonHttpResponseHandler with JSON String encoding UTF-8 and given RFC5179CompatibilityMode + * + * @param useRFC5179CompatibilityMode Boolean mode to use RFC5179 or latest + */ + public JsonHttpResponseHandler(boolean useRFC5179CompatibilityMode) { + super(DEFAULT_CHARSET); + this.useRFC5179CompatibilityMode = useRFC5179CompatibilityMode; + } + + /** + * Creates new JsonHttpResponseHandler with given JSON String encoding and RFC5179CompatibilityMode + * + * @param encoding String encoding to be used when parsing JSON + * @param useRFC5179CompatibilityMode Boolean mode to use RFC5179 or latest + */ + public JsonHttpResponseHandler(String encoding, boolean useRFC5179CompatibilityMode) { + super(encoding); + this.useRFC5179CompatibilityMode = useRFC5179CompatibilityMode; + } + + /** + * Returns when request succeeds + * + * @param statusCode http response status line + * @param headers response headers if any + * @param response parsed response if any + */ + public void onSuccess(int statusCode, Header[] headers, JSONObject response) { + AsyncHttpClient.log.w(LOG_TAG, "onSuccess(int, Header[], JSONObject) was not overriden, but callback was received"); + } + + /** + * Returns when request succeeds + * + * @param statusCode http response status line + * @param headers response headers if any + * @param response parsed response if any + */ + public void onSuccess(int statusCode, Header[] headers, JSONArray response) { + AsyncHttpClient.log.w(LOG_TAG, "onSuccess(int, Header[], JSONArray) was not overriden, but callback was received"); + } + + /** + * Returns when request failed + * + * @param statusCode http response status line + * @param headers response headers if any + * @param throwable throwable describing the way request failed + * @param errorResponse parsed response if any + */ + public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) { + AsyncHttpClient.log.w(LOG_TAG, "onFailure(int, Header[], Throwable, JSONObject) was not overriden, but callback was received", throwable); + } + + /** + * Returns when request failed + * + * @param statusCode http response status line + * @param headers response headers if any + * @param throwable throwable describing the way request failed + * @param errorResponse parsed response if any + */ + public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) { + AsyncHttpClient.log.w(LOG_TAG, "onFailure(int, Header[], Throwable, JSONArray) was not overriden, but callback was received", throwable); + } + + @Override + public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) { + AsyncHttpClient.log.w(LOG_TAG, "onFailure(int, Header[], String, Throwable) was not overriden, but callback was received", throwable); + } + + @Override + public void onSuccess(int statusCode, Header[] headers, String responseString) { + AsyncHttpClient.log.w(LOG_TAG, "onSuccess(int, Header[], String) was not overriden, but callback was received"); + } + + @Override + public final void onSuccess(final int statusCode, final Header[] headers, final byte[] responseBytes) { + if (statusCode != HttpStatus.SC_NO_CONTENT) { + Runnable parser = new Runnable() { + @Override + public void run() { + try { + final Object jsonResponse = parseResponse(responseBytes); + postRunnable(new Runnable() { + @Override + public void run() { + // In RFC5179 a null value is not a valid JSON + if (!useRFC5179CompatibilityMode && jsonResponse == null) { + onSuccess(statusCode, headers, (String) null); + } else if (jsonResponse instanceof JSONObject) { + onSuccess(statusCode, headers, (JSONObject) jsonResponse); + } else if (jsonResponse instanceof JSONArray) { + onSuccess(statusCode, headers, (JSONArray) jsonResponse); + } else if (jsonResponse instanceof String) { + // In RFC5179 a simple string value is not a valid JSON + if (useRFC5179CompatibilityMode) { + onFailure(statusCode, headers, (String) jsonResponse, new JSONException("Response cannot be parsed as JSON data")); + } else { + onSuccess(statusCode, headers, (String) jsonResponse); + } + } else { + onFailure(statusCode, headers, new JSONException("Unexpected response type " + jsonResponse.getClass().getName()), (JSONObject) null); + } + } + }); + } catch (final JSONException ex) { + postRunnable(new Runnable() { + @Override + public void run() { + onFailure(statusCode, headers, ex, (JSONObject) null); + } + }); + } + } + }; + if (!getUseSynchronousMode() && !getUsePoolThread()) { + new Thread(parser).start(); + } else { + // In synchronous mode everything should be run on one thread + parser.run(); + } + } else { + onSuccess(statusCode, headers, new JSONObject()); + } + } + + @Override + public final void onFailure(final int statusCode, final Header[] headers, final byte[] responseBytes, final Throwable throwable) { + if (responseBytes != null) { + Runnable parser = new Runnable() { + @Override + public void run() { + try { + final Object jsonResponse = parseResponse(responseBytes); + postRunnable(new Runnable() { + @Override + public void run() { + // In RFC5179 a null value is not a valid JSON + if (!useRFC5179CompatibilityMode && jsonResponse == null) { + onFailure(statusCode, headers, (String) null, throwable); + } else if (jsonResponse instanceof JSONObject) { + onFailure(statusCode, headers, throwable, (JSONObject) jsonResponse); + } else if (jsonResponse instanceof JSONArray) { + onFailure(statusCode, headers, throwable, (JSONArray) jsonResponse); + } else if (jsonResponse instanceof String) { + onFailure(statusCode, headers, (String) jsonResponse, throwable); + } else { + onFailure(statusCode, headers, new JSONException("Unexpected response type " + jsonResponse.getClass().getName()), (JSONObject) null); + } + } + }); + + } catch (final JSONException ex) { + postRunnable(new Runnable() { + @Override + public void run() { + onFailure(statusCode, headers, ex, (JSONObject) null); + } + }); + + } + } + }; + if (!getUseSynchronousMode() && !getUsePoolThread()) { + new Thread(parser).start(); + } else { + // In synchronous mode everything should be run on one thread + parser.run(); + } + } else { + AsyncHttpClient.log.v(LOG_TAG, "response body is null, calling onFailure(Throwable, JSONObject)"); + onFailure(statusCode, headers, throwable, (JSONObject) null); + } + } + + /** + * Returns Object of type {@link JSONObject}, {@link JSONArray}, String, Boolean, Integer, Long, + * Double or {@link JSONObject#NULL}, see {@link org.json.JSONTokener#nextValue()} + * + * @param responseBody response bytes to be assembled in String and parsed as JSON + * @return Object parsedResponse + * @throws org.json.JSONException exception if thrown while parsing JSON + */ + protected Object parseResponse(byte[] responseBody) throws JSONException { + if (null == responseBody) + return null; + Object result = null; + //trim the string to prevent start with blank, and test if the string is valid JSON, because the parser don't do this :(. If JSON is not valid this will return null + String jsonString = getResponseString(responseBody, getCharset()); + if (jsonString != null) { + jsonString = jsonString.trim(); + if (useRFC5179CompatibilityMode) { + if (jsonString.startsWith("{") || jsonString.startsWith("[")) { + result = new JSONTokener(jsonString).nextValue(); + } + } else { + // Check if the string is an JSONObject style {} or JSONArray style [] + // If not we consider this as a string + if ((jsonString.startsWith("{") && jsonString.endsWith("}")) + || jsonString.startsWith("[") && jsonString.endsWith("]")) { + result = new JSONTokener(jsonString).nextValue(); + } + // Check if this is a String "my String value" and remove quote + // Other value type (numerical, boolean) should be without quote + else if (jsonString.startsWith("\"") && jsonString.endsWith("\"")) { + result = jsonString.substring(1, jsonString.length() - 1); + } + } + } + if (result == null) { + result = jsonString; + } + return result; + } + + public boolean isUseRFC5179CompatibilityMode() { + return useRFC5179CompatibilityMode; + } + + public void setUseRFC5179CompatibilityMode(boolean useRFC5179CompatibilityMode) { + this.useRFC5179CompatibilityMode = useRFC5179CompatibilityMode; + } + +} diff --git a/library/src/main/java/com/loopj/android/http/JsonStreamerEntity.java b/library/src/main/java/com/loopj/android/http/JsonStreamerEntity.java new file mode 100755 index 000000000..6fbee5040 --- /dev/null +++ b/library/src/main/java/com/loopj/android/http/JsonStreamerEntity.java @@ -0,0 +1,391 @@ +/* + Android Asynchronous Http Client + Copyright (c) 2011 James Smith + https://github.com/android-async-http/android-async-http + + 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 + + https://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.loopj.android.http; + +import android.text.TextUtils; + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.zip.GZIPOutputStream; + +import cz.msebera.android.httpclient.Header; +import cz.msebera.android.httpclient.HttpEntity; +import cz.msebera.android.httpclient.message.BasicHeader; + +/** + * HTTP entity to upload JSON data using streams. This has very low memory footprint; suitable for + * uploading large files using base64 encoding. + */ +public class JsonStreamerEntity implements HttpEntity { + + private static final String LOG_TAG = "JsonStreamerEntity"; + + private static final UnsupportedOperationException ERR_UNSUPPORTED = + new UnsupportedOperationException("Unsupported operation in this implementation."); + + // Size of the byte-array buffer used in I/O streams. + private static final int BUFFER_SIZE = 4096; + private static final byte[] JSON_TRUE = "true".getBytes(); + private static final byte[] JSON_FALSE = "false".getBytes(); + private static final byte[] JSON_NULL = "null".getBytes(); + private static final byte[] STREAM_NAME = escape("name"); + private static final byte[] STREAM_TYPE = escape("type"); + private static final byte[] STREAM_CONTENTS = escape("contents"); + private static final Header HEADER_JSON_CONTENT = + new BasicHeader( + AsyncHttpClient.HEADER_CONTENT_TYPE, + RequestParams.APPLICATION_JSON); + private static final Header HEADER_GZIP_ENCODING = + new BasicHeader( + AsyncHttpClient.HEADER_CONTENT_ENCODING, + AsyncHttpClient.ENCODING_GZIP); + // Buffer used for reading from input streams. + private final byte[] buffer = new byte[BUFFER_SIZE]; + // JSON data and associated meta-data to be uploaded. + private final Map jsonParams = new HashMap(); + + // Whether to use gzip compression while uploading + private final Header contentEncoding; + + private final byte[] elapsedField; + + private final ResponseHandlerInterface progressHandler; + + public JsonStreamerEntity(ResponseHandlerInterface progressHandler, boolean useGZipCompression, String elapsedField) { + this.progressHandler = progressHandler; + this.contentEncoding = useGZipCompression ? HEADER_GZIP_ENCODING : null; + this.elapsedField = TextUtils.isEmpty(elapsedField) + ? null + : escape(elapsedField); + } + + // Curtosy of Simple-JSON: https://goo.gl/XoW8RF + // Changed a bit to suit our needs in this class. + static byte[] escape(String string) { + // If it's null, just return prematurely. + if (string == null) { + return JSON_NULL; + } + + // Create a string builder to generate the escaped string. + StringBuilder sb = new StringBuilder(128); + + // Surround with quotations. + sb.append('"'); + + int length = string.length(), pos = -1; + while (++pos < length) { + char ch = string.charAt(pos); + switch (ch) { + case '"': + sb.append("\\\""); + break; + case '\\': + sb.append("\\\\"); + break; + case '\b': + sb.append("\\b"); + break; + case '\f': + sb.append("\\f"); + break; + case '\n': + sb.append("\\n"); + break; + case '\r': + sb.append("\\r"); + break; + case '\t': + sb.append("\\t"); + break; + default: + // Reference: https://www.unicode.org/versions/Unicode5.1.0/ + if ((ch <= '\u001F') || (ch >= '\u007F' && ch <= '\u009F') || (ch >= '\u2000' && ch <= '\u20FF')) { + String intString = Integer.toHexString(ch); + sb.append("\\u"); + int intLength = 4 - intString.length(); + for (int zero = 0; zero < intLength; zero++) { + sb.append('0'); + } + sb.append(intString.toUpperCase(Locale.US)); + } else { + sb.append(ch); + } + break; + } + } + + // Surround with quotations. + sb.append('"'); + + return sb.toString().getBytes(); + } + + /** + * Add content parameter, identified by the given key, to the request. + * + * @param key entity's name + * @param value entity's value (Scalar, FileWrapper, StreamWrapper) + */ + public void addPart(String key, Object value) { + jsonParams.put(key, value); + } + + @Override + public boolean isRepeatable() { + return false; + } + + @Override + public boolean isChunked() { + return false; + } + + @Override + public boolean isStreaming() { + return false; + } + + @Override + public long getContentLength() { + return -1; + } + + @Override + public Header getContentEncoding() { + return contentEncoding; + } + + @Override + public Header getContentType() { + return HEADER_JSON_CONTENT; + } + + @Override + public void consumeContent() throws IOException, UnsupportedOperationException { + } + + @Override + public InputStream getContent() throws IOException, UnsupportedOperationException { + throw ERR_UNSUPPORTED; + } + + @Override + public void writeTo(final OutputStream out) throws IOException { + if (out == null) { + throw new IllegalStateException("Output stream cannot be null."); + } + + // Record the time when uploading started. + long now = System.currentTimeMillis(); + + // Use GZIP compression when sending streams, otherwise just use + // a buffered output stream to speed things up a bit. + OutputStream os = contentEncoding != null + ? new GZIPOutputStream(out, BUFFER_SIZE) + : out; + + // Always send a JSON object. + os.write('{'); + + // Keys used by the HashMaps. + Set keys = jsonParams.keySet(); + + int keysCount = keys.size(); + if (0 < keysCount) { + int keysProcessed = 0; + boolean isFileWrapper; + + // Go over all keys and handle each's value. + for (String key : keys) { + // Indicate that this key has been processed. + keysProcessed++; + + try { + // Evaluate the value (which cannot be null). + Object value = jsonParams.get(key); + + // Write the JSON object's key. + os.write(escape(key)); + os.write(':'); + + // Bail out prematurely if value's null. + if (value == null) { + os.write(JSON_NULL); + } else { + // Check if this is a FileWrapper. + isFileWrapper = value instanceof RequestParams.FileWrapper; + + // If a file should be uploaded. + if (isFileWrapper || value instanceof RequestParams.StreamWrapper) { + // All uploads are sent as an object containing the file's details. + os.write('{'); + + // Determine how to handle this entry. + if (isFileWrapper) { + writeToFromFile(os, (RequestParams.FileWrapper) value); + } else { + writeToFromStream(os, (RequestParams.StreamWrapper) value); + } + + // End the file's object and prepare for next one. + os.write('}'); + } else if (value instanceof JsonValueInterface) { + os.write(((JsonValueInterface) value).getEscapedJsonValue()); + } else if (value instanceof org.json.JSONObject) { + os.write(value.toString().getBytes()); + } else if (value instanceof org.json.JSONArray) { + os.write(value.toString().getBytes()); + } else if (value instanceof Boolean) { + os.write((Boolean) value ? JSON_TRUE : JSON_FALSE); + } else if (value instanceof Long) { + os.write((((Number) value).longValue() + "").getBytes()); + } else if (value instanceof Double) { + os.write((((Number) value).doubleValue() + "").getBytes()); + } else if (value instanceof Float) { + os.write((((Number) value).floatValue() + "").getBytes()); + } else if (value instanceof Integer) { + os.write((((Number) value).intValue() + "").getBytes()); + } else { + os.write(escape(value.toString())); + } + } + } finally { + // Separate each K:V with a comma, except the last one. + if (elapsedField != null || keysProcessed < keysCount) { + os.write(','); + } + } + } + + // Calculate how many milliseconds it took to upload the contents. + long elapsedTime = System.currentTimeMillis() - now; + + // Include the elapsed time taken to upload everything. + // This might be useful for somebody, but it serves us well since + // there will almost always be a ',' as the last sent character. + if (elapsedField != null) { + os.write(elapsedField); + os.write(':'); + os.write((elapsedTime + "").getBytes()); + } + + AsyncHttpClient.log.i(LOG_TAG, "Uploaded JSON in " + Math.floor(elapsedTime / 1000) + " seconds"); + } + + // Close the JSON object. + os.write('}'); + + // Flush the contents up the stream. + os.flush(); + AsyncHttpClient.silentCloseOutputStream(os); + } + + private void writeToFromStream(OutputStream os, RequestParams.StreamWrapper entry) + throws IOException { + + // Send the meta data. + writeMetaData(os, entry.name, entry.contentType); + + int bytesRead; + + // Upload the file's contents in Base64. + Base64OutputStream bos = + new Base64OutputStream(os, Base64.NO_CLOSE | Base64.NO_WRAP); + + // Read from input stream until no more data's left to read. + while ((bytesRead = entry.inputStream.read(buffer)) != -1) { + bos.write(buffer, 0, bytesRead); + } + + // Close the Base64 output stream. + AsyncHttpClient.silentCloseOutputStream(bos); + + // End the meta data. + endMetaData(os); + + // Close input stream. + if (entry.autoClose) { + // Safely close the input stream. + AsyncHttpClient.silentCloseInputStream(entry.inputStream); + } + } + + private void writeToFromFile(OutputStream os, RequestParams.FileWrapper wrapper) + throws IOException { + + // Send the meta data. + writeMetaData(os, wrapper.file.getName(), wrapper.contentType); + + int bytesRead; + long bytesWritten = 0, totalSize = wrapper.file.length(); + + // Open the file for reading. + FileInputStream in = new FileInputStream(wrapper.file); + + // Upload the file's contents in Base64. + Base64OutputStream bos = + new Base64OutputStream(os, Base64.NO_CLOSE | Base64.NO_WRAP); + + // Read from file until no more data's left to read. + while ((bytesRead = in.read(buffer)) != -1) { + bos.write(buffer, 0, bytesRead); + bytesWritten += bytesRead; + progressHandler.sendProgressMessage(bytesWritten, totalSize); + } + + // Close the Base64 output stream. + AsyncHttpClient.silentCloseOutputStream(bos); + + // End the meta data. + endMetaData(os); + + // Safely close the input stream. + AsyncHttpClient.silentCloseInputStream(in); + } + + private void writeMetaData(OutputStream os, String name, String contentType) throws IOException { + // Send the streams's name. + os.write(STREAM_NAME); + os.write(':'); + os.write(escape(name)); + os.write(','); + + // Send the streams's content type. + os.write(STREAM_TYPE); + os.write(':'); + os.write(escape(contentType)); + os.write(','); + + // Prepare the file content's key. + os.write(STREAM_CONTENTS); + os.write(':'); + os.write('"'); + } + + private void endMetaData(OutputStream os) throws IOException { + os.write('"'); + } +} diff --git a/library/src/main/java/com/loopj/android/http/JsonValueInterface.java b/library/src/main/java/com/loopj/android/http/JsonValueInterface.java new file mode 100644 index 000000000..303d96b22 --- /dev/null +++ b/library/src/main/java/com/loopj/android/http/JsonValueInterface.java @@ -0,0 +1,37 @@ +/* + Android Asynchronous Http Client + Copyright (c) 2011 James Smith + https://github.com/android-async-http/android-async-http + + 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 + + https://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.loopj.android.http; + +/** + * This interface is used to encapsulate JSON values that are handled entirely + * by the app. For example, apps could manage any type of JSON on their own (and + * not rely on {@link org.json.JSONArray} or {@link org.json.JSONObject} to + * exchange data. + * + * @author Noor Dawod {@literal } + */ +public interface JsonValueInterface { + + /** + * Returns the escaped, ready-to-be used value of this encapsulated object. + * + * @return byte array holding the data to be used (as-is) in a JSON object + */ + byte[] getEscapedJsonValue(); +} diff --git a/library/src/main/java/com/loopj/android/http/LogHandler.java b/library/src/main/java/com/loopj/android/http/LogHandler.java new file mode 100644 index 000000000..2b7080a15 --- /dev/null +++ b/library/src/main/java/com/loopj/android/http/LogHandler.java @@ -0,0 +1,130 @@ +package com.loopj.android.http; + +import android.annotation.TargetApi; +import android.os.Build; +import android.util.Log; + +public class LogHandler implements LogInterface { + + boolean mLoggingEnabled = true; + int mLoggingLevel = VERBOSE; + + @Override + public boolean isLoggingEnabled() { + return mLoggingEnabled; + } + + @Override + public void setLoggingEnabled(boolean loggingEnabled) { + this.mLoggingEnabled = loggingEnabled; + } + + @Override + public int getLoggingLevel() { + return mLoggingLevel; + } + + @Override + public void setLoggingLevel(int loggingLevel) { + this.mLoggingLevel = loggingLevel; + } + + @Override + public boolean shouldLog(int logLevel) { + return logLevel >= mLoggingLevel; + } + + public void log(int logLevel, String tag, String msg) { + logWithThrowable(logLevel, tag, msg, null); + } + + public void logWithThrowable(int logLevel, String tag, String msg, Throwable t) { + if (isLoggingEnabled() && shouldLog(logLevel)) { + switch (logLevel) { + case VERBOSE: + Log.v(tag, msg, t); + break; + case WARN: + Log.w(tag, msg, t); + break; + case ERROR: + Log.e(tag, msg, t); + break; + case DEBUG: + Log.d(tag, msg, t); + break; + case WTF: + checkedWtf(tag, msg, t); + break; + case INFO: + Log.i(tag, msg, t); + break; + } + } + } + + @TargetApi(Build.VERSION_CODES.FROYO) + private void checkedWtf(String tag, String msg, Throwable t) { + Log.wtf(tag, msg, t); + } + + @Override + public void v(String tag, String msg) { + log(VERBOSE, tag, msg); + } + + @Override + public void v(String tag, String msg, Throwable t) { + logWithThrowable(VERBOSE, tag, msg, t); + } + + @Override + public void d(String tag, String msg) { + log(VERBOSE, tag, msg); + } + + @Override + public void d(String tag, String msg, Throwable t) { + logWithThrowable(DEBUG, tag, msg, t); + } + + @Override + public void i(String tag, String msg) { + log(INFO, tag, msg); + } + + @Override + public void i(String tag, String msg, Throwable t) { + logWithThrowable(INFO, tag, msg, t); + } + + @Override + public void w(String tag, String msg) { + log(WARN, tag, msg); + } + + @Override + public void w(String tag, String msg, Throwable t) { + logWithThrowable(WARN, tag, msg, t); + } + + @Override + public void e(String tag, String msg) { + log(ERROR, tag, msg); + } + + @Override + public void e(String tag, String msg, Throwable t) { + logWithThrowable(ERROR, tag, msg, t); + } + + @Override + public void wtf(String tag, String msg) { + log(WTF, tag, msg); + } + + @Override + public void wtf(String tag, String msg, Throwable t) { + logWithThrowable(WTF, tag, msg, t); + } +} diff --git a/library/src/main/java/com/loopj/android/http/LogInterface.java b/library/src/main/java/com/loopj/android/http/LogInterface.java new file mode 100644 index 000000000..f5a06b19a --- /dev/null +++ b/library/src/main/java/com/loopj/android/http/LogInterface.java @@ -0,0 +1,51 @@ +package com.loopj.android.http; + +/** + * Interface independent to any library, which currently uses same interface as {@link android.util.Log} implementation + * You can change currently used LogInterface through {@link AsyncHttpClient#setLogInterface(LogInterface)} + */ +public interface LogInterface { + + int VERBOSE = 2; + int DEBUG = 3; + int INFO = 4; + int WARN = 5; + int ERROR = 6; + int WTF = 8; + + boolean isLoggingEnabled(); + + void setLoggingEnabled(boolean loggingEnabled); + + int getLoggingLevel(); + + void setLoggingLevel(int loggingLevel); + + boolean shouldLog(int logLevel); + + void v(String tag, String msg); + + void v(String tag, String msg, Throwable t); + + void d(String tag, String msg); + + void d(String tag, String msg, Throwable t); + + void i(String tag, String msg); + + void i(String tag, String msg, Throwable t); + + void w(String tag, String msg); + + void w(String tag, String msg, Throwable t); + + void e(String tag, String msg); + + void e(String tag, String msg, Throwable t); + + void wtf(String tag, String msg); + + void wtf(String tag, String msg, Throwable t); + + +} diff --git a/library/src/main/java/com/loopj/android/http/MyRedirectHandler.java b/library/src/main/java/com/loopj/android/http/MyRedirectHandler.java new file mode 100644 index 000000000..54f385ede --- /dev/null +++ b/library/src/main/java/com/loopj/android/http/MyRedirectHandler.java @@ -0,0 +1,166 @@ +/* + Android Asynchronous Http Client + Copyright (c) 2014 Aymon Fournier + https://github.com/android-async-http/android-async-http + + 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 + + https://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.loopj.android.http; + +import java.net.URI; +import java.net.URISyntaxException; + +import cz.msebera.android.httpclient.Header; +import cz.msebera.android.httpclient.HttpHost; +import cz.msebera.android.httpclient.HttpRequest; +import cz.msebera.android.httpclient.HttpResponse; +import cz.msebera.android.httpclient.HttpStatus; +import cz.msebera.android.httpclient.ProtocolException; +import cz.msebera.android.httpclient.client.CircularRedirectException; +import cz.msebera.android.httpclient.client.params.ClientPNames; +import cz.msebera.android.httpclient.client.utils.URIUtils; +import cz.msebera.android.httpclient.impl.client.DefaultRedirectHandler; +import cz.msebera.android.httpclient.impl.client.RedirectLocations; +import cz.msebera.android.httpclient.params.HttpParams; +import cz.msebera.android.httpclient.protocol.ExecutionContext; +import cz.msebera.android.httpclient.protocol.HttpContext; + +/** + * Taken from StackOverflow + * + * @author Aymon Fournier, aymon.fournier@gmail.com + * @see https://stackoverflow.com/questions/3420767/httpclient-redirecting-to-url-with-spaces-throwing-exception + */ +class MyRedirectHandler extends DefaultRedirectHandler { + + private static final String REDIRECT_LOCATIONS = "http.protocol.redirect-locations"; + private final boolean enableRedirects; + + public MyRedirectHandler(final boolean allowRedirects) { + super(); + this.enableRedirects = allowRedirects; + } + + @Override + public boolean isRedirectRequested( + final HttpResponse response, + final HttpContext context) { + if (!enableRedirects) { + return false; + } + if (response == null) { + throw new IllegalArgumentException("HTTP response may not be null"); + } + int statusCode = response.getStatusLine().getStatusCode(); + switch (statusCode) { + case HttpStatus.SC_MOVED_TEMPORARILY: + case HttpStatus.SC_MOVED_PERMANENTLY: + case HttpStatus.SC_SEE_OTHER: + case HttpStatus.SC_TEMPORARY_REDIRECT: + return true; + default: + return false; + } //end of switch + } + + @Override + public URI getLocationURI( + final HttpResponse response, + final HttpContext context) throws ProtocolException { + if (response == null) { + throw new IllegalArgumentException("HTTP response may not be null"); + } + //get the location header to find out where to redirect to + Header locationHeader = response.getFirstHeader("location"); + if (locationHeader == null) { + // got a redirect response, but no location header + throw new ProtocolException( + "Received redirect response " + response.getStatusLine() + + " but no location header" + ); + } + //HERE IS THE MODIFIED LINE OF CODE + String location = locationHeader.getValue().replaceAll(" ", "%20"); + + URI uri; + try { + uri = new URI(location); + } catch (URISyntaxException ex) { + throw new ProtocolException("Invalid redirect URI: " + location, ex); + } + + HttpParams params = response.getParams(); + // rfc2616 demands the location value be a complete URI + // Location = "Location" ":" absoluteURI + if (!uri.isAbsolute()) { + if (params.isParameterTrue(ClientPNames.REJECT_RELATIVE_REDIRECT)) { + throw new ProtocolException("Relative redirect location '" + + uri + "' not allowed"); + } + // Adjust location URI + HttpHost target = (HttpHost) context.getAttribute( + ExecutionContext.HTTP_TARGET_HOST); + if (target == null) { + throw new IllegalStateException("Target host not available " + + "in the HTTP context"); + } + + HttpRequest request = (HttpRequest) context.getAttribute( + ExecutionContext.HTTP_REQUEST); + + try { + URI requestURI = new URI(request.getRequestLine().getUri()); + URI absoluteRequestURI = URIUtils.rewriteURI(requestURI, target, true); + uri = URIUtils.resolve(absoluteRequestURI, uri); + } catch (URISyntaxException ex) { + throw new ProtocolException(ex.getMessage(), ex); + } + } + + if (params.isParameterFalse(ClientPNames.ALLOW_CIRCULAR_REDIRECTS)) { + + RedirectLocations redirectLocations = (RedirectLocations) context.getAttribute( + REDIRECT_LOCATIONS); + + if (redirectLocations == null) { + redirectLocations = new RedirectLocations(); + context.setAttribute(REDIRECT_LOCATIONS, redirectLocations); + } + + URI redirectURI; + if (uri.getFragment() != null) { + try { + HttpHost target = new HttpHost( + uri.getHost(), + uri.getPort(), + uri.getScheme()); + redirectURI = URIUtils.rewriteURI(uri, target, true); + } catch (URISyntaxException ex) { + throw new ProtocolException(ex.getMessage(), ex); + } + } else { + redirectURI = uri; + } + + if (redirectLocations.contains(redirectURI)) { + throw new CircularRedirectException("Circular redirect to '" + + redirectURI + "'"); + } else { + redirectLocations.add(redirectURI); + } + } + + return uri; + } +} \ No newline at end of file diff --git a/library/src/main/java/com/loopj/android/http/MySSLSocketFactory.java b/library/src/main/java/com/loopj/android/http/MySSLSocketFactory.java new file mode 100755 index 000000000..7a2e6f432 --- /dev/null +++ b/library/src/main/java/com/loopj/android/http/MySSLSocketFactory.java @@ -0,0 +1,230 @@ +/* + Android Asynchronous Http Client + Copyright (c) 2011 James Smith + https://github.com/android-async-http/android-async-http + + 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 + + https://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.loopj.android.http; + +import java.io.BufferedInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.Socket; +import java.security.KeyManagementException; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.UnrecoverableKeyException; +import java.security.cert.Certificate; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; + +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLParameters; +import javax.net.ssl.SSLSocket; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; + +import cz.msebera.android.httpclient.HttpVersion; +import cz.msebera.android.httpclient.conn.ClientConnectionManager; +import cz.msebera.android.httpclient.conn.scheme.PlainSocketFactory; +import cz.msebera.android.httpclient.conn.scheme.Scheme; +import cz.msebera.android.httpclient.conn.scheme.SchemeRegistry; +import cz.msebera.android.httpclient.conn.ssl.SSLSocketFactory; +import cz.msebera.android.httpclient.impl.client.DefaultHttpClient; +import cz.msebera.android.httpclient.impl.conn.tsccm.ThreadSafeClientConnManager; +import cz.msebera.android.httpclient.params.BasicHttpParams; +import cz.msebera.android.httpclient.params.HttpParams; +import cz.msebera.android.httpclient.params.HttpProtocolParams; +import cz.msebera.android.httpclient.protocol.HTTP; + +/** + * This file is introduced to fix HTTPS Post bug on API < ICS see + * https://code.google.com/p/android/issues/detail?id=13117#c14

 

Warning! This omits SSL + * certificate validation on every device, use with caution + */ +public class MySSLSocketFactory extends SSLSocketFactory { + final SSLContext sslContext = SSLContext.getInstance("TLS"); + + /** + * Creates a new SSL Socket Factory with the given KeyStore. + * + * @param truststore A KeyStore to create the SSL Socket Factory in context of + * @throws NoSuchAlgorithmException NoSuchAlgorithmException + * @throws KeyManagementException KeyManagementException + * @throws KeyStoreException KeyStoreException + * @throws UnrecoverableKeyException UnrecoverableKeyException + */ + public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { + super(truststore); + + X509TrustManager tm = new X509TrustManager() { + public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { + try { + chain[0].checkValidity(); + } catch (Exception e) { + throw new CertificateException("Certificate not valid or trusted."); + } + } + + public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { + try { + chain[0].checkValidity(); + } catch (Exception e) { + throw new CertificateException("Certificate not valid or trusted."); + } + } + + public X509Certificate[] getAcceptedIssuers() { + return null; + } + }; + + sslContext.init(null, new TrustManager[]{tm}, null); + } + + /** + * Gets a KeyStore containing the Certificate + * + * @param cert InputStream of the Certificate + * @return KeyStore + */ + public static KeyStore getKeystoreOfCA(InputStream cert) { + + // Load CAs from an InputStream + InputStream caInput = null; + Certificate ca = null; + try { + CertificateFactory cf = CertificateFactory.getInstance("X.509"); + caInput = new BufferedInputStream(cert); + ca = cf.generateCertificate(caInput); + } catch (CertificateException e1) { + e1.printStackTrace(); + } finally { + try { + if (caInput != null) { + caInput.close(); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + + // Create a KeyStore containing our trusted CAs + String keyStoreType = KeyStore.getDefaultType(); + KeyStore keyStore = null; + try { + keyStore = KeyStore.getInstance(keyStoreType); + keyStore.load(null, null); + keyStore.setCertificateEntry("ca", ca); + } catch (Exception e) { + e.printStackTrace(); + } + return keyStore; + } + + /** + * Gets a Default KeyStore + * + * @return KeyStore + */ + public static KeyStore getKeystore() { + KeyStore trustStore = null; + try { + trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); + trustStore.load(null, null); + } catch (Throwable t) { + t.printStackTrace(); + } + return trustStore; + } + + /** + * Returns a SSlSocketFactory which trusts all certificates + * + * @return SSLSocketFactory + */ + public static SSLSocketFactory getFixedSocketFactory() { + SSLSocketFactory socketFactory; + try { + socketFactory = new MySSLSocketFactory(getKeystore()); + socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); + } catch (Throwable t) { + t.printStackTrace(); + socketFactory = SSLSocketFactory.getSocketFactory(); + } + return socketFactory; + } + + /** + * Gets a DefaultHttpClient which trusts a set of certificates specified by the KeyStore + * + * @param keyStore custom provided KeyStore instance + * @return DefaultHttpClient + */ + public static DefaultHttpClient getNewHttpClient(KeyStore keyStore) { + + try { + SSLSocketFactory sf = new MySSLSocketFactory(keyStore); + SchemeRegistry registry = new SchemeRegistry(); + registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); + registry.register(new Scheme("https", sf, 443)); + + HttpParams params = new BasicHttpParams(); + HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); + HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); + + ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); + + return new DefaultHttpClient(ccm, params); + } catch (Exception e) { + return new DefaultHttpClient(); + } + } + + @Override + public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException { + Socket localSocket = sslContext.getSocketFactory().createSocket(socket, host, port, autoClose); + enableSecureProtocols(localSocket); + return localSocket; + } + + @Override + public Socket createSocket() throws IOException { + Socket socket = sslContext.getSocketFactory().createSocket(); + enableSecureProtocols(socket); + return socket; + } + + /** + * Activate supported protocols on the socket. + * + * @param socket The socket on which to activate secure protocols. + */ + private void enableSecureProtocols(Socket socket) { + // set all supported protocols + SSLParameters params = sslContext.getSupportedSSLParameters(); + ((SSLSocket) socket).setEnabledProtocols(params.getProtocols()); + } + + /** + * Makes HttpsURLConnection trusts a set of certificates specified by the KeyStore + */ + public void fixHttpsURLConnection() { + HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory()); + } +} \ No newline at end of file diff --git a/src/com/loopj/android/http/PersistentCookieStore.java b/library/src/main/java/com/loopj/android/http/PersistentCookieStore.java old mode 100644 new mode 100755 similarity index 52% rename from src/com/loopj/android/http/PersistentCookieStore.java rename to library/src/main/java/com/loopj/android/http/PersistentCookieStore.java index 3f98a00bc..8065d4821 --- a/src/com/loopj/android/http/PersistentCookieStore.java +++ b/library/src/main/java/com/loopj/android/http/PersistentCookieStore.java @@ -1,13 +1,13 @@ /* Android Asynchronous Http Client Copyright (c) 2011 James Smith - http://loopj.com + https://github.com/android-async-http/android-async-http 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 + https://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, @@ -18,42 +18,44 @@ package com.loopj.android.http; +import android.content.Context; +import android.content.SharedPreferences; +import android.text.TextUtils; + import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; +import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.Date; import java.util.List; +import java.util.Locale; import java.util.concurrent.ConcurrentHashMap; -import org.apache.http.client.CookieStore; -import org.apache.http.cookie.Cookie; - -import android.content.Context; -import android.content.SharedPreferences; -import android.text.TextUtils; +import cz.msebera.android.httpclient.client.CookieStore; +import cz.msebera.android.httpclient.cookie.Cookie; /** - * A persistent cookie store which implements the Apache HttpClient - * {@link CookieStore} interface. Cookies are stored and will persist on the - * user's device between application sessions since they are serialized and - * stored in {@link SharedPreferences}. - *

- * Instances of this class are designed to be used with - * {@link AsyncHttpClient#setCookieStore}, but can also be used with a + * A persistent cookie store which implements the Apache HttpClient {@link CookieStore} interface. + * Cookies are stored and will persist on the user's device between application sessions since they + * are serialized and stored in {@link SharedPreferences}.

 

Instances of this class are + * designed to be used with {@link AsyncHttpClient#setCookieStore}, but can also be used with a * regular old apache HttpClient/HttpContext if you prefer. */ public class PersistentCookieStore implements CookieStore { + private static final String LOG_TAG = "PersistentCookieStore"; private static final String COOKIE_PREFS = "CookiePrefsFile"; private static final String COOKIE_NAME_STORE = "names"; private static final String COOKIE_NAME_PREFIX = "cookie_"; - private final ConcurrentHashMap cookies; private final SharedPreferences cookiePrefs; + private boolean omitNonPersistentCookies = false; /** * Construct a persistent cookie store. + * + * @param context Context to attach cookie store to */ public PersistentCookieStore(Context context) { cookiePrefs = context.getSharedPreferences(COOKIE_PREFS, 0); @@ -61,13 +63,13 @@ public PersistentCookieStore(Context context) { // Load any previously stored cookies into the store String storedCookieNames = cookiePrefs.getString(COOKIE_NAME_STORE, null); - if(storedCookieNames != null) { + if (storedCookieNames != null) { String[] cookieNames = TextUtils.split(storedCookieNames, ","); - for(String name : cookieNames) { + for (String name : cookieNames) { String encodedCookie = cookiePrefs.getString(COOKIE_NAME_PREFIX + name, null); - if(encodedCookie != null) { + if (encodedCookie != null) { Cookie decodedCookie = decodeCookie(encodedCookie); - if(decodedCookie != null) { + if (decodedCookie != null) { cookies.put(name, decodedCookie); } } @@ -80,10 +82,12 @@ public PersistentCookieStore(Context context) { @Override public void addCookie(Cookie cookie) { + if (omitNonPersistentCookies && !cookie.isPersistent()) + return; String name = cookie.getName() + cookie.getDomain(); // Save cookie into local store, or remove if expired - if(!cookie.isExpired(new Date())) { + if (!cookie.isExpired(new Date())) { cookies.put(name, cookie); } else { cookies.remove(name); @@ -93,21 +97,21 @@ public void addCookie(Cookie cookie) { SharedPreferences.Editor prefsWriter = cookiePrefs.edit(); prefsWriter.putString(COOKIE_NAME_STORE, TextUtils.join(",", cookies.keySet())); prefsWriter.putString(COOKIE_NAME_PREFIX + name, encodeCookie(new SerializableCookie(cookie))); - prefsWriter.commit(); + prefsWriter.apply(); } @Override public void clear() { - // Clear cookies from local store - cookies.clear(); - // Clear cookies from persistent store SharedPreferences.Editor prefsWriter = cookiePrefs.edit(); - for(String name : cookies.keySet()) { + for (String name : cookies.keySet()) { prefsWriter.remove(COOKIE_NAME_PREFIX + name); } prefsWriter.remove(COOKIE_NAME_STORE); - prefsWriter.commit(); + prefsWriter.apply(); + + // Clear cookies from local store + cookies.clear(); } @Override @@ -115,10 +119,10 @@ public boolean clearExpired(Date date) { boolean clearedAny = false; SharedPreferences.Editor prefsWriter = cookiePrefs.edit(); - for(ConcurrentHashMap.Entry entry : cookies.entrySet()) { + for (ConcurrentHashMap.Entry entry : cookies.entrySet()) { String name = entry.getKey(); Cookie cookie = entry.getValue(); - if(cookie.isExpired(date)) { + if (cookie.isExpired(date)) { // Clear cookies from local store cookies.remove(name); @@ -131,10 +135,10 @@ public boolean clearExpired(Date date) { } // Update names in persistent store - if(clearedAny) { + if (clearedAny) { prefsWriter.putString(COOKIE_NAME_STORE, TextUtils.join(",", cookies.keySet())); } - prefsWriter.commit(); + prefsWriter.apply(); return clearedAny; } @@ -144,56 +148,102 @@ public List getCookies() { return new ArrayList(cookies.values()); } + /** + * Will make PersistentCookieStore instance ignore Cookies, which are non-persistent by + * signature (`Cookie.isPersistent`) + * + * @param omitNonPersistentCookies true if non-persistent cookies should be omited + */ + public void setOmitNonPersistentCookies(boolean omitNonPersistentCookies) { + this.omitNonPersistentCookies = omitNonPersistentCookies; + } - // - // Cookie serialization/deserialization - // + /** + * Non-standard helper method, to delete cookie + * + * @param cookie cookie to be removed + */ + public void deleteCookie(Cookie cookie) { + String name = cookie.getName() + cookie.getDomain(); + cookies.remove(name); + SharedPreferences.Editor prefsWriter = cookiePrefs.edit(); + prefsWriter.remove(COOKIE_NAME_PREFIX + name); + prefsWriter.apply(); + } + /** + * Serializes Cookie object into String + * + * @param cookie cookie to be encoded, can be null + * @return cookie encoded as String + */ protected String encodeCookie(SerializableCookie cookie) { + if (cookie == null) + return null; ByteArrayOutputStream os = new ByteArrayOutputStream(); try { ObjectOutputStream outputStream = new ObjectOutputStream(os); outputStream.writeObject(cookie); - } catch (Exception e) { + } catch (IOException e) { + AsyncHttpClient.log.d(LOG_TAG, "IOException in encodeCookie", e); return null; } return byteArrayToHexString(os.toByteArray()); } - protected Cookie decodeCookie(String cookieStr) { - byte[] bytes = hexStringToByteArray(cookieStr); - ByteArrayInputStream is = new ByteArrayInputStream(bytes); + /** + * Returns cookie decoded from cookie string + * + * @param cookieString string of cookie as returned from http request + * @return decoded cookie or null if exception occured + */ + protected Cookie decodeCookie(String cookieString) { + byte[] bytes = hexStringToByteArray(cookieString); + ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); Cookie cookie = null; try { - ObjectInputStream ois = new ObjectInputStream(is); - cookie = ((SerializableCookie)ois.readObject()).getCookie(); - } catch (Exception e) { - e.printStackTrace(); + ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); + cookie = ((SerializableCookie) objectInputStream.readObject()).getCookie(); + } catch (IOException e) { + AsyncHttpClient.log.d(LOG_TAG, "IOException in decodeCookie", e); + } catch (ClassNotFoundException e) { + AsyncHttpClient.log.d(LOG_TAG, "ClassNotFoundException in decodeCookie", e); } return cookie; } - // Using some super basic byte array <-> hex conversions so we don't have - // to rely on any large Base64 libraries. Can be overridden if you like! - protected String byteArrayToHexString(byte[] b) { - StringBuffer sb = new StringBuffer(b.length * 2); - for (byte element : b) { + /** + * Using some super basic byte array <-> hex conversions so we don't have to rely on any + * large Base64 libraries. Can be overridden if you like! + * + * @param bytes byte array to be converted + * @return string containing hex values + */ + protected String byteArrayToHexString(byte[] bytes) { + StringBuilder sb = new StringBuilder(bytes.length * 2); + for (byte element : bytes) { int v = element & 0xff; - if(v < 16) { + if (v < 16) { sb.append('0'); } sb.append(Integer.toHexString(v)); } - return sb.toString().toUpperCase(); + return sb.toString().toUpperCase(Locale.US); } - protected byte[] hexStringToByteArray(String s) { - int len = s.length(); + /** + * Converts hex values from strings to byte arra + * + * @param hexString string of hex-encoded values + * @return decoded byte array + */ + protected byte[] hexStringToByteArray(String hexString) { + int len = hexString.length(); byte[] data = new byte[len / 2]; - for(int i=0; i + https://github.com/android-async-http/android-async-http + + 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 + + https://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.loopj.android.http; + +import java.io.IOException; + +import cz.msebera.android.httpclient.HttpException; +import cz.msebera.android.httpclient.HttpHost; +import cz.msebera.android.httpclient.HttpRequest; +import cz.msebera.android.httpclient.HttpRequestInterceptor; +import cz.msebera.android.httpclient.auth.AuthScope; +import cz.msebera.android.httpclient.auth.AuthState; +import cz.msebera.android.httpclient.auth.Credentials; +import cz.msebera.android.httpclient.client.CredentialsProvider; +import cz.msebera.android.httpclient.client.protocol.ClientContext; +import cz.msebera.android.httpclient.impl.auth.BasicScheme; +import cz.msebera.android.httpclient.protocol.ExecutionContext; +import cz.msebera.android.httpclient.protocol.HttpContext; + +public class PreemptiveAuthorizationHttpRequestInterceptor implements HttpRequestInterceptor { + + public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { + AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE); + CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute( + ClientContext.CREDS_PROVIDER); + HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); + + if (authState.getAuthScheme() == null) { + AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); + Credentials creds = credsProvider.getCredentials(authScope); + if (creds != null) { + authState.setAuthScheme(new BasicScheme()); + authState.setCredentials(creds); + } + } + } + +} diff --git a/library/src/main/java/com/loopj/android/http/RangeFileAsyncHttpResponseHandler.java b/library/src/main/java/com/loopj/android/http/RangeFileAsyncHttpResponseHandler.java new file mode 100755 index 000000000..f327a8caf --- /dev/null +++ b/library/src/main/java/com/loopj/android/http/RangeFileAsyncHttpResponseHandler.java @@ -0,0 +1,109 @@ +/* + Android Asynchronous Http Client + Copyright (c) 2014 Marek Sebera + https://github.com/android-async-http/android-async-http + + 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 + + https://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.loopj.android.http; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; + +import cz.msebera.android.httpclient.Header; +import cz.msebera.android.httpclient.HttpEntity; +import cz.msebera.android.httpclient.HttpResponse; +import cz.msebera.android.httpclient.HttpStatus; +import cz.msebera.android.httpclient.StatusLine; +import cz.msebera.android.httpclient.client.HttpResponseException; +import cz.msebera.android.httpclient.client.methods.HttpUriRequest; + + +public abstract class RangeFileAsyncHttpResponseHandler extends FileAsyncHttpResponseHandler { + private static final String LOG_TAG = "RangeFileAsyncHttpRH"; + + private long current = 0; + private boolean append = false; + + /** + * Obtains new RangeFileAsyncHttpResponseHandler and stores response in passed file + * + * @param file File to store response within, must not be null + */ + public RangeFileAsyncHttpResponseHandler(File file) { + super(file); + } + + @Override + public void sendResponseMessage(HttpResponse response) throws IOException { + if (!Thread.currentThread().isInterrupted()) { + StatusLine status = response.getStatusLine(); + if (status.getStatusCode() == HttpStatus.SC_REQUESTED_RANGE_NOT_SATISFIABLE) { + //already finished + if (!Thread.currentThread().isInterrupted()) + sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), null); + } else if (status.getStatusCode() >= 300) { + if (!Thread.currentThread().isInterrupted()) + sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), null, new HttpResponseException(status.getStatusCode(), status.getReasonPhrase())); + } else { + if (!Thread.currentThread().isInterrupted()) { + Header header = response.getFirstHeader(AsyncHttpClient.HEADER_CONTENT_RANGE); + if (header == null) { + append = false; + current = 0; + } else { + AsyncHttpClient.log.v(LOG_TAG, AsyncHttpClient.HEADER_CONTENT_RANGE + ": " + header.getValue()); + } + sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), getResponseData(response.getEntity())); + } + } + } + } + + @Override + protected byte[] getResponseData(HttpEntity entity) throws IOException { + if (entity != null) { + InputStream instream = entity.getContent(); + long contentLength = entity.getContentLength() + current; + FileOutputStream buffer = new FileOutputStream(getTargetFile(), append); + if (instream != null) { + try { + byte[] tmp = new byte[BUFFER_SIZE]; + int l; + while (current < contentLength && (l = instream.read(tmp)) != -1 && !Thread.currentThread().isInterrupted()) { + current += l; + buffer.write(tmp, 0, l); + sendProgressMessage(current, contentLength); + } + } finally { + instream.close(); + buffer.flush(); + buffer.close(); + } + } + } + return null; + } + + public void updateRequestHeaders(HttpUriRequest uriRequest) { + if (file.exists() && file.canWrite()) + current = file.length(); + if (current > 0) { + append = true; + uriRequest.setHeader("Range", "bytes=" + current + "-"); + } + } +} diff --git a/library/src/main/java/com/loopj/android/http/RequestHandle.java b/library/src/main/java/com/loopj/android/http/RequestHandle.java new file mode 100755 index 000000000..959190e13 --- /dev/null +++ b/library/src/main/java/com/loopj/android/http/RequestHandle.java @@ -0,0 +1,121 @@ +/* + Android Asynchronous Http Client + Copyright (c) 2013 Jason Choy + https://github.com/android-async-http/android-async-http + + 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 + + https://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.loopj.android.http; + +import android.os.Looper; + +import java.lang.ref.WeakReference; + +/** + * A Handle to an AsyncRequest which can be used to cancel a running request. + */ +public class RequestHandle { + private final WeakReference request; + + public RequestHandle(AsyncHttpRequest request) { + this.request = new WeakReference(request); + } + + /** + * Attempts to cancel this request. This attempt will fail if the request has already completed, + * has already been cancelled, or could not be cancelled for some other reason. If successful, + * and this request has not started when cancel is called, this request should never run. If the + * request has already started, then the mayInterruptIfRunning parameter determines whether the + * thread executing this request should be interrupted in an attempt to stop the request. + *

 

After this method returns, subsequent calls to isDone() will always return + * true. Subsequent calls to isCancelled() will always return true if this method returned + * true. Subsequent calls to isDone() will return true either if the request got cancelled by + * this method, or if the request completed normally + * + * @param mayInterruptIfRunning true if the thread executing this request should be interrupted; + * otherwise, in-progress requests are allowed to complete + * @return false if the request could not be cancelled, typically because it has already + * completed normally; true otherwise + */ + public boolean cancel(final boolean mayInterruptIfRunning) { + final AsyncHttpRequest _request = request.get(); + if (_request != null) { + if (Looper.myLooper() == Looper.getMainLooper()) { + new Thread(new Runnable() { + @Override + public void run() { + _request.cancel(mayInterruptIfRunning); + } + }).start(); + // Cannot reliably tell if the request got immediately canceled at this point + // we'll assume it got cancelled + return true; + } else { + return _request.cancel(mayInterruptIfRunning); + } + } + return false; + } + + /** + * Returns true if this task completed. Completion may be due to normal termination, an + * exception, or cancellation -- in all of these cases, this method will return true. + * + * @return true if this task completed + */ + public boolean isFinished() { + AsyncHttpRequest _request = request.get(); + return _request == null || _request.isDone(); + } + + /** + * Returns true if this task was cancelled before it completed normally. + * + * @return true if this task was cancelled before it completed + */ + public boolean isCancelled() { + AsyncHttpRequest _request = request.get(); + return _request == null || _request.isCancelled(); + } + + public boolean shouldBeGarbageCollected() { + boolean should = isCancelled() || isFinished(); + if (should) + request.clear(); + return should; + } + + /** + * Will return TAG of underlying AsyncHttpRequest if it's not already GCed + * + * @return Object TAG, can be null + */ + public Object getTag() { + AsyncHttpRequest _request = request.get(); + return _request == null ? null : _request.getTag(); + } + + /** + * Will set Object as TAG to underlying AsyncHttpRequest + * + * @param tag Object used as TAG to underlying AsyncHttpRequest + * @return this RequestHandle to allow fluid syntax + */ + public RequestHandle setTag(Object tag) { + AsyncHttpRequest _request = request.get(); + if (_request != null) + _request.setRequestTag(tag); + return this; + } +} \ No newline at end of file diff --git a/library/src/main/java/com/loopj/android/http/RequestParams.java b/library/src/main/java/com/loopj/android/http/RequestParams.java new file mode 100755 index 000000000..e594f7909 --- /dev/null +++ b/library/src/main/java/com/loopj/android/http/RequestParams.java @@ -0,0 +1,705 @@ +/* + Android Asynchronous Http Client + Copyright (c) 2011 James Smith + https://github.com/android-async-http/android-async-http + + 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 + + https://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.loopj.android.http; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.io.Serializable; +import java.io.UnsupportedEncodingException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentSkipListMap; +//import java.util.concurrent.ConcurrentSkipList; + +import cz.msebera.android.httpclient.HttpEntity; +import cz.msebera.android.httpclient.client.entity.UrlEncodedFormEntity; +import cz.msebera.android.httpclient.client.utils.URLEncodedUtils; +import cz.msebera.android.httpclient.message.BasicNameValuePair; +import cz.msebera.android.httpclient.protocol.HTTP; + +/** + * A collection of string request parameters or files to send along with requests made from an + * {@link AsyncHttpClient} instance.

 

For example:

 

+ *
+ * RequestParams params = new RequestParams();
+ * params.put("username", "james");
+ * params.put("password", "123456");
+ * params.put("email", "my@email.com");
+ * params.put("profile_picture", new File("pic.jpg")); // Upload a File
+ * params.put("profile_picture2", someInputStream); // Upload an InputStream
+ * params.put("profile_picture3", new ByteArrayInputStream(someBytes)); // Upload some bytes
+ *
+ * Map<String, String> map = new HashMap<String, String>();
+ * map.put("first_name", "James");
+ * map.put("last_name", "Smith");
+ * params.put("user", map); // url params: "user[first_name]=James&user[last_name]=Smith"
+ *
+ * Set<String> set = new HashSet<String>(); // unordered collection
+ * set.add("music");
+ * set.add("art");
+ * params.put("like", set); // url params: "like=music&like=art"
+ *
+ * List<String> list = new ArrayList<String>(); // Ordered collection
+ * list.add("Java");
+ * list.add("C");
+ * params.put("languages", list); // url params: "languages[0]=Java&languages[1]=C"
+ *
+ * String[] colors = { "blue", "yellow" }; // Ordered collection
+ * params.put("colors", colors); // url params: "colors[0]=blue&colors[1]=yellow"
+ *
+ * File[] files = { new File("pic.jpg"), new File("pic1.jpg") }; // Ordered collection
+ * params.put("files", files); // url params: "files[]=pic.jpg&files[]=pic1.jpg"
+ *
+ * List<Map<String, String>> listOfMaps = new ArrayList<Map<String,
+ * String>>();
+ * Map<String, String> user1 = new HashMap<String, String>();
+ * user1.put("age", "30");
+ * user1.put("gender", "male");
+ * Map<String, String> user2 = new HashMap<String, String>();
+ * user2.put("age", "25");
+ * user2.put("gender", "female");
+ * listOfMaps.add(user1);
+ * listOfMaps.add(user2);
+ * params.put("users", listOfMaps); // url params: "users[][age]=30&users[][gender]=male&users[][age]=25&users[][gender]=female"
+ *
+ * AsyncHttpClient client = new AsyncHttpClient();
+ * client.post("https://myendpoint.com/", params, responseHandler);
+ * 
+ */ +public class RequestParams implements Serializable { + + public final static String APPLICATION_OCTET_STREAM = + "application/octet-stream"; + + public final static String APPLICATION_JSON = + "application/json"; + + protected final static String LOG_TAG = "RequestParams"; + protected final ConcurrentSkipListMap urlParams = new ConcurrentSkipListMap(); + protected final ConcurrentSkipListMap streamParams = new ConcurrentSkipListMap(); + protected final ConcurrentSkipListMap fileParams = new ConcurrentSkipListMap(); + protected final ConcurrentSkipListMap> fileArrayParams = new ConcurrentSkipListMap>(); + protected final ConcurrentSkipListMap urlParamsWithObjects = new ConcurrentSkipListMap(); + protected boolean isRepeatable; + protected boolean forceMultipartEntity = false; + protected boolean useJsonStreamer; + protected String elapsedFieldInJsonStreamer = "_elapsed"; + protected boolean autoCloseInputStreams; + protected String contentEncoding = HTTP.UTF_8; + + /** + * Constructs a new empty {@code RequestParams} instance. + */ + public RequestParams() { + this((Map) null); + } + + /** + * Constructs a new RequestParams instance containing the key/value string params from the + * specified map. + * + * @param source the source key/value string map to add. + */ + public RequestParams(Map source) { + if (source != null) { + for (Map.Entry entry : source.entrySet()) { + put(entry.getKey(), entry.getValue()); + } + } + } + + /** + * Constructs a new RequestParams instance and populate it with a single initial key/value + * string param. + * + * @param key the key name for the intial param. + * @param value the value string for the initial param. + */ + public RequestParams(final String key, final String value) { + this(new HashMap() {{ + put(key, value); + }}); + } + + /** + * Constructs a new RequestParams instance and populate it with multiple initial key/value + * string param. + * + * @param keysAndValues a sequence of keys and values. Objects are automatically converted to + * Strings (including the value {@code null}). + * @throws IllegalArgumentException if the number of arguments isn't even. + */ + public RequestParams(Object... keysAndValues) { + int len = keysAndValues.length; + if (len % 2 != 0) + throw new IllegalArgumentException("Supplied arguments must be even"); + for (int i = 0; i < len; i += 2) { + String key = String.valueOf(keysAndValues[i]); + String val = String.valueOf(keysAndValues[i + 1]); + put(key, val); + } + } + + /** + * Sets content encoding for return value of {@link #getParamString()} and {@link + * #createFormEntity()}

 

Default encoding is "UTF-8" + * + * @param encoding String constant from {@link HTTP} + */ + public void setContentEncoding(final String encoding) { + if (encoding != null) { + this.contentEncoding = encoding; + } else { + AsyncHttpClient.log.d(LOG_TAG, "setContentEncoding called with null attribute"); + } + } + + /** + * If set to true will force Content-Type header to `multipart/form-data` + * even if there are not Files or Streams to be send + *

 

+ * Default value is false + * + * @param force boolean, should declare content-type multipart/form-data even without files or streams present + */ + public void setForceMultipartEntityContentType(boolean force) { + this.forceMultipartEntity = force; + } + + /** + * Adds a key/value string pair to the request. + * + * @param key the key name for the new param. + * @param value the value string for the new param. + */ + public void put(String key, String value) { + if (key != null && value != null) { + urlParams.put(key, value); + } + } + + /** + * Adds files array to the request. + * + * @param key the key name for the new param. + * @param files the files array to add. + * @throws FileNotFoundException if one of passed files is not found at time of assembling the requestparams into request + */ + public void put(String key, File files[]) throws FileNotFoundException { + put(key, files, null, null); + } + + /** + * Adds files array to the request with both custom provided file content-type and files name + * + * @param key the key name for the new param. + * @param files the files array to add. + * @param contentType the content type of the file, eg. application/json + * @param customFileName file name to use instead of real file name + * @throws FileNotFoundException throws if wrong File argument was passed + */ + public void put(String key, File files[], String contentType, String customFileName) throws FileNotFoundException { + + if (key != null) { + List fileWrappers = new ArrayList(); + for (File file : files) { + if (file == null || !file.exists()) { + throw new FileNotFoundException(); + } + fileWrappers.add(new FileWrapper(file, contentType, customFileName)); + } + fileArrayParams.put(key, fileWrappers); + } + } + + /** + * Adds a file to the request. + * + * @param key the key name for the new param. + * @param file the file to add. + * @throws FileNotFoundException throws if wrong File argument was passed + */ + public void put(String key, File file) throws FileNotFoundException { + put(key, file, null, null); + } + + /** + * Adds a file to the request with custom provided file name + * + * @param key the key name for the new param. + * @param file the file to add. + * @param customFileName file name to use instead of real file name + * @throws FileNotFoundException throws if wrong File argument was passed + */ + public void put(String key, String customFileName, File file) throws FileNotFoundException { + put(key, file, null, customFileName); + } + + /** + * Adds a file to the request with custom provided file content-type + * + * @param key the key name for the new param. + * @param file the file to add. + * @param contentType the content type of the file, eg. application/json + * @throws FileNotFoundException throws if wrong File argument was passed + */ + public void put(String key, File file, String contentType) throws FileNotFoundException { + put(key, file, contentType, null); + } + + /** + * Adds a file to the request with both custom provided file content-type and file name + * + * @param key the key name for the new param. + * @param file the file to add. + * @param contentType the content type of the file, eg. application/json + * @param customFileName file name to use instead of real file name + * @throws FileNotFoundException throws if wrong File argument was passed + */ + public void put(String key, File file, String contentType, String customFileName) throws FileNotFoundException { + if (file == null || !file.exists()) { + throw new FileNotFoundException(); + } + if (key != null) { + fileParams.put(key, new FileWrapper(file, contentType, customFileName)); + } + } + + /** + * Adds an input stream to the request. + * + * @param key the key name for the new param. + * @param stream the input stream to add. + */ + public void put(String key, InputStream stream) { + put(key, stream, null); + } + + /** + * Adds an input stream to the request. + * + * @param key the key name for the new param. + * @param stream the input stream to add. + * @param name the name of the stream. + */ + public void put(String key, InputStream stream, String name) { + put(key, stream, name, null); + } + + /** + * Adds an input stream to the request. + * + * @param key the key name for the new param. + * @param stream the input stream to add. + * @param name the name of the stream. + * @param contentType the content type of the file, eg. application/json + */ + public void put(String key, InputStream stream, String name, String contentType) { + put(key, stream, name, contentType, autoCloseInputStreams); + } + + /** + * Adds an input stream to the request. + * + * @param key the key name for the new param. + * @param stream the input stream to add. + * @param name the name of the stream. + * @param contentType the content type of the file, eg. application/json + * @param autoClose close input stream automatically on successful upload + */ + public void put(String key, InputStream stream, String name, String contentType, boolean autoClose) { + if (key != null && stream != null) { + streamParams.put(key, StreamWrapper.newInstance(stream, name, contentType, autoClose)); + } + } + + /** + * Adds param with non-string value (e.g. Map, List, Set). + * + * @param key the key name for the new param. + * @param value the non-string value object for the new param. + */ + public void put(String key, Object value) { + if (key != null && value != null) { + urlParamsWithObjects.put(key, value); + } + } + + /** + * Adds a int value to the request. + * + * @param key the key name for the new param. + * @param value the value int for the new param. + */ + public void put(String key, int value) { + if (key != null) { + urlParams.put(key, String.valueOf(value)); + } + } + + /** + * Adds a long value to the request. + * + * @param key the key name for the new param. + * @param value the value long for the new param. + */ + public void put(String key, long value) { + if (key != null) { + urlParams.put(key, String.valueOf(value)); + } + } + + /** + * Adds string value to param which can have more than one value. + * + * @param key the key name for the param, either existing or new. + * @param value the value string for the new param. + */ + public void add(String key, String value) { + if (key != null && value != null) { + Object params = urlParamsWithObjects.get(key); + if (params == null) { + // Backward compatible, which will result in "k=v1&k=v2&k=v3" + params = new HashSet(); + this.put(key, params); + } + if (params instanceof List) { + ((List) params).add(value); + } else if (params instanceof Set) { + ((Set) params).add(value); + } + } + } + + /** + * Removes a parameter from the request. + * + * @param key the key name for the parameter to remove. + */ + public void remove(String key) { + urlParams.remove(key); + streamParams.remove(key); + fileParams.remove(key); + urlParamsWithObjects.remove(key); + fileArrayParams.remove(key); + } + + /** + * Check if a parameter is defined. + * + * @param key the key name for the parameter to check existence. + * @return Boolean + */ + public boolean has(String key) { + return urlParams.get(key) != null || + streamParams.get(key) != null || + fileParams.get(key) != null || + urlParamsWithObjects.get(key) != null || + fileArrayParams.get(key) != null; + } + + @Override + public String toString() { + StringBuilder result = new StringBuilder(); + for (ConcurrentSkipListMap.Entry entry : urlParams.entrySet()) { + if (result.length() > 0) + result.append("&"); + + result.append(entry.getKey()); + result.append("="); + result.append(entry.getValue()); + } + + for (ConcurrentSkipListMap.Entry entry : streamParams.entrySet()) { + if (result.length() > 0) + result.append("&"); + + result.append(entry.getKey()); + result.append("="); + result.append("STREAM"); + } + + for (ConcurrentSkipListMap.Entry entry : fileParams.entrySet()) { + if (result.length() > 0) + result.append("&"); + + result.append(entry.getKey()); + result.append("="); + result.append("FILE"); + } + + for (ConcurrentSkipListMap.Entry> entry : fileArrayParams.entrySet()) { + if (result.length() > 0) + result.append("&"); + + result.append(entry.getKey()); + result.append("="); + result.append("FILES(SIZE=").append(entry.getValue().size()).append(")"); + } + + List params = getParamsList(null, urlParamsWithObjects); + for (BasicNameValuePair kv : params) { + if (result.length() > 0) + result.append("&"); + + result.append(kv.getName()); + result.append("="); + result.append(kv.getValue()); + } + + return result.toString(); + } + + public void setHttpEntityIsRepeatable(boolean flag) { + this.isRepeatable = flag; + } + + public void setUseJsonStreamer(boolean flag) { + this.useJsonStreamer = flag; + } + + /** + * Sets an additional field when upload a JSON object through the streamer + * to hold the time, in milliseconds, it took to upload the payload. By + * default, this field is set to "_elapsed". + *

 

+ * To disable this feature, call this method with null as the field value. + * + * @param value field name to add elapsed time, or null to disable + */ + public void setElapsedFieldInJsonStreamer(String value) { + this.elapsedFieldInJsonStreamer = value; + } + + /** + * Set global flag which determines whether to automatically close input streams on successful + * upload. + * + * @param flag boolean whether to automatically close input streams + */ + public void setAutoCloseInputStreams(boolean flag) { + autoCloseInputStreams = flag; + } + + /** + * Returns an HttpEntity containing all request parameters. + * + * @param progressHandler HttpResponseHandler for reporting progress on entity submit + * @return HttpEntity resulting HttpEntity to be included along with {@link + * cz.msebera.android.httpclient.client.methods.HttpEntityEnclosingRequestBase} + * @throws IOException if one of the streams cannot be read + */ + public HttpEntity getEntity(ResponseHandlerInterface progressHandler) throws IOException { + if (useJsonStreamer) { + return createJsonStreamerEntity(progressHandler); + } else if (!forceMultipartEntity && streamParams.isEmpty() && fileParams.isEmpty() && fileArrayParams.isEmpty()) { + return createFormEntity(); + } else { + return createMultipartEntity(progressHandler); + } + } + + private HttpEntity createJsonStreamerEntity(ResponseHandlerInterface progressHandler) throws IOException { + JsonStreamerEntity entity = new JsonStreamerEntity( + progressHandler, + !fileParams.isEmpty() || !streamParams.isEmpty(), + elapsedFieldInJsonStreamer); + + // Add string params + for (ConcurrentSkipListMap.Entry entry : urlParams.entrySet()) { + entity.addPart(entry.getKey(), entry.getValue()); + } + + // Add non-string params + for (ConcurrentSkipListMap.Entry entry : urlParamsWithObjects.entrySet()) { + entity.addPart(entry.getKey(), entry.getValue()); + } + + // Add file params + for (ConcurrentSkipListMap.Entry entry : fileParams.entrySet()) { + entity.addPart(entry.getKey(), entry.getValue()); + } + + // Add stream params + for (ConcurrentSkipListMap.Entry entry : streamParams.entrySet()) { + StreamWrapper stream = entry.getValue(); + if (stream.inputStream != null) { + entity.addPart(entry.getKey(), + StreamWrapper.newInstance( + stream.inputStream, + stream.name, + stream.contentType, + stream.autoClose) + ); + } + } + + return entity; + } + + private HttpEntity createFormEntity() { + try { + return new UrlEncodedFormEntity(getParamsList(), contentEncoding); + } catch (UnsupportedEncodingException e) { + AsyncHttpClient.log.e(LOG_TAG, "createFormEntity failed", e); + return null; // Can happen, if the 'contentEncoding' won't be HTTP.UTF_8 + } + } + + private HttpEntity createMultipartEntity(ResponseHandlerInterface progressHandler) throws IOException { + SimpleMultipartEntity entity = new SimpleMultipartEntity(progressHandler); + entity.setIsRepeatable(isRepeatable); + + // Add string params + for (ConcurrentSkipListMap.Entry entry : urlParams.entrySet()) { + entity.addPartWithCharset(entry.getKey(), entry.getValue(), contentEncoding); + } + + // Add non-string params + List params = getParamsList(null, urlParamsWithObjects); + for (BasicNameValuePair kv : params) { + entity.addPartWithCharset(kv.getName(), kv.getValue(), contentEncoding); + } + + // Add stream params + for (ConcurrentSkipListMap.Entry entry : streamParams.entrySet()) { + StreamWrapper stream = entry.getValue(); + if (stream.inputStream != null) { + entity.addPart(entry.getKey(), stream.name, stream.inputStream, + stream.contentType); + } + } + + // Add file params + for (ConcurrentSkipListMap.Entry entry : fileParams.entrySet()) { + FileWrapper fileWrapper = entry.getValue(); + entity.addPart(entry.getKey(), fileWrapper.file, fileWrapper.contentType, fileWrapper.customFileName); + } + + // Add file collection + for (ConcurrentSkipListMap.Entry> entry : fileArrayParams.entrySet()) { + List fileWrapper = entry.getValue(); + for (FileWrapper fw : fileWrapper) { + entity.addPart(entry.getKey(), fw.file, fw.contentType, fw.customFileName); + } + } + + return entity; + } + + protected List getParamsList() { + List lparams = new LinkedList(); + + for (ConcurrentSkipListMap.Entry entry : urlParams.entrySet()) { + lparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); + } + + lparams.addAll(getParamsList(null, urlParamsWithObjects)); + + return lparams; + } + + private List getParamsList(String key, Object value) { + List params = new LinkedList(); + if (value instanceof Map) { + Map map = (Map) value; + List list = new ArrayList(map.keySet()); + // Ensure consistent ordering in query string + if (list.size() > 0 && list.get(0) instanceof Comparable) { + Collections.sort(list); + } + for (Object nestedKey : list) { + if (nestedKey instanceof String) { + Object nestedValue = map.get(nestedKey); + if (nestedValue != null) { + params.addAll(getParamsList(key == null ? (String) nestedKey : String.format(Locale.US, "%s[%s]", key, nestedKey), + nestedValue)); + } + } + } + } else if (value instanceof List) { + List list = (List) value; + int listSize = list.size(); + for (int nestedValueIndex = 0; nestedValueIndex < listSize; nestedValueIndex++) { + params.addAll(getParamsList(String.format(Locale.US, "%s[%d]", key, nestedValueIndex), list.get(nestedValueIndex))); + } + } else if (value instanceof Object[]) { + Object[] array = (Object[]) value; + int arrayLength = array.length; + for (int nestedValueIndex = 0; nestedValueIndex < arrayLength; nestedValueIndex++) { + params.addAll(getParamsList(String.format(Locale.US, "%s[%d]", key, nestedValueIndex), array[nestedValueIndex])); + } + } else if (value instanceof Set) { + Set set = (Set) value; + for (Object nestedValue : set) { + params.addAll(getParamsList(key, nestedValue)); + } + } else { + params.add(new BasicNameValuePair(key, value.toString())); + } + return params; + } + + protected String getParamString() { + return URLEncodedUtils.format(getParamsList(), contentEncoding); + } + + public static class FileWrapper implements Serializable { + public final File file; + public final String contentType; + public final String customFileName; + + public FileWrapper(File file, String contentType, String customFileName) { + this.file = file; + this.contentType = contentType; + this.customFileName = customFileName; + } + } + + public static class StreamWrapper { + public final InputStream inputStream; + public final String name; + public final String contentType; + public final boolean autoClose; + + public StreamWrapper(InputStream inputStream, String name, String contentType, boolean autoClose) { + this.inputStream = inputStream; + this.name = name; + this.contentType = contentType; + this.autoClose = autoClose; + } + + static StreamWrapper newInstance(InputStream inputStream, String name, String contentType, boolean autoClose) { + return new StreamWrapper( + inputStream, + name, + contentType == null ? APPLICATION_OCTET_STREAM : contentType, + autoClose); + } + } +} diff --git a/library/src/main/java/com/loopj/android/http/ResponseHandlerInterface.java b/library/src/main/java/com/loopj/android/http/ResponseHandlerInterface.java new file mode 100755 index 000000000..4040a965b --- /dev/null +++ b/library/src/main/java/com/loopj/android/http/ResponseHandlerInterface.java @@ -0,0 +1,189 @@ +/* + Android Asynchronous Http Client + Copyright (c) 2013 Marek Sebera + https://github.com/android-async-http/android-async-http + + 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 + + https://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.loopj.android.http; + +import java.io.IOException; +import java.net.URI; + +import cz.msebera.android.httpclient.Header; +import cz.msebera.android.httpclient.HttpResponse; + +/** + * Interface to standardize implementations + */ +public interface ResponseHandlerInterface { + + /** + * Returns data whether request completed successfully + * + * @param response HttpResponse object with data + * @throws java.io.IOException if retrieving data from response fails + */ + void sendResponseMessage(HttpResponse response) throws IOException; + + /** + * Notifies callback, that request started execution + */ + void sendStartMessage(); + + /** + * Notifies callback, that request was completed and is being removed from thread pool + */ + void sendFinishMessage(); + + /** + * Notifies callback, that request (mainly uploading) has progressed + * + * @param bytesWritten number of written bytes + * @param bytesTotal number of total bytes to be written + */ + void sendProgressMessage(long bytesWritten, long bytesTotal); + + /** + * Notifies callback, that request was cancelled + */ + void sendCancelMessage(); + + /** + * Notifies callback, that request was handled successfully + * + * @param statusCode HTTP status code + * @param headers returned headers + * @param responseBody returned data + */ + void sendSuccessMessage(int statusCode, Header[] headers, byte[] responseBody); + + /** + * Returns if request was completed with error code or failure of implementation + * + * @param statusCode returned HTTP status code + * @param headers returned headers + * @param responseBody returned data + * @param error cause of request failure + */ + void sendFailureMessage(int statusCode, Header[] headers, byte[] responseBody, Throwable error); + + /** + * Notifies callback of retrying request + * + * @param retryNo number of retry within one request + */ + void sendRetryMessage(int retryNo); + + /** + * Returns URI which was used to request + * + * @return uri of origin request + */ + URI getRequestURI(); + + /** + * Helper for handlers to receive Request URI info + * + * @param requestURI claimed request URI + */ + void setRequestURI(URI requestURI); + + /** + * Returns Header[] which were used to request + * + * @return headers from origin request + */ + Header[] getRequestHeaders(); + + /** + * Helper for handlers to receive Request Header[] info + * + * @param requestHeaders Headers, claimed to be from original request + */ + void setRequestHeaders(Header[] requestHeaders); + + /** + * Returns whether the handler is asynchronous or synchronous + * + * @return boolean if the ResponseHandler is running in synchronous mode + */ + boolean getUseSynchronousMode(); + + /** + * Can set, whether the handler should be asynchronous or synchronous + * + * @param useSynchronousMode whether data should be handled on background Thread on UI Thread + */ + void setUseSynchronousMode(boolean useSynchronousMode); + + /** + * Returns whether the handler should be executed on the pool's thread + * or the UI thread + * + * @return boolean if the ResponseHandler should run on pool's thread + */ + boolean getUsePoolThread(); + + /** + * Sets whether the handler should be executed on the pool's thread or the + * UI thread + * + * @param usePoolThread if the ResponseHandler should run on pool's thread + */ + void setUsePoolThread(boolean usePoolThread); + + /** + * This method is called once by the system when the response is about to be + * processed by the system. The library makes sure that a single response + * is pre-processed only once. + *

 

+ * Please note: pre-processing does NOT run on the main thread, and thus + * any UI activities that you must perform should be properly dispatched to + * the app's UI thread. + * + * @param instance An instance of this response object + * @param response The response to pre-processed + */ + void onPreProcessResponse(ResponseHandlerInterface instance, HttpResponse response); + + /** + * This method is called once by the system when the request has been fully + * sent, handled and finished. The library makes sure that a single response + * is post-processed only once. + *

 

+ * Please note: post-processing does NOT run on the main thread, and thus + * any UI activities that you must perform should be properly dispatched to + * the app's UI thread. + * + * @param instance An instance of this response object + * @param response The response to post-process + */ + void onPostProcessResponse(ResponseHandlerInterface instance, HttpResponse response); + + /** + * Will retrieve TAG Object if it's not already freed from memory + * + * @return Object TAG or null if it's been garbage collected + */ + Object getTag(); + + /** + * Will set TAG to ResponseHandlerInterface implementation, which can be then obtained + * in implemented methods, such as onSuccess, onFailure, ... + * + * @param TAG Object to be set as TAG, will be placed in WeakReference + */ + void setTag(Object TAG); +} diff --git a/src/com/loopj/android/http/RetryHandler.java b/library/src/main/java/com/loopj/android/http/RetryHandler.java old mode 100644 new mode 100755 similarity index 66% rename from src/com/loopj/android/http/RetryHandler.java rename to library/src/main/java/com/loopj/android/http/RetryHandler.java index 5256aad21..c9e549a2b --- a/src/com/loopj/android/http/RetryHandler.java +++ b/library/src/main/java/com/loopj/android/http/RetryHandler.java @@ -1,13 +1,13 @@ /* Android Asynchronous Http Client Copyright (c) 2011 James Smith - http://loopj.com + https://github.com/android-async-http/android-async-http 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 + https://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, @@ -23,27 +23,25 @@ package com.loopj.android.http; +import android.os.SystemClock; + import java.io.IOException; import java.io.InterruptedIOException; import java.net.SocketException; import java.net.UnknownHostException; import java.util.HashSet; -import java.util.Iterator; import javax.net.ssl.SSLException; -import org.apache.http.NoHttpResponseException; -import org.apache.http.client.HttpRequestRetryHandler; -import org.apache.http.client.methods.HttpUriRequest; -import org.apache.http.protocol.ExecutionContext; -import org.apache.http.protocol.HttpContext; - -import android.os.SystemClock; +import cz.msebera.android.httpclient.NoHttpResponseException; +import cz.msebera.android.httpclient.client.HttpRequestRetryHandler; +import cz.msebera.android.httpclient.client.methods.HttpUriRequest; +import cz.msebera.android.httpclient.protocol.ExecutionContext; +import cz.msebera.android.httpclient.protocol.HttpContext; class RetryHandler implements HttpRequestRetryHandler { - private static final int RETRY_SLEEP_TIME_MILLIS = 1500; - private static HashSet> exceptionWhitelist = new HashSet>(); - private static HashSet> exceptionBlacklist = new HashSet>(); + private final static HashSet> exceptionWhitelist = new HashSet>(); + private final static HashSet> exceptionBlacklist = new HashSet>(); static { // Retry if the server dropped connection on us @@ -60,9 +58,19 @@ class RetryHandler implements HttpRequestRetryHandler { } private final int maxRetries; + private final int retrySleepTimeMS; - public RetryHandler(int maxRetries) { + public RetryHandler(int maxRetries, int retrySleepTimeMS) { this.maxRetries = maxRetries; + this.retrySleepTimeMS = retrySleepTimeMS; + } + + static void addClassToWhitelist(Class cls) { + exceptionWhitelist.add(cls); + } + + static void addClassToBlacklist(Class cls) { + exceptionBlacklist.add(cls); } @Override @@ -70,45 +78,45 @@ public boolean retryRequest(IOException exception, int executionCount, HttpConte boolean retry = true; Boolean b = (Boolean) context.getAttribute(ExecutionContext.HTTP_REQ_SENT); - boolean sent = (b != null && b.booleanValue()); + boolean sent = (b != null && b); - if(executionCount > maxRetries) { + if (executionCount > maxRetries) { // Do not retry if over max retry count retry = false; - } else if (isInList(exceptionBlacklist, exception)) { - // immediately cancel retry if the error is blacklisted - retry = false; } else if (isInList(exceptionWhitelist, exception)) { // immediately retry if error is whitelisted retry = true; + } else if (isInList(exceptionBlacklist, exception)) { + // immediately cancel retry if the error is blacklisted + retry = false; } else if (!sent) { // for most other errors, retry only if request hasn't been fully sent yet retry = true; } - if(retry) { + if (retry) { // resend all idempotent requests - HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute( ExecutionContext.HTTP_REQUEST ); - String requestType = currentReq.getMethod(); - retry = !requestType.equals("POST"); + HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST); + if (currentReq == null) { + return false; + } } - if(retry) { - SystemClock.sleep(RETRY_SLEEP_TIME_MILLIS); + if (retry) { + SystemClock.sleep(retrySleepTimeMS); } else { exception.printStackTrace(); } return retry; } - + protected boolean isInList(HashSet> list, Throwable error) { - Iterator> itr = list.iterator(); - while (itr.hasNext()) { - if (itr.next().isInstance(error)) { - return true; - } - } - return false; + for (Class aList : list) { + if (aList.isInstance(error)) { + return true; + } + } + return false; } -} \ No newline at end of file +} diff --git a/library/src/main/java/com/loopj/android/http/SaxAsyncHttpResponseHandler.java b/library/src/main/java/com/loopj/android/http/SaxAsyncHttpResponseHandler.java new file mode 100644 index 000000000..8198fb549 --- /dev/null +++ b/library/src/main/java/com/loopj/android/http/SaxAsyncHttpResponseHandler.java @@ -0,0 +1,148 @@ +/* + Android Asynchronous Http Client + Copyright (c) 2011 James Smith + https://github.com/android-async-http/android-async-http + + 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 + + https://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.loopj.android.http; + +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; +import org.xml.sax.XMLReader; +import org.xml.sax.helpers.DefaultHandler; + +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; + +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.parsers.SAXParser; +import javax.xml.parsers.SAXParserFactory; + +import cz.msebera.android.httpclient.Header; +import cz.msebera.android.httpclient.HttpEntity; + +/** + * Provides interface to deserialize SAX responses, using AsyncHttpResponseHandler. Can be used like + * this + *

 

+ *
+ *     AsyncHttpClient ahc = new AsyncHttpClient();
+ *     FontHandler handlerInstance = ... ; // init handler instance
+ *     ahc.post("https://server.tld/api/call", new SaxAsyncHttpResponseHandler{@literal <}FontHandler{@literal >}(handlerInstance){
+ *         @Override
+ *         public void onSuccess(int statusCode, Header[] headers, FontHandler t) {
+ *              // Request got HTTP success statusCode
+ *         }
+ *         @Override
+ *         public void onFailure(int statusCode, Header[] headers, FontHandler t){
+ *              // Request got HTTP fail statusCode
+ *         }
+ *     });
+ * 
+ * + * @param Handler extending {@link org.xml.sax.helpers.DefaultHandler} + * @see org.xml.sax.helpers.DefaultHandler + * @see com.loopj.android.http.AsyncHttpResponseHandler + */ +public abstract class SaxAsyncHttpResponseHandler extends AsyncHttpResponseHandler { + + private final static String LOG_TAG = "SaxAsyncHttpRH"; + /** + * Generic Type of handler + */ + private T handler = null; + + /** + * Constructs new SaxAsyncHttpResponseHandler with given handler instance + * + * @param t instance of Handler extending DefaultHandler + * @see org.xml.sax.helpers.DefaultHandler + */ + public SaxAsyncHttpResponseHandler(T t) { + super(); + if (t == null) { + throw new Error("null instance of passed to constructor"); + } + this.handler = t; + } + + /** + * Deconstructs response into given content handler + * + * @param entity returned HttpEntity + * @return deconstructed response + * @throws java.io.IOException if there is problem assembling SAX response from stream + * @see cz.msebera.android.httpclient.HttpEntity + */ + @Override + protected byte[] getResponseData(HttpEntity entity) throws IOException { + if (entity != null) { + InputStream instream = entity.getContent(); + InputStreamReader inputStreamReader = null; + if (instream != null) { + try { + SAXParserFactory sfactory = SAXParserFactory.newInstance(); + SAXParser sparser = sfactory.newSAXParser(); + XMLReader rssReader = sparser.getXMLReader(); + rssReader.setContentHandler(handler); + inputStreamReader = new InputStreamReader(instream, getCharset()); + rssReader.parse(new InputSource(inputStreamReader)); + } catch (SAXException e) { + AsyncHttpClient.log.e(LOG_TAG, "getResponseData exception", e); + } catch (ParserConfigurationException e) { + AsyncHttpClient.log.e(LOG_TAG, "getResponseData exception", e); + } finally { + AsyncHttpClient.silentCloseInputStream(instream); + if (inputStreamReader != null) { + try { + inputStreamReader.close(); + } catch (IOException e) { /*ignore*/ } + } + } + } + } + return null; + } + + /** + * Default onSuccess method for this AsyncHttpResponseHandler to override + * + * @param statusCode returned HTTP status code + * @param headers returned HTTP headers + * @param t instance of Handler extending DefaultHandler + */ + public abstract void onSuccess(int statusCode, Header[] headers, T t); + + @Override + public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { + onSuccess(statusCode, headers, handler); + } + + /** + * Default onFailure method for this AsyncHttpResponseHandler to override + * + * @param statusCode returned HTTP status code + * @param headers returned HTTP headers + * @param t instance of Handler extending DefaultHandler + */ + public abstract void onFailure(int statusCode, Header[] headers, T t); + + @Override + public void onFailure(int statusCode, Header[] headers, + byte[] responseBody, Throwable error) { + onFailure(statusCode, headers, handler); + } +} diff --git a/src/com/loopj/android/http/SerializableCookie.java b/library/src/main/java/com/loopj/android/http/SerializableCookie.java old mode 100644 new mode 100755 similarity index 73% rename from src/com/loopj/android/http/SerializableCookie.java rename to library/src/main/java/com/loopj/android/http/SerializableCookie.java index cc12993c2..f6b88ffc0 --- a/src/com/loopj/android/http/SerializableCookie.java +++ b/library/src/main/java/com/loopj/android/http/SerializableCookie.java @@ -1,13 +1,13 @@ /* Android Asynchronous Http Client Copyright (c) 2011 James Smith - http://loopj.com + https://github.com/android-async-http/android-async-http 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 + https://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, @@ -18,18 +18,18 @@ package com.loopj.android.http; -import java.io.Serializable; +import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; -import java.io.IOException; +import java.io.Serializable; import java.util.Date; -import org.apache.http.cookie.Cookie; -import org.apache.http.impl.cookie.BasicClientCookie; +import cz.msebera.android.httpclient.cookie.Cookie; +import cz.msebera.android.httpclient.impl.cookie.BasicClientCookie; /** - * A wrapper class around {@link Cookie} and/or {@link BasicClientCookie} - * designed for use in {@link PersistentCookieStore}. + * A wrapper class around {@link Cookie} and/or {@link BasicClientCookie} designed for use in {@link + * PersistentCookieStore}. */ public class SerializableCookie implements Serializable { private static final long serialVersionUID = 6374381828722046732L; @@ -43,7 +43,7 @@ public SerializableCookie(Cookie cookie) { public Cookie getCookie() { Cookie bestCookie = cookie; - if(clientCookie != null) { + if (clientCookie != null) { bestCookie = clientCookie; } return bestCookie; @@ -61,13 +61,13 @@ private void writeObject(ObjectOutputStream out) throws IOException { } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { - String name = (String)in.readObject(); - String value = (String)in.readObject(); - clientCookie = new BasicClientCookie(name, value); - clientCookie.setComment((String)in.readObject()); - clientCookie.setDomain((String)in.readObject()); - clientCookie.setExpiryDate((Date)in.readObject()); - clientCookie.setPath((String)in.readObject()); + String key = (String) in.readObject(); + String value = (String) in.readObject(); + clientCookie = new BasicClientCookie(key, value); + clientCookie.setComment((String) in.readObject()); + clientCookie.setDomain((String) in.readObject()); + clientCookie.setExpiryDate((Date) in.readObject()); + clientCookie.setPath((String) in.readObject()); clientCookie.setVersion(in.readInt()); clientCookie.setSecure(in.readBoolean()); } diff --git a/library/src/main/java/com/loopj/android/http/SimpleMultipartEntity.java b/library/src/main/java/com/loopj/android/http/SimpleMultipartEntity.java new file mode 100755 index 000000000..2b4758f70 --- /dev/null +++ b/library/src/main/java/com/loopj/android/http/SimpleMultipartEntity.java @@ -0,0 +1,297 @@ +/* + Android Asynchronous Http Client + Copyright (c) 2011 James Smith + https://github.com/android-async-http/android-async-http + + 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 + + https://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. +*/ + +/* + This code is taken from Rafael Sanches' blog. Link is no longer working (as of 17th July 2015) + https://blog.rafaelsanches.com/2011/01/29/upload-using-multipart-post-using-httpclient-in-android/ +*/ + +package com.loopj.android.http; + +import android.text.TextUtils; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.Random; + +import cz.msebera.android.httpclient.Header; +import cz.msebera.android.httpclient.HttpEntity; +import cz.msebera.android.httpclient.message.BasicHeader; +import cz.msebera.android.httpclient.protocol.HTTP; + +/** + * Simplified multipart entity mainly used for sending one or more files. + */ +class SimpleMultipartEntity implements HttpEntity { + + private static final String LOG_TAG = "SimpleMultipartEntity"; + + private static final String STR_CR_LF = "\r\n"; + private static final byte[] CR_LF = STR_CR_LF.getBytes(); + private static final byte[] TRANSFER_ENCODING_BINARY = + ("Content-Transfer-Encoding: binary" + STR_CR_LF).getBytes(); + + private final static char[] MULTIPART_CHARS = + "-_1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray(); + + private final String boundary; + private final byte[] boundaryLine; + private final byte[] boundaryEnd; + private final List fileParts = new ArrayList(); + // The buffer we use for building the message excluding files and the last + // boundary + private final ByteArrayOutputStream out = new ByteArrayOutputStream(); + private final ResponseHandlerInterface progressHandler; + private boolean isRepeatable; + private long bytesWritten; + + private long totalSize; + + public SimpleMultipartEntity(ResponseHandlerInterface progressHandler) { + final StringBuilder buf = new StringBuilder(); + final Random rand = new Random(); + for (int i = 0; i < 30; i++) { + buf.append(MULTIPART_CHARS[rand.nextInt(MULTIPART_CHARS.length)]); + } + + boundary = buf.toString(); + boundaryLine = ("--" + boundary + STR_CR_LF).getBytes(); + boundaryEnd = ("--" + boundary + "--" + STR_CR_LF).getBytes(); + + this.progressHandler = progressHandler; + } + + public void addPart(String key, String value, String contentType) { + try { + out.write(boundaryLine); + out.write(createContentDisposition(key)); + out.write(createContentType(contentType)); + out.write(CR_LF); + out.write(value.getBytes()); + out.write(CR_LF); + } catch (final IOException e) { + // Shall not happen on ByteArrayOutputStream + AsyncHttpClient.log.e(LOG_TAG, "addPart ByteArrayOutputStream exception", e); + } + } + + public void addPartWithCharset(String key, String value, String charset) { + if (charset == null) charset = HTTP.UTF_8; + addPart(key, value, "text/plain; charset=" + charset); + } + + public void addPart(String key, String value) { + addPartWithCharset(key, value, null); + } + + public void addPart(String key, File file) { + addPart(key, file, null); + } + + public void addPart(String key, File file, String type) { + fileParts.add(new FilePart(key, file, normalizeContentType(type))); + } + + public void addPart(String key, File file, String type, String customFileName) { + fileParts.add(new FilePart(key, file, normalizeContentType(type), customFileName)); + } + + public void addPart(String key, String streamName, InputStream inputStream, String type) + throws IOException { + + out.write(boundaryLine); + + // Headers + out.write(createContentDisposition(key, streamName)); + out.write(createContentType(type)); + out.write(TRANSFER_ENCODING_BINARY); + out.write(CR_LF); + + // Stream (file) + final byte[] tmp = new byte[4096]; + int l; + while ((l = inputStream.read(tmp)) != -1) { + out.write(tmp, 0, l); + } + + out.write(CR_LF); + out.flush(); + } + + private String normalizeContentType(String type) { + return type == null ? RequestParams.APPLICATION_OCTET_STREAM : type; + } + + private byte[] createContentType(String type) { + String result = AsyncHttpClient.HEADER_CONTENT_TYPE + ": " + normalizeContentType(type) + STR_CR_LF; + return result.getBytes(); + } + + private byte[] createContentDisposition(String key) { + return ( + AsyncHttpClient.HEADER_CONTENT_DISPOSITION + + ": form-data; name=\"" + key + "\"" + STR_CR_LF).getBytes(); + } + + private byte[] createContentDisposition(String key, String fileName) { + return ( + AsyncHttpClient.HEADER_CONTENT_DISPOSITION + + ": form-data; name=\"" + key + "\"" + + "; filename=\"" + fileName + "\"" + STR_CR_LF).getBytes(); + } + + private void updateProgress(long count) { + bytesWritten += count; + progressHandler.sendProgressMessage(bytesWritten, totalSize); + } + + @Override + public long getContentLength() { + long contentLen = out.size(); + for (FilePart filePart : fileParts) { + long len = filePart.getTotalLength(); + if (len < 0) { + return -1; // Should normally not happen + } + contentLen += len; + } + contentLen += boundaryEnd.length; + return contentLen; + } + + // The following methods are from the HttpEntity interface + + @Override + public Header getContentType() { + return new BasicHeader( + AsyncHttpClient.HEADER_CONTENT_TYPE, + "multipart/form-data; boundary=" + boundary); + } + + @Override + public boolean isChunked() { + return false; + } + + public void setIsRepeatable(boolean isRepeatable) { + this.isRepeatable = isRepeatable; + } + + @Override + public boolean isRepeatable() { + return isRepeatable; + } + + @Override + public boolean isStreaming() { + return false; + } + + @Override + public void writeTo(final OutputStream outstream) throws IOException { + bytesWritten = 0; + totalSize = (int) getContentLength(); + out.writeTo(outstream); + updateProgress(out.size()); + + for (FilePart filePart : fileParts) { + filePart.writeTo(outstream); + } + outstream.write(boundaryEnd); + updateProgress(boundaryEnd.length); + } + + @Override + public Header getContentEncoding() { + return null; + } + + @Override + public void consumeContent() throws IOException, UnsupportedOperationException { + if (isStreaming()) { + throw new UnsupportedOperationException( + "Streaming entity does not implement #consumeContent()"); + } + } + + @Override + public InputStream getContent() throws IOException, UnsupportedOperationException { + throw new UnsupportedOperationException( + "getContent() is not supported. Use writeTo() instead."); + } + + private class FilePart { + public final File file; + public final byte[] header; + + public FilePart(String key, File file, String type, String customFileName) { + header = createHeader(key, TextUtils.isEmpty(customFileName) ? file.getName() : customFileName, type); + this.file = file; + } + + public FilePart(String key, File file, String type) { + header = createHeader(key, file.getName(), type); + this.file = file; + } + + private byte[] createHeader(String key, String filename, String type) { + ByteArrayOutputStream headerStream = new ByteArrayOutputStream(); + try { + headerStream.write(boundaryLine); + + // Headers + headerStream.write(createContentDisposition(key, filename)); + headerStream.write(createContentType(type)); + headerStream.write(TRANSFER_ENCODING_BINARY); + headerStream.write(CR_LF); + } catch (IOException e) { + // Can't happen on ByteArrayOutputStream + AsyncHttpClient.log.e(LOG_TAG, "createHeader ByteArrayOutputStream exception", e); + } + return headerStream.toByteArray(); + } + + public long getTotalLength() { + long streamLength = file.length() + CR_LF.length; + return header.length + streamLength; + } + + public void writeTo(OutputStream out) throws IOException { + out.write(header); + updateProgress(header.length); + + FileInputStream inputStream = new FileInputStream(file); + final byte[] tmp = new byte[4096]; + int bytesRead; + while ((bytesRead = inputStream.read(tmp)) != -1) { + out.write(tmp, 0, bytesRead); + updateProgress(bytesRead); + } + out.write(CR_LF); + updateProgress(CR_LF.length); + out.flush(); + AsyncHttpClient.silentCloseInputStream(inputStream); + } + } +} diff --git a/library/src/main/java/com/loopj/android/http/SyncHttpClient.java b/library/src/main/java/com/loopj/android/http/SyncHttpClient.java new file mode 100755 index 000000000..dd7d8f532 --- /dev/null +++ b/library/src/main/java/com/loopj/android/http/SyncHttpClient.java @@ -0,0 +1,101 @@ +/* + Android Asynchronous Http Client + Copyright (c) 2011 James Smith + https://github.com/android-async-http/android-async-http + + 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 + + https://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.loopj.android.http; + +import android.content.Context; + +import cz.msebera.android.httpclient.client.methods.HttpUriRequest; +import cz.msebera.android.httpclient.conn.scheme.SchemeRegistry; +import cz.msebera.android.httpclient.impl.client.DefaultHttpClient; +import cz.msebera.android.httpclient.protocol.HttpContext; + +/** + * Processes http requests in synchronous mode, so your caller thread will be blocked on each + * request + * + * @see com.loopj.android.http.AsyncHttpClient + */ +public class SyncHttpClient extends AsyncHttpClient { + + /** + * Creates a new SyncHttpClient with default constructor arguments values + */ + public SyncHttpClient() { + super(false, 80, 443); + } + + /** + * Creates a new SyncHttpClient. + * + * @param httpPort non-standard HTTP-only port + */ + public SyncHttpClient(int httpPort) { + super(false, httpPort, 443); + } + + /** + * Creates a new SyncHttpClient. + * + * @param httpPort non-standard HTTP-only port + * @param httpsPort non-standard HTTPS-only port + */ + public SyncHttpClient(int httpPort, int httpsPort) { + super(false, httpPort, httpsPort); + } + + /** + * Creates new SyncHttpClient using given params + * + * @param fixNoHttpResponseException Whether to fix or not issue, by ommiting SSL verification + * @param httpPort HTTP port to be used, must be greater than 0 + * @param httpsPort HTTPS port to be used, must be greater than 0 + */ + public SyncHttpClient(boolean fixNoHttpResponseException, int httpPort, int httpsPort) { + super(fixNoHttpResponseException, httpPort, httpsPort); + } + + /** + * Creates a new SyncHttpClient. + * + * @param schemeRegistry SchemeRegistry to be used + */ + public SyncHttpClient(SchemeRegistry schemeRegistry) { + super(schemeRegistry); + } + + @Override + protected RequestHandle sendRequest(DefaultHttpClient client, + HttpContext httpContext, HttpUriRequest uriRequest, + String contentType, ResponseHandlerInterface responseHandler, + Context context) { + if (contentType != null) { + uriRequest.addHeader(AsyncHttpClient.HEADER_CONTENT_TYPE, contentType); + } + + responseHandler.setUseSynchronousMode(true); + + /* + * will execute the request directly + */ + newAsyncHttpRequest(client, httpContext, uriRequest, contentType, responseHandler, context).run(); + + // Return a Request Handle that cannot be used to cancel the request + // because it is already complete by the time this returns + return new RequestHandle(null); + } +} diff --git a/library/src/main/java/com/loopj/android/http/TextHttpResponseHandler.java b/library/src/main/java/com/loopj/android/http/TextHttpResponseHandler.java new file mode 100755 index 000000000..6b8aa67ed --- /dev/null +++ b/library/src/main/java/com/loopj/android/http/TextHttpResponseHandler.java @@ -0,0 +1,125 @@ +/* + Android Asynchronous Http Client + Copyright (c) 2011 James Smith + https://github.com/android-async-http/android-async-http + + 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 + + https://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.loopj.android.http; + +import java.io.UnsupportedEncodingException; + +import cz.msebera.android.httpclient.Header; + +/** + * Used to intercept and handle the responses from requests made using {@link AsyncHttpClient}. The + * {@link #onSuccess(int, cz.msebera.android.httpclient.Header[], String)} method is designed to be anonymously + * overridden with your own response handling code.

 

Additionally, you can override the + * {@link #onFailure(int, cz.msebera.android.httpclient.Header[], String, Throwable)}, {@link #onStart()}, and + * {@link #onFinish()} methods as required.

 

For example:

 

+ *
+ * AsyncHttpClient client = new AsyncHttpClient();
+ * client.get("https://www.google.com/", new TextHttpResponseHandler() {
+ *     @Override
+ *     public void onStart() {
+ *         // Initiated the request
+ *     }
+ *
+ *     @Override
+ *     public void onSuccess(String responseBody) {
+ *         // Successfully got a response
+ *     }
+ *
+ *     @Override
+ *     public void onFailure(String responseBody, Throwable e) {
+ *         // Response failed :(
+ *     }
+ *
+ *     @Override
+ *     public void onFinish() {
+ *         // Completed the request (either success or failure)
+ *     }
+ * });
+ * 
+ */ +public abstract class TextHttpResponseHandler extends AsyncHttpResponseHandler { + + private static final String LOG_TAG = "TextHttpRH"; + + /** + * Creates new instance with default UTF-8 encoding + */ + public TextHttpResponseHandler() { + this(DEFAULT_CHARSET); + } + + /** + * Creates new instance with given string encoding + * + * @param encoding String encoding, see {@link #setCharset(String)} + */ + public TextHttpResponseHandler(String encoding) { + super(); + setCharset(encoding); + } + + /** + * Attempts to encode response bytes as string of set encoding + * + * @param charset charset to create string with + * @param stringBytes response bytes + * @return String of set encoding or null + */ + public static String getResponseString(byte[] stringBytes, String charset) { + try { + String toReturn = (stringBytes == null) ? null : new String(stringBytes, charset); + if (toReturn != null && toReturn.startsWith(UTF8_BOM)) { + return toReturn.substring(1); + } + return toReturn; + } catch (UnsupportedEncodingException e) { + AsyncHttpClient.log.e(LOG_TAG, "Encoding response into string failed", e); + return null; + } + } + + /** + * Called when request fails + * + * @param statusCode http response status line + * @param headers response headers if any + * @param responseString string response of given charset + * @param throwable throwable returned when processing request + */ + public abstract void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable); + + /** + * Called when request succeeds + * + * @param statusCode http response status line + * @param headers response headers if any + * @param responseString string response of given charset + */ + public abstract void onSuccess(int statusCode, Header[] headers, String responseString); + + @Override + public void onSuccess(int statusCode, Header[] headers, byte[] responseBytes) { + onSuccess(statusCode, headers, getResponseString(responseBytes, getCharset())); + } + + @Override + public void onFailure(int statusCode, Header[] headers, byte[] responseBytes, Throwable throwable) { + onFailure(statusCode, headers, getResponseString(responseBytes, getCharset()), throwable); + } +} diff --git a/library/src/main/java/com/loopj/android/http/TokenCredentials.java b/library/src/main/java/com/loopj/android/http/TokenCredentials.java new file mode 100644 index 000000000..aa361d395 --- /dev/null +++ b/library/src/main/java/com/loopj/android/http/TokenCredentials.java @@ -0,0 +1,42 @@ +/* + Android Asynchronous Http Client + Copyright (c) 2011 James Smith + https://github.com/android-async-http/android-async-http + + 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 + + https://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.loopj.android.http; + +import java.security.Principal; + +import cz.msebera.android.httpclient.auth.BasicUserPrincipal; +import cz.msebera.android.httpclient.auth.Credentials; + +public class TokenCredentials implements Credentials { + private Principal userPrincipal; + + public TokenCredentials(String token) { + this.userPrincipal = new BasicUserPrincipal(token); + } + + @Override + public Principal getUserPrincipal() { + return userPrincipal; + } + + @Override + public String getPassword() { + return null; + } + +} diff --git a/library/src/main/java/com/loopj/android/http/Utils.java b/library/src/main/java/com/loopj/android/http/Utils.java new file mode 100644 index 000000000..3f56df33f --- /dev/null +++ b/library/src/main/java/com/loopj/android/http/Utils.java @@ -0,0 +1,56 @@ +/* + Android Asynchronous Http Client + Copyright (c) 2011 James Smith + https://github.com/android-async-http/android-async-http + + 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 + + https://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.loopj.android.http; + +/** + * Provides general assert utils, which are stripped by Android SDK on + * compile/runtime, to work on release builds + */ +class Utils { + + private Utils() { + } + + /** + * Will throw AssertionError, if expression is not true + * + * @param expression result of your asserted condition + * @param failedMessage message to be included in error log + * @throws java.lang.AssertionError + */ + public static void asserts(final boolean expression, final String failedMessage) { + if (!expression) { + throw new AssertionError(failedMessage); + } + } + + /** + * Will throw IllegalArgumentException if provided object is null on runtime + * + * @param argument object that should be asserted as not null + * @param name name of the object asserted + * @throws java.lang.IllegalArgumentException + */ + public static T notNull(final T argument, final String name) { + if (argument == null) { + throw new IllegalArgumentException(name + " should not be null!"); + } + return argument; + } +} diff --git a/library/src/main/java/com/loopj/android/http/package-info.java b/library/src/main/java/com/loopj/android/http/package-info.java new file mode 100644 index 000000000..1e99633ca --- /dev/null +++ b/library/src/main/java/com/loopj/android/http/package-info.java @@ -0,0 +1,19 @@ +/* + Android Asynchronous Http Client + Copyright (c) 2011 James Smith + https://github.com/android-async-http/android-async-http + + 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 + + https://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.loopj.android.http; \ No newline at end of file diff --git a/maven_push.gradle b/maven_push.gradle new file mode 100755 index 000000000..b56473b28 --- /dev/null +++ b/maven_push.gradle @@ -0,0 +1,128 @@ +/* + * Copyright 2013 Chris Banes + * + * 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 + * + * https://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: 'maven' +apply plugin: 'signing' + +def isReleaseBuild() { + return VERSION_NAME.contains("SNAPSHOT") == false +} + +def getReleaseRepositoryUrl() { + return hasProperty('RELEASE_REPOSITORY_URL') ? RELEASE_REPOSITORY_URL + : "https://oss.sonatype.org/service/local/staging/deploy/maven2/" +} + +def getSnapshotRepositoryUrl() { + return hasProperty('SNAPSHOT_REPOSITORY_URL') ? SNAPSHOT_REPOSITORY_URL + : "https://oss.sonatype.org/content/repositories/snapshots/" +} + +def getRepositoryUsername() { + return hasProperty('NEXUS_USERNAME') ? NEXUS_USERNAME : "" +} + +def getRepositoryPassword() { + return hasProperty('NEXUS_PASSWORD') ? NEXUS_PASSWORD : "" +} + +afterEvaluate { project -> + uploadArchives { + repositories { + mavenDeployer { + beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) } + + pom.groupId = GROUP + pom.artifactId = POM_ARTIFACT_ID + pom.version = VERSION_NAME + + repository(url: getReleaseRepositoryUrl()) { + authentication(userName: getRepositoryUsername(), password: getRepositoryPassword()) + } + snapshotRepository(url: getSnapshotRepositoryUrl()) { + authentication(userName: getRepositoryUsername(), password: getRepositoryPassword()) + } + + pom.project { + name POM_NAME + packaging POM_PACKAGING + description POM_DESCRIPTION + url POM_URL + + scm { + url POM_SCM_URL + connection POM_SCM_CONNECTION + developerConnection POM_SCM_DEV_CONNECTION + } + + licenses { + license { + name POM_LICENCE_NAME + url POM_LICENCE_URL + distribution POM_LICENCE_DIST + } + } + + developers { + developer { + id POM_DEVELOPER_ID + name POM_DEVELOPER_NAME + } + } + } + } + } + } + + task installArchives(type: Upload) { + description "Installs the artifacts to the local Maven repository." + configuration = configurations['archives'] + repositories { + mavenDeployer { + pom.groupId = GROUP + pom.artifactId = POM_ARTIFACT_ID + pom.version = VERSION_NAME + + repository url: "file://${System.properties['user.home']}/.m2/repository" + } + } + } + + signing { + required { isReleaseBuild() && gradle.taskGraph.hasTask("uploadArchives") } + sign configurations.archives + } + + task androidJavadocs(type: Javadoc) { + source = android.sourceSets.main.java.srcDirs + classpath += project.files(android.getBootClasspath().join(File.pathSeparator)) + } + + task androidJavadocsJar(type: Jar, dependsOn: androidJavadocs) { + classifier = 'javadoc' + from androidJavadocs.destinationDir + } + + task androidSourcesJar(type: Jar) { + classifier = 'sources' + from android.sourceSets.main.java.srcDirs + } + + artifacts { + archives androidSourcesJar + archives androidJavadocsJar + } +} diff --git a/project.properties b/project.properties deleted file mode 100644 index 1880987e2..000000000 --- a/project.properties +++ /dev/null @@ -1,12 +0,0 @@ -# This file is automatically generated by Android Tools. -# Do not modify this file -- YOUR CHANGES WILL BE ERASED! -# -# This file must be checked in Version Control Systems. -# -# To customize properties used by the Ant build system use, -# "ant.properties", and override values to adapt the script to your -# project structure. - -android.library=true -# Project target. -target=android-3 diff --git a/releases/android-async-http-1.4.4.jar b/releases/android-async-http-1.4.4.jar new file mode 100644 index 000000000..75af7015d Binary files /dev/null and b/releases/android-async-http-1.4.4.jar differ diff --git a/releases/android-async-http-1.4.5.jar b/releases/android-async-http-1.4.5.jar new file mode 100644 index 000000000..d383f60e8 Binary files /dev/null and b/releases/android-async-http-1.4.5.jar differ diff --git a/releases/android-async-http-1.4.6.jar b/releases/android-async-http-1.4.6.jar new file mode 100644 index 000000000..70391cb95 Binary files /dev/null and b/releases/android-async-http-1.4.6.jar differ diff --git a/releases/android-async-http-1.4.7.jar b/releases/android-async-http-1.4.7.jar new file mode 100644 index 000000000..d9e203e5f Binary files /dev/null and b/releases/android-async-http-1.4.7.jar differ diff --git a/releases/android-async-http-1.4.8.jar b/releases/android-async-http-1.4.8.jar new file mode 100644 index 000000000..74664cca1 Binary files /dev/null and b/releases/android-async-http-1.4.8.jar differ diff --git a/sample/.gitignore b/sample/.gitignore new file mode 100755 index 000000000..796b96d1c --- /dev/null +++ b/sample/.gitignore @@ -0,0 +1 @@ +/build diff --git a/sample/build.gradle b/sample/build.gradle new file mode 100755 index 000000000..a964a667f --- /dev/null +++ b/sample/build.gradle @@ -0,0 +1,43 @@ +apply plugin: 'com.android.application' + +repositories { + mavenCentral() + maven { + url "https://oss.sonatype.org/content/repositories/snapshots/" + } +} + +android { + compileSdkVersion 28 + + defaultConfig { + minSdkVersion 9 + targetSdkVersion 28 + } + + flavorDimensions "version" + productFlavors { + standard { + dimension "version" + } + } + + lintOptions { + xmlReport false + warningsAsErrors true + quiet false + showAll true + disable 'OldTargetApi', 'UnusedAttribute', 'LongLogTag', 'TrustAllX509TrustManager', 'GoogleAppIndexingWarning', 'Autofill', 'LabelFor', 'SetTextI18n' + } + + packagingOptions { + exclude 'META-INF/DEPENDENCIES' + exclude 'META-INF/LICENSE' + exclude 'META-INF/NOTICE' + } +} + +dependencies { + implementation 'com.fasterxml.jackson.core:jackson-databind:2.11.0' + implementation project(':android-async-http') +} diff --git a/sample/src/main/AndroidManifest.xml b/sample/src/main/AndroidManifest.xml new file mode 100755 index 000000000..3f4f13d4f --- /dev/null +++ b/sample/src/main/AndroidManifest.xml @@ -0,0 +1,63 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/sample/src/main/java/com/loopj/android/http/sample/AsyncBackgroundThreadSample.java b/sample/src/main/java/com/loopj/android/http/sample/AsyncBackgroundThreadSample.java new file mode 100755 index 000000000..3af0dbea7 --- /dev/null +++ b/sample/src/main/java/com/loopj/android/http/sample/AsyncBackgroundThreadSample.java @@ -0,0 +1,153 @@ +/* + Android Asynchronous Http Client Sample + Copyright (c) 2014 Marek Sebera + https://github.com/android-async-http/android-async-http + + 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 + + https://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.loopj.android.http.sample; + +import android.app.Activity; +import android.os.Looper; +import android.util.Log; +import android.widget.Toast; + +import com.loopj.android.http.AsyncHttpClient; +import com.loopj.android.http.AsyncHttpResponseHandler; +import com.loopj.android.http.RequestHandle; +import com.loopj.android.http.ResponseHandlerInterface; + +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.FutureTask; +import java.util.concurrent.TimeUnit; +import java.util.Locale; + +import cz.msebera.android.httpclient.Header; +import cz.msebera.android.httpclient.HttpEntity; + +public class AsyncBackgroundThreadSample extends SampleParentActivity { + private static final String LOG_TAG = "AsyncBackgroundThreadSample"; + + private final ExecutorService executor = Executors.newSingleThreadExecutor(); + + @Override + public void onStop() { + super.onStop(); + } + + @Override + public RequestHandle executeSample(final AsyncHttpClient client, final String URL, final Header[] headers, HttpEntity entity, final ResponseHandlerInterface responseHandler) { + + final Activity ctx = this; + FutureTask future = new FutureTask<>(new Callable() { + public RequestHandle call() { + Log.d(LOG_TAG, "Executing GET request on background thread"); + return client.get(ctx, URL, headers, null, responseHandler); + } + }); + + executor.execute(future); + + RequestHandle handle = null; + try { + handle = future.get(5, TimeUnit.SECONDS); + Log.d(LOG_TAG, "Background thread for GET request has finished"); + } catch (Exception e) { + Toast.makeText(ctx, e.getMessage(), Toast.LENGTH_LONG).show(); + e.printStackTrace(); + } + + return handle; + } + + @Override + public int getSampleTitle() { + return R.string.title_async_background_thread; + } + + @Override + public boolean isRequestBodyAllowed() { + return false; + } + + @Override + public boolean isRequestHeadersAllowed() { + return false; + } + + @Override + public String getDefaultURL() { + return PROTOCOL + "httpbin.org/get"; + } + + @Override + public ResponseHandlerInterface getResponseHandler() { + + FutureTask future = new FutureTask<>(new Callable() { + + @Override + public ResponseHandlerInterface call() throws Exception { + Log.d(LOG_TAG, "Creating AsyncHttpResponseHandler on background thread"); + return new AsyncHttpResponseHandler(Looper.getMainLooper()) { + + @Override + public void onStart() { + clearOutputs(); + } + + @Override + public void onSuccess(int statusCode, Header[] headers, byte[] response) { + Log.d(LOG_TAG, String.format(Locale.US, "onSuccess executing on main thread : %B", Looper.myLooper() == Looper.getMainLooper())); + debugHeaders(LOG_TAG, headers); + debugStatusCode(LOG_TAG, statusCode); + debugResponse(LOG_TAG, new String(response)); + } + + @Override + public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) { + Log.d(LOG_TAG, String.format(Locale.US, "onFailure executing on main thread : %B", Looper.myLooper() == Looper.getMainLooper())); + debugHeaders(LOG_TAG, headers); + debugStatusCode(LOG_TAG, statusCode); + debugThrowable(LOG_TAG, e); + if (errorResponse != null) { + debugResponse(LOG_TAG, new String(errorResponse)); + } + } + + @Override + public void onRetry(int retryNo) { + Toast.makeText(AsyncBackgroundThreadSample.this, + String.format(Locale.US, "Request is retried, retry no. %d", retryNo), + Toast.LENGTH_SHORT) + .show(); + } + }; + } + }); + + executor.execute(future); + + ResponseHandlerInterface responseHandler = null; + try { + responseHandler = future.get(); + Log.d(LOG_TAG, "Background thread for AsyncHttpResponseHandler has finished"); + } catch (Exception e) { + e.printStackTrace(); + } + + return responseHandler; + } +} diff --git a/sample/src/main/java/com/loopj/android/http/sample/BinarySample.java b/sample/src/main/java/com/loopj/android/http/sample/BinarySample.java new file mode 100755 index 000000000..73d47a5ad --- /dev/null +++ b/sample/src/main/java/com/loopj/android/http/sample/BinarySample.java @@ -0,0 +1,88 @@ +/* + Android Asynchronous Http Client Sample + Copyright (c) 2014 Marek Sebera + https://github.com/android-async-http/android-async-http + + 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 + + https://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.loopj.android.http.sample; + +import com.loopj.android.http.AsyncHttpClient; +import com.loopj.android.http.BinaryHttpResponseHandler; +import com.loopj.android.http.RequestHandle; +import com.loopj.android.http.ResponseHandlerInterface; + +import cz.msebera.android.httpclient.Header; +import cz.msebera.android.httpclient.HttpEntity; + +public class BinarySample extends SampleParentActivity { + private static final String LOG_TAG = "BinarySample"; + + @Override + public int getSampleTitle() { + return R.string.title_binary_sample; + } + + @Override + public boolean isRequestBodyAllowed() { + return false; + } + + @Override + public boolean isRequestHeadersAllowed() { + return true; + } + + @Override + public String getDefaultURL() { + return "https://httpbin.org/gzip"; + } + + @Override + public ResponseHandlerInterface getResponseHandler() { + return new BinaryHttpResponseHandler() { + @Override + public void onStart() { + clearOutputs(); + } + + @Override + public String[] getAllowedContentTypes() { + // Allowing all data for debug purposes + return new String[]{".*"}; + } + + public void onSuccess(int statusCode, Header[] headers, byte[] binaryData) { + debugStatusCode(LOG_TAG, statusCode); + debugHeaders(LOG_TAG, headers); + debugResponse(LOG_TAG, "Received response is " + binaryData.length + " bytes"); + } + + @Override + public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) { + debugHeaders(LOG_TAG, headers); + debugStatusCode(LOG_TAG, statusCode); + debugThrowable(LOG_TAG, e); + if (errorResponse != null) { + debugResponse(LOG_TAG, "Received response is " + errorResponse.length + " bytes"); + } + } + }; + } + + @Override + public RequestHandle executeSample(AsyncHttpClient client, String URL, Header[] headers, HttpEntity entity, ResponseHandlerInterface responseHandler) { + return client.get(this, URL, headers, null, responseHandler); + } +} diff --git a/sample/src/main/java/com/loopj/android/http/sample/CancelAllRequestsSample.java b/sample/src/main/java/com/loopj/android/http/sample/CancelAllRequestsSample.java new file mode 100644 index 000000000..7348e26e4 --- /dev/null +++ b/sample/src/main/java/com/loopj/android/http/sample/CancelAllRequestsSample.java @@ -0,0 +1,32 @@ +/* + Android Asynchronous Http Client Sample + Copyright (c) 2014 Marek Sebera + https://github.com/android-async-http/android-async-http + + 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 + + https://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.loopj.android.http.sample; + +public class CancelAllRequestsSample extends ThreadingTimeoutSample { + + @Override + public int getSampleTitle() { + return R.string.title_cancel_all; + } + + @Override + public void onCancelButtonPressed() { + getAsyncHttpClient().cancelAllRequests(true); + } +} diff --git a/sample/src/main/java/com/loopj/android/http/sample/CancelRequestByTagSample.java b/sample/src/main/java/com/loopj/android/http/sample/CancelRequestByTagSample.java new file mode 100644 index 000000000..38f1133bd --- /dev/null +++ b/sample/src/main/java/com/loopj/android/http/sample/CancelRequestByTagSample.java @@ -0,0 +1,84 @@ +/* + Android Asynchronous Http Client Sample + Copyright (c) 2014 Marek Sebera + https://github.com/android-async-http/android-async-http + + 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 + + https://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.loopj.android.http.sample; + +import android.util.Log; + +import com.loopj.android.http.AsyncHttpClient; +import com.loopj.android.http.AsyncHttpResponseHandler; +import com.loopj.android.http.RequestHandle; +import com.loopj.android.http.ResponseHandlerInterface; + +import cz.msebera.android.httpclient.Header; +import cz.msebera.android.httpclient.HttpEntity; + +public class CancelRequestByTagSample extends ThreadingTimeoutSample { + + private static final String LOG_TAG = "CancelRequestByTagSample"; + private static final Integer REQUEST_TAG = 132435; + + @Override + public int getSampleTitle() { + return R.string.title_cancel_tag; + } + + @Override + public void onCancelButtonPressed() { + Log.d(LOG_TAG, "Canceling requests by TAG: " + REQUEST_TAG); + getAsyncHttpClient().cancelRequestsByTAG(REQUEST_TAG, false); + } + + @Override + public ResponseHandlerInterface getResponseHandler() { + return new AsyncHttpResponseHandler() { + + private final int id = counter++; + + @Override + public void onStart() { + setStatus(id, "TAG:" + getTag() + ", START"); + } + + @Override + public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { + setStatus(id, "SUCCESS"); + } + + @Override + public void onFinish() { + setStatus(id, "FINISH"); + } + + @Override + public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { + setStatus(id, "FAILURE"); + } + + @Override + public void onCancel() { + setStatus(id, "CANCEL"); + } + }; + } + + @Override + public RequestHandle executeSample(AsyncHttpClient client, String URL, Header[] headers, HttpEntity entity, ResponseHandlerInterface responseHandler) { + return client.get(this, URL, headers, null, responseHandler).setTag(REQUEST_TAG); + } +} diff --git a/sample/src/main/java/com/loopj/android/http/sample/CancelRequestHandleSample.java b/sample/src/main/java/com/loopj/android/http/sample/CancelRequestHandleSample.java new file mode 100644 index 000000000..e41a1d1be --- /dev/null +++ b/sample/src/main/java/com/loopj/android/http/sample/CancelRequestHandleSample.java @@ -0,0 +1,50 @@ +/* + Android Asynchronous Http Client Sample + Copyright (c) 2014 Marek Sebera + https://github.com/android-async-http/android-async-http + + 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 + + https://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.loopj.android.http.sample; + +import android.util.Log; + +import java.util.Locale; + +import com.loopj.android.http.RequestHandle; + +public class CancelRequestHandleSample extends ThreadingTimeoutSample { + + private static final String LOG_TAG = "CancelRequestHandleSample"; + + @Override + public int getSampleTitle() { + return R.string.title_cancel_handle; + } + + @Override + public void onCancelButtonPressed() { + Log.d(LOG_TAG, String.format(Locale.US, "Number of handles found: %d", getRequestHandles().size())); + int counter = 0; + for (RequestHandle handle : getRequestHandles()) { + if (!handle.isCancelled() && !handle.isFinished()) { + Log.d(LOG_TAG, String.format(Locale.US, "Cancelling handle %d", counter)); + Log.d(LOG_TAG, String.format(Locale.US, "Handle %d cancel", counter) + (handle.cancel(true) ? " succeeded" : " failed")); + } else { + Log.d(LOG_TAG, String.format(Locale.US, "Handle %d already non-cancellable", counter)); + } + counter++; + } + } +} diff --git a/sample/src/main/java/com/loopj/android/http/sample/ContentTypeForHttpEntitySample.java b/sample/src/main/java/com/loopj/android/http/sample/ContentTypeForHttpEntitySample.java new file mode 100644 index 000000000..aa7183c6a --- /dev/null +++ b/sample/src/main/java/com/loopj/android/http/sample/ContentTypeForHttpEntitySample.java @@ -0,0 +1,72 @@ +package com.loopj.android.http.sample; + +import android.util.Log; + +import com.loopj.android.http.AsyncHttpClient; +import com.loopj.android.http.RequestHandle; +import com.loopj.android.http.RequestParams; +import com.loopj.android.http.ResponseHandlerInterface; +import com.loopj.android.http.TextHttpResponseHandler; + +import java.io.File; +import java.io.IOException; + +import cz.msebera.android.httpclient.Header; +import cz.msebera.android.httpclient.HttpEntity; + +public class ContentTypeForHttpEntitySample extends SampleParentActivity { + private static final String LOG_TAG = "ContentTypeForHttpEntitySample"; + + @Override + public ResponseHandlerInterface getResponseHandler() { + return new TextHttpResponseHandler() { + @Override + public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) { + debugHeaders(LOG_TAG, headers); + debugStatusCode(LOG_TAG, statusCode); + debugResponse(LOG_TAG, responseString); + debugThrowable(LOG_TAG, throwable); + } + + @Override + public void onSuccess(int statusCode, Header[] headers, String responseString) { + debugHeaders(LOG_TAG, headers); + debugStatusCode(LOG_TAG, statusCode); + debugResponse(LOG_TAG, responseString); + } + }; + } + + @Override + public String getDefaultURL() { + return "https://httpbin.org/post"; + } + + @Override + public boolean isRequestHeadersAllowed() { + return true; + } + + @Override + public boolean isRequestBodyAllowed() { + return false; + } + + @Override + public int getSampleTitle() { + return R.string.title_content_type_http_entity; + } + + @Override + public RequestHandle executeSample(AsyncHttpClient client, String URL, Header[] headers, HttpEntity entity, ResponseHandlerInterface responseHandler) { + RequestParams rParams = new RequestParams(); + rParams.put("sample_key", "Sample String"); + try { + File sample_file = File.createTempFile("temp_", "_handled", getCacheDir()); + rParams.put("sample_file", sample_file); + } catch (IOException e) { + Log.e(LOG_TAG, "Cannot add sample file", e); + } + return client.post(this, URL, headers, rParams, "multipart/form-data", responseHandler); + } +} diff --git a/sample/src/main/java/com/loopj/android/http/sample/CustomCASample.java b/sample/src/main/java/com/loopj/android/http/sample/CustomCASample.java new file mode 100644 index 000000000..2a3798ca2 --- /dev/null +++ b/sample/src/main/java/com/loopj/android/http/sample/CustomCASample.java @@ -0,0 +1,202 @@ +/* + Android Asynchronous Http Client Sample + Copyright (c) 2014 Marek Sebera + https://github.com/android-async-http/android-async-http + + 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 + + https://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.loopj.android.http.sample; + +import android.app.AlertDialog; +import android.content.DialogInterface; +import android.content.res.Resources; +import android.os.Bundle; +import android.util.Log; + +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.loopj.android.http.AsyncHttpClient; +import com.loopj.android.http.BaseJsonHttpResponseHandler; +import com.loopj.android.http.RequestHandle; +import com.loopj.android.http.ResponseHandlerInterface; +import com.loopj.android.http.sample.util.SampleJSON; +import com.loopj.android.http.sample.util.SecureSocketFactory; + +import java.io.IOException; +import java.io.InputStream; +import java.security.KeyManagementException; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.UnrecoverableKeyException; +import java.security.cert.CertificateException; + +import cz.msebera.android.httpclient.Header; +import cz.msebera.android.httpclient.HttpEntity; + +/** + * This sample demonstrates the implementation of self-signed CA's and connection to servers with + * such certificates. Be sure to read 'res/raw/custom_ca.txt' for how-to instructions on how to + * generate a BKS file necessary for this sample. + * + * @author Noor Dawod + */ +public class CustomCASample extends SampleParentActivity { + + private static final String LOG_TAG = "CustomCASample"; + + // This is A TEST URL for use with AsyncHttpClient LIBRARY ONLY! + // It is provided courtesy of Fineswap (https://fineswap.com) and must never + // be used in ANY program except when running this sample (CustomCASample). + private static final String SERVER_TEST_URL = "https://api.fineswap.io/ahc"; + + // The certificate's alias. + private static final String STORE_ALIAS = "rootca"; + + // The certificate's password. + private static final String STORE_PASS = "Fineswap"; + + // Instruct the library to retry connection when this exception is raised. + static { + AsyncHttpClient.allowRetryExceptionClass(javax.net.ssl.SSLException.class); + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + try { + InputStream is = null; + try { + // Configure the library to use a custom 'bks' file to perform + // SSL negotiation. + KeyStore store = KeyStore.getInstance(KeyStore.getDefaultType()); + is = getResources().openRawResource(R.raw.store); + store.load(is, STORE_PASS.toCharArray()); + getAsyncHttpClient().setSSLSocketFactory(new SecureSocketFactory(store, STORE_ALIAS)); + } catch (IOException e) { + throw new KeyStoreException(e); + } catch (CertificateException e) { + throw new KeyStoreException(e); + } catch (NoSuchAlgorithmException e) { + throw new KeyStoreException(e); + } catch (KeyManagementException e) { + throw new KeyStoreException(e); + } catch (UnrecoverableKeyException e) { + throw new KeyStoreException(e); + } finally { + AsyncHttpClient.silentCloseInputStream(is); + } + } catch (KeyStoreException e) { + Log.e(LOG_TAG, "Unable to initialize key store", e); + showCustomCAHelp(); + } + } + + @Override + public int getSampleTitle() { + return R.string.title_custom_ca; + } + + @Override + public boolean isRequestBodyAllowed() { + return false; + } + + @Override + public boolean isRequestHeadersAllowed() { + return false; + } + + @Override + public String getDefaultURL() { + return SERVER_TEST_URL; + } + + @Override + public ResponseHandlerInterface getResponseHandler() { + return new BaseJsonHttpResponseHandler() { + + @Override + public void onStart() { + clearOutputs(); + } + + @Override + public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, SampleJSON response) { + debugHeaders(LOG_TAG, headers); + debugStatusCode(LOG_TAG, statusCode); + if (response != null) { + debugResponse(LOG_TAG, rawJsonResponse); + } + } + + @Override + public void onFailure(int statusCode, Header[] headers, Throwable throwable, String rawJsonData, SampleJSON errorResponse) { + debugHeaders(LOG_TAG, headers); + debugStatusCode(LOG_TAG, statusCode); + debugThrowable(LOG_TAG, throwable); + if (errorResponse != null) { + debugResponse(LOG_TAG, rawJsonData); + } + } + + @Override + protected SampleJSON parseResponse(String rawJsonData, boolean isFailure) throws Throwable { + return new ObjectMapper().readValues(new JsonFactory().createParser(rawJsonData), SampleJSON.class).next(); + } + }; + } + + @Override + public RequestHandle executeSample(AsyncHttpClient client, String URL, Header[] headers, HttpEntity entity, ResponseHandlerInterface responseHandler) { + return client.get(this, URL, headers, null, responseHandler); + } + + /** + * Returns contents of `custom_ca.txt` file from assets as CharSequence. + * + * @return contents of custom_ca.txt file + */ + private CharSequence getReadmeText() { + String rtn = ""; + try { + InputStream stream = getResources().openRawResource(R.raw.custom_ca); + java.util.Scanner s = new java.util.Scanner(stream) + .useDelimiter("\\A"); + rtn = s.hasNext() ? s.next() : ""; + } catch (Resources.NotFoundException e) { + Log.e(LOG_TAG, "License couldn't be retrieved", e); + } + return rtn; + } + + /** + * Displays a dialog showing contents of `custom_ca.txt` file from assets. + * This is needed to avoid Lint's strict mode. + */ + private void showCustomCAHelp() { + AlertDialog.Builder builder = new AlertDialog.Builder(this); + builder.setTitle(R.string.title_custom_ca); + builder.setMessage(getReadmeText()); + builder.setNeutralButton(android.R.string.cancel, + new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + dialog.dismiss(); + } + } + ); + builder.show(); + } +} diff --git a/sample/src/main/java/com/loopj/android/http/sample/DeleteSample.java b/sample/src/main/java/com/loopj/android/http/sample/DeleteSample.java new file mode 100755 index 000000000..69f443496 --- /dev/null +++ b/sample/src/main/java/com/loopj/android/http/sample/DeleteSample.java @@ -0,0 +1,85 @@ +/* + Android Asynchronous Http Client Sample + Copyright (c) 2014 Marek Sebera + https://github.com/android-async-http/android-async-http + + 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 + + https://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.loopj.android.http.sample; + +import com.loopj.android.http.AsyncHttpClient; +import com.loopj.android.http.AsyncHttpResponseHandler; +import com.loopj.android.http.RequestHandle; +import com.loopj.android.http.ResponseHandlerInterface; + +import cz.msebera.android.httpclient.Header; +import cz.msebera.android.httpclient.HttpEntity; + +public class DeleteSample extends SampleParentActivity { + private static final String LOG_TAG = "DeleteSample"; + + @Override + public RequestHandle executeSample(AsyncHttpClient client, String URL, Header[] headers, HttpEntity entity, ResponseHandlerInterface responseHandler) { + return client.delete(this, URL, headers, null, responseHandler); + } + + @Override + public int getSampleTitle() { + return R.string.title_delete_sample; + } + + @Override + public boolean isRequestBodyAllowed() { + // HttpDelete is not HttpEntityEnclosingRequestBase, thus cannot contain body + return false; + } + + @Override + public boolean isRequestHeadersAllowed() { + return true; + } + + @Override + public String getDefaultURL() { + return PROTOCOL + "httpbin.org/delete"; + } + + @Override + public ResponseHandlerInterface getResponseHandler() { + return new AsyncHttpResponseHandler() { + + @Override + public void onStart() { + clearOutputs(); + } + + @Override + public void onSuccess(int statusCode, Header[] headers, byte[] response) { + debugHeaders(LOG_TAG, headers); + debugStatusCode(LOG_TAG, statusCode); + debugResponse(LOG_TAG, new String(response)); + } + + @Override + public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) { + debugHeaders(LOG_TAG, headers); + debugStatusCode(LOG_TAG, statusCode); + debugThrowable(LOG_TAG, e); + if (errorResponse != null) { + debugResponse(LOG_TAG, new String(errorResponse)); + } + } + }; + } +} diff --git a/sample/src/main/java/com/loopj/android/http/sample/DigestAuthSample.java b/sample/src/main/java/com/loopj/android/http/sample/DigestAuthSample.java new file mode 100644 index 000000000..e4b64575a --- /dev/null +++ b/sample/src/main/java/com/loopj/android/http/sample/DigestAuthSample.java @@ -0,0 +1,75 @@ +package com.loopj.android.http.sample; + +import android.net.Uri; +import android.os.Bundle; +import android.widget.EditText; + +import com.loopj.android.http.AsyncHttpClient; +import com.loopj.android.http.RequestHandle; +import com.loopj.android.http.ResponseHandlerInterface; + +import cz.msebera.android.httpclient.Header; +import cz.msebera.android.httpclient.HttpEntity; +import cz.msebera.android.httpclient.auth.AuthScope; +import cz.msebera.android.httpclient.auth.UsernamePasswordCredentials; + +public class DigestAuthSample extends GetSample { + + private EditText usernameField, passwordField; + + @Override + public String getDefaultURL() { + return PROTOCOL + "httpbin.org/digest-auth/auth/user/passwd2"; + } + + @Override + public int getSampleTitle() { + return R.string.title_digest_auth; + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + usernameField = new EditText(this); + passwordField = new EditText(this); + usernameField.setHint("Username"); + passwordField.setHint("Password"); + usernameField.setText("user"); + passwordField.setText("passwd2"); + customFieldsLayout.addView(usernameField); + customFieldsLayout.addView(passwordField); + } + + @Override + public RequestHandle executeSample(AsyncHttpClient client, String URL, Header[] headers, HttpEntity entity, ResponseHandlerInterface responseHandler) { + setCredentials(client, URL); + return client.get(this, URL, headers, null, responseHandler); + } + + @Override + public boolean isCancelButtonAllowed() { + return true; + } + + @Override + public boolean isRequestHeadersAllowed() { + return true; + } + + @Override + public boolean isRequestBodyAllowed() { + return false; + } + + private void setCredentials(AsyncHttpClient client, String URL) { + Uri parsed = Uri.parse(URL); + client.clearCredentialsProvider(); + client.setCredentials( + new AuthScope(parsed.getHost(), parsed.getPort() == -1 ? 80 : parsed.getPort()), + new UsernamePasswordCredentials( + usernameField.getText().toString(), + passwordField.getText().toString() + ) + ); + } +} diff --git a/sample/src/main/java/com/loopj/android/http/sample/DirectorySample.java b/sample/src/main/java/com/loopj/android/http/sample/DirectorySample.java new file mode 100755 index 000000000..37b3f986d --- /dev/null +++ b/sample/src/main/java/com/loopj/android/http/sample/DirectorySample.java @@ -0,0 +1,136 @@ +/* + Android Asynchronous Http Client Sample + Copyright (c) 2014 Marek Sebera + https://github.com/android-async-http/android-async-http + + 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 + + https://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.loopj.android.http.sample; + +import android.os.Bundle; +import android.util.Log; +import android.view.View; +import android.widget.Button; +import android.widget.CheckBox; + +import com.loopj.android.http.AsyncHttpClient; +import com.loopj.android.http.FileAsyncHttpResponseHandler; +import com.loopj.android.http.RequestHandle; +import com.loopj.android.http.ResponseHandlerInterface; +import com.loopj.android.http.sample.util.FileUtil; + +import java.io.File; + +import java.util.Locale; + +import cz.msebera.android.httpclient.Header; +import cz.msebera.android.httpclient.HttpEntity; + +public class DirectorySample extends SampleParentActivity { + private static final String LOG_TAG = "DirectorySample"; + private FileAsyncHttpResponseHandler lastResponseHandler = null; + private CheckBox cbAppend, cbRename; + + @Override + public int getSampleTitle() { + return R.string.title_directory_sample; + } + + @Override + public boolean isRequestBodyAllowed() { + return false; + } + + @Override + public boolean isRequestHeadersAllowed() { + return true; + } + + @Override + public String getDefaultURL() { + return "https://httpbin.org/robots.txt"; + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + Button deleteTargetFile = new Button(this); + deleteTargetFile.setText(R.string.button_delete_target_file); + deleteTargetFile.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + clearOutputs(); + if (lastResponseHandler != null) { + File toBeDeleted = lastResponseHandler.getTargetFile(); + debugResponse(LOG_TAG, String.format(Locale.US, "File was deleted? %b", toBeDeleted.delete())); + debugResponse(LOG_TAG, String.format(Locale.US, "Delete file path: %s", toBeDeleted.getAbsolutePath())); + } else { + debugThrowable(LOG_TAG, new Error("You have to Run example first")); + } + } + }); + cbAppend = new CheckBox(this); + cbAppend.setText("Constructor \"append\" is true?"); + cbAppend.setChecked(false); + cbRename = new CheckBox(this); + cbRename.setText("Constructor \"renameTargetFileIfExists\" is true?"); + cbRename.setChecked(true); + customFieldsLayout.addView(deleteTargetFile); + customFieldsLayout.addView(cbAppend); + customFieldsLayout.addView(cbRename); + } + + @Override + public ResponseHandlerInterface getResponseHandler() { + lastResponseHandler = new FileAsyncHttpResponseHandler(getCacheDir(), cbAppend.isChecked(), cbRename.isChecked()) { + @Override + public void onStart() { + clearOutputs(); + } + + @Override + public void onSuccess(int statusCode, Header[] headers, File response) { + debugHeaders(LOG_TAG, headers); + debugStatusCode(LOG_TAG, statusCode); + debugFile(response); + } + + @Override + public void onFailure(int statusCode, Header[] headers, Throwable throwable, File file) { + debugHeaders(LOG_TAG, headers); + debugStatusCode(LOG_TAG, statusCode); + debugThrowable(LOG_TAG, throwable); + debugFile(file); + } + + private void debugFile(File file) { + if (file == null || !file.exists()) { + debugResponse(LOG_TAG, "Response is null"); + return; + } + try { + debugResponse(LOG_TAG, file.getAbsolutePath() + "\r\n\r\n" + FileUtil.getStringFromFile(file)); + } catch (Throwable t) { + Log.e(LOG_TAG, "Cannot debug file contents", t); + } + } + }; + return lastResponseHandler; + } + + @Override + public RequestHandle executeSample(AsyncHttpClient client, String URL, Header[] headers, HttpEntity entity, ResponseHandlerInterface responseHandler) { + return client.get(this, URL, headers, null, responseHandler); + } +} diff --git a/sample/src/main/java/com/loopj/android/http/sample/FileSample.java b/sample/src/main/java/com/loopj/android/http/sample/FileSample.java new file mode 100755 index 000000000..c06f9c480 --- /dev/null +++ b/sample/src/main/java/com/loopj/android/http/sample/FileSample.java @@ -0,0 +1,101 @@ +/* + Android Asynchronous Http Client Sample + Copyright (c) 2014 Marek Sebera + https://github.com/android-async-http/android-async-http + + 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 + + https://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.loopj.android.http.sample; + +import android.util.Log; + +import com.loopj.android.http.AsyncHttpClient; +import com.loopj.android.http.FileAsyncHttpResponseHandler; +import com.loopj.android.http.RequestHandle; +import com.loopj.android.http.ResponseHandlerInterface; +import com.loopj.android.http.sample.util.FileUtil; + +import java.io.File; + +import cz.msebera.android.httpclient.Header; +import cz.msebera.android.httpclient.HttpEntity; + +public class FileSample extends SampleParentActivity { + private static final String LOG_TAG = "FileSample"; + + @Override + public int getSampleTitle() { + return R.string.title_file_sample; + } + + @Override + public boolean isRequestBodyAllowed() { + return false; + } + + @Override + public boolean isRequestHeadersAllowed() { + return true; + } + + @Override + public String getDefaultURL() { + return "https://httpbin.org/robots.txt"; + } + + @Override + public ResponseHandlerInterface getResponseHandler() { + return new FileAsyncHttpResponseHandler(this) { + @Override + public void onStart() { + clearOutputs(); + } + + @Override + public void onSuccess(int statusCode, Header[] headers, File response) { + debugHeaders(LOG_TAG, headers); + debugStatusCode(LOG_TAG, statusCode); + debugFile(response); + } + + @Override + public void onFailure(int statusCode, Header[] headers, Throwable throwable, File file) { + debugHeaders(LOG_TAG, headers); + debugStatusCode(LOG_TAG, statusCode); + debugThrowable(LOG_TAG, throwable); + debugFile(file); + } + + private void debugFile(File file) { + if (file == null || !file.exists()) { + debugResponse(LOG_TAG, "Response is null"); + return; + } + try { + debugResponse(LOG_TAG, file.getAbsolutePath() + "\r\n\r\n" + FileUtil.getStringFromFile(file)); + } catch (Throwable t) { + Log.e(LOG_TAG, "Cannot debug file contents", t); + } + if (!deleteTargetFile()) { + Log.d(LOG_TAG, "Could not delete response file " + file.getAbsolutePath()); + } + } + }; + } + + @Override + public RequestHandle executeSample(AsyncHttpClient client, String URL, Header[] headers, HttpEntity entity, ResponseHandlerInterface responseHandler) { + return client.get(this, URL, headers, null, responseHandler); + } +} diff --git a/sample/src/main/java/com/loopj/android/http/sample/FilesSample.java b/sample/src/main/java/com/loopj/android/http/sample/FilesSample.java new file mode 100644 index 000000000..6eff61066 --- /dev/null +++ b/sample/src/main/java/com/loopj/android/http/sample/FilesSample.java @@ -0,0 +1,67 @@ +package com.loopj.android.http.sample; + +import android.util.Log; + +import com.loopj.android.http.AsyncHttpClient; +import com.loopj.android.http.RequestHandle; +import com.loopj.android.http.RequestParams; +import com.loopj.android.http.ResponseHandlerInterface; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.util.Random; + +import cz.msebera.android.httpclient.Header; +import cz.msebera.android.httpclient.HttpEntity; + +public class FilesSample extends PostSample { + + public static final String LOG_TAG = "FilesSample"; + + @Override + public int getSampleTitle() { + return R.string.title_post_files; + } + + @Override + public boolean isRequestBodyAllowed() { + return false; + } + + @Override + public RequestHandle executeSample(AsyncHttpClient client, String URL, Header[] headers, HttpEntity entity, ResponseHandlerInterface responseHandler) { + try { + RequestParams params = new RequestParams(); + final String contentType = RequestParams.APPLICATION_OCTET_STREAM; + params.put("fileOne", createTempFile("fileOne", 1020), contentType, "fileOne"); + params.put("fileTwo", createTempFile("fileTwo", 1030), contentType); + params.put("fileThree", createTempFile("fileThree", 1040), contentType, "customFileThree"); + params.put("fileFour", createTempFile("fileFour", 1050), contentType); + params.put("fileFive", createTempFile("fileFive", 1060), contentType, "testingFileFive"); + params.setHttpEntityIsRepeatable(true); + params.setUseJsonStreamer(false); + return client.post(this, URL, params, responseHandler); + } catch (FileNotFoundException fnfException) { + Log.e(LOG_TAG, "executeSample failed with FileNotFoundException", fnfException); + } + return null; + } + + public File createTempFile(String namePart, int byteSize) { + try { + File f = File.createTempFile(namePart, "_handled", getCacheDir()); + FileOutputStream fos = new FileOutputStream(f); + Random r = new Random(); + byte[] buffer = new byte[byteSize]; + r.nextBytes(buffer); + fos.write(buffer); + fos.flush(); + fos.close(); + return f; + } catch (Throwable t) { + Log.e(LOG_TAG, "createTempFile failed", t); + } + return null; + } +} diff --git a/sample/src/main/java/com/loopj/android/http/sample/GetSample.java b/sample/src/main/java/com/loopj/android/http/sample/GetSample.java new file mode 100755 index 000000000..27b0be0e0 --- /dev/null +++ b/sample/src/main/java/com/loopj/android/http/sample/GetSample.java @@ -0,0 +1,96 @@ +/* + Android Asynchronous Http Client Sample + Copyright (c) 2014 Marek Sebera + https://github.com/android-async-http/android-async-http + + 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 + + https://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.loopj.android.http.sample; + +import android.widget.Toast; + +import com.loopj.android.http.AsyncHttpClient; +import com.loopj.android.http.AsyncHttpResponseHandler; +import com.loopj.android.http.RequestHandle; +import com.loopj.android.http.ResponseHandlerInterface; + +import java.util.Locale; + +import cz.msebera.android.httpclient.Header; +import cz.msebera.android.httpclient.HttpEntity; + +public class GetSample extends SampleParentActivity { + private static final String LOG_TAG = "GetSample"; + + @Override + public RequestHandle executeSample(AsyncHttpClient client, String URL, Header[] headers, HttpEntity entity, ResponseHandlerInterface responseHandler) { + return client.get(this, URL, headers, null, responseHandler); + } + + @Override + public int getSampleTitle() { + return R.string.title_get_sample; + } + + @Override + public boolean isRequestBodyAllowed() { + return false; + } + + @Override + public boolean isRequestHeadersAllowed() { + return true; + } + + @Override + public String getDefaultURL() { + return "https://httpbin.org/get"; + } + + @Override + public ResponseHandlerInterface getResponseHandler() { + return new AsyncHttpResponseHandler() { + + @Override + public void onStart() { + clearOutputs(); + } + + @Override + public void onSuccess(int statusCode, Header[] headers, byte[] response) { + debugHeaders(LOG_TAG, headers); + debugStatusCode(LOG_TAG, statusCode); + debugResponse(LOG_TAG, new String(response)); + } + + @Override + public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) { + debugHeaders(LOG_TAG, headers); + debugStatusCode(LOG_TAG, statusCode); + debugThrowable(LOG_TAG, e); + if (errorResponse != null) { + debugResponse(LOG_TAG, new String(errorResponse)); + } + } + + @Override + public void onRetry(int retryNo) { + Toast.makeText(GetSample.this, + String.format(Locale.US, "Request is retried, retry no. %d", retryNo), + Toast.LENGTH_SHORT) + .show(); + } + }; + } +} diff --git a/sample/src/main/java/com/loopj/android/http/sample/GzipSample.java b/sample/src/main/java/com/loopj/android/http/sample/GzipSample.java new file mode 100644 index 000000000..8da1c9372 --- /dev/null +++ b/sample/src/main/java/com/loopj/android/http/sample/GzipSample.java @@ -0,0 +1,32 @@ +/* + Android Asynchronous Http Client Sample + Copyright (c) 2014 Marek Sebera + https://github.com/android-async-http/android-async-http + + 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 + + https://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.loopj.android.http.sample; + +public class GzipSample extends JsonSample { + + @Override + public int getSampleTitle() { + return R.string.title_gzip_sample; + } + + @Override + public String getDefaultURL() { + return PROTOCOL + "httpbin.org/gzip"; + } +} diff --git a/sample/src/main/java/com/loopj/android/http/sample/HeadSample.java b/sample/src/main/java/com/loopj/android/http/sample/HeadSample.java new file mode 100644 index 000000000..d3a6d0dcb --- /dev/null +++ b/sample/src/main/java/com/loopj/android/http/sample/HeadSample.java @@ -0,0 +1,61 @@ +/* + Copyright (c) 2015 Marek Sebera + + 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 + + https://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.loopj.android.http.sample; + +import com.loopj.android.http.AsyncHttpClient; +import com.loopj.android.http.AsyncHttpResponseHandler; +import com.loopj.android.http.RequestHandle; +import com.loopj.android.http.ResponseHandlerInterface; + +import cz.msebera.android.httpclient.Header; +import cz.msebera.android.httpclient.HttpEntity; + +import java.util.Locale; + +public class HeadSample extends FileSample { + + private static final String LOG_TAG = "HeadSample"; + + @Override + public ResponseHandlerInterface getResponseHandler() { + return new AsyncHttpResponseHandler() { + @Override + public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { + debugStatusCode(LOG_TAG, statusCode); + debugHeaders(LOG_TAG, headers); + debugResponse(LOG_TAG, String.format(Locale.US, "Response of size: %d", responseBody == null ? 0 : responseBody.length)); + } + + @Override + public void onProgress(long bytesWritten, long totalSize) { + addView(getColoredView(LIGHTRED, String.format(Locale.US, "Progress %d from %d", bytesWritten, totalSize))); + } + + @Override + public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable throwable) { + debugStatusCode(LOG_TAG, statusCode); + debugHeaders(LOG_TAG, headers); + debugThrowable(LOG_TAG, throwable); + debugResponse(LOG_TAG, String.format(Locale.US, "Response of size: %d", responseBody == null ? 0 : responseBody.length)); + } + }; + } + + @Override + public RequestHandle executeSample(AsyncHttpClient client, String URL, Header[] headers, HttpEntity entity, ResponseHandlerInterface responseHandler) { + return client.head(this, URL, headers, null, responseHandler); + } +} diff --git a/sample/src/main/java/com/loopj/android/http/sample/Http401AuthSample.java b/sample/src/main/java/com/loopj/android/http/sample/Http401AuthSample.java new file mode 100644 index 000000000..93db38c3c --- /dev/null +++ b/sample/src/main/java/com/loopj/android/http/sample/Http401AuthSample.java @@ -0,0 +1,228 @@ +/* + Android Asynchronous Http Client Sample + Copyright (c) 2014 Marek Sebera + https://github.com/android-async-http/android-async-http + + 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 + + https://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.loopj.android.http.sample; + +import android.app.AlertDialog; +import android.content.DialogInterface; +import android.util.Log; +import android.view.LayoutInflater; +import android.view.View; +import android.widget.EditText; +import android.widget.LinearLayout; +import android.widget.TextView; + +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.loopj.android.http.AsyncHttpClient; +import com.loopj.android.http.Base64; +import com.loopj.android.http.BaseJsonHttpResponseHandler; +import com.loopj.android.http.RequestHandle; +import com.loopj.android.http.ResponseHandlerInterface; +import com.loopj.android.http.sample.util.SampleJSON; + +import java.util.List; +import java.util.Locale; + +import cz.msebera.android.httpclient.Header; +import cz.msebera.android.httpclient.HttpEntity; +import cz.msebera.android.httpclient.message.BasicHeader; + +/** + * This sample demonstrates how to implement HTTP 401 Basic Authentication. + * + * @author Noor Dawod + */ +public class Http401AuthSample extends GetSample { + + private static final String LOG_TAG = "Http401AuthSample"; + private static final String HEADER_WWW_AUTHENTICATE = "WWW-Authenticate"; + private static final String HEADER_AUTHORIZATION = "Authorization"; + private static final String HEADER_REALM_PREFIX = "realm="; + private static final String HEADER_BASIC = "basic"; + + private static final String SECRET_USERNAME = "ahc"; + private static final String SECRET_PASSWORD = "LetMeIn"; + + private String userName; + private String passWord; + + public void retryRequest() { + // File is still smaller than remote file; send a new request. + onRunButtonPressed(); + } + + @Override + public String getDefaultURL() { + return PROTOCOL + "httpbin.org/basic-auth/" + SECRET_USERNAME + "/" + SECRET_PASSWORD; + } + + @Override + public int getSampleTitle() { + return R.string.title_401_unauth; + } + + @Override + public RequestHandle executeSample(AsyncHttpClient client, String URL, Header[] headers, HttpEntity entity, ResponseHandlerInterface responseHandler) { + return client.get(this, URL, headers, null, responseHandler); + } + + @Override + public Header[] getRequestHeaders() { + List
headers = getRequestHeadersList(); + + // Add authentication header. + if (userName != null && passWord != null) { + byte[] base64bytes = Base64.encode( + (userName + ":" + passWord).getBytes(), + Base64.DEFAULT + ); + String credentials = new String(base64bytes); + headers.add(new BasicHeader(HEADER_AUTHORIZATION, HEADER_BASIC + " " + credentials)); + } + + return headers.toArray(new Header[headers.size()]); + } + + @Override + public ResponseHandlerInterface getResponseHandler() { + return new BaseJsonHttpResponseHandler() { + + @Override + public void onStart() { + clearOutputs(); + } + + @Override + public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, SampleJSON response) { + debugHeaders(LOG_TAG, headers); + debugStatusCode(LOG_TAG, statusCode); + if (response != null) { + debugResponse(LOG_TAG, rawJsonResponse); + } + } + + @Override + public void onFailure(int statusCode, Header[] headers, Throwable throwable, String rawJsonData, SampleJSON errorResponse) { + debugHeaders(LOG_TAG, headers); + debugStatusCode(LOG_TAG, statusCode); + debugThrowable(LOG_TAG, throwable); + + // Ask the user for credentials if required by the server. + if (statusCode == 401) { + String realm = "Protected Page"; + String authType = null; + + // Cycle through the headers and look for the WWW-Authenticate header. + for (Header header : headers) { + String headerName = header.getName(); + if (HEADER_WWW_AUTHENTICATE.equalsIgnoreCase(headerName)) { + String headerValue = header.getValue().trim(); + String headerValueLowerCase = headerValue.toLowerCase(Locale.US); + + // Get the type of auth requested. + int charPos = headerValueLowerCase.indexOf(' '); + if (0 < charPos) { + authType = headerValueLowerCase.substring(0, charPos); + + // The second part should begin with a "realm=" prefix. + if (headerValueLowerCase.substring(1 + charPos).startsWith(HEADER_REALM_PREFIX)) { + // The new realm value, including any possible wrapping quotation. + realm = headerValue.substring(1 + charPos + HEADER_REALM_PREFIX.length()); + + // If realm starts with a quote, remove surrounding quotes. + if (realm.charAt(0) == '"' || realm.charAt(0) == '\'') { + realm = realm.substring(1, realm.length() - 1); + } + } + } + } + } + + // We will support basic auth in this sample. + if (authType != null && HEADER_BASIC.equals(authType)) { + // Show a dialog for the user and request user/pass. + Log.d(LOG_TAG, HEADER_REALM_PREFIX + realm); + + // Present the dialog. + postRunnable(new DialogRunnable(realm)); + } + } + } + + @Override + protected SampleJSON parseResponse(String rawJsonData, boolean isFailure) throws Throwable { + return new ObjectMapper().readValues(new JsonFactory().createParser(rawJsonData), SampleJSON.class).next(); + } + }; + } + + private class DialogRunnable implements Runnable, DialogInterface.OnClickListener { + + final String realm; + final View dialogView; + + public DialogRunnable(String realm) { + this.realm = realm; + this.dialogView = LayoutInflater + .from(Http401AuthSample.this) + .inflate(R.layout.credentials, new LinearLayout(Http401AuthSample.this), false); + + // Update the preface text with correct credentials. + TextView preface = (TextView) dialogView.findViewById(R.id.label_credentials); + String prefaceText = preface.getText().toString(); + + // Substitute placeholders, and re-set the value. + preface.setText(String.format(Locale.US, prefaceText, SECRET_USERNAME, SECRET_PASSWORD)); + } + + @Override + public void run() { + AlertDialog.Builder builder = new AlertDialog.Builder(Http401AuthSample.this); + builder.setTitle(realm); + builder.setView(dialogView); + builder.setPositiveButton(android.R.string.ok, this); + builder.setNegativeButton(android.R.string.cancel, this); + builder.show(); + } + + @Override + public void onClick(DialogInterface dialog, int which) { + switch (which) { + case DialogInterface.BUTTON_POSITIVE: + // Dismiss the dialog. + dialog.dismiss(); + + // Update the username and password variables. + userName = ((EditText) dialogView.findViewById(R.id.field_username)).getText().toString(); + passWord = ((EditText) dialogView.findViewById(R.id.field_password)).getText().toString(); + + // Refetch the remote file. + retryRequest(); + + break; + + case DialogInterface.BUTTON_NEGATIVE: + // Dismiss the dialog. + dialog.dismiss(); + + break; + } + } + } +} diff --git a/sample/src/main/java/com/loopj/android/http/sample/IntentServiceSample.java b/sample/src/main/java/com/loopj/android/http/sample/IntentServiceSample.java new file mode 100644 index 000000000..718529d4a --- /dev/null +++ b/sample/src/main/java/com/loopj/android/http/sample/IntentServiceSample.java @@ -0,0 +1,106 @@ +package com.loopj.android.http.sample; + +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; + +import com.loopj.android.http.AsyncHttpClient; +import com.loopj.android.http.RequestHandle; +import com.loopj.android.http.ResponseHandlerInterface; +import com.loopj.android.http.sample.services.ExampleIntentService; +import com.loopj.android.http.sample.util.IntentUtil; + +import cz.msebera.android.httpclient.Header; +import cz.msebera.android.httpclient.HttpEntity; + +public class IntentServiceSample extends SampleParentActivity { + + public static final String LOG_TAG = "IntentServiceSample"; + public static final String ACTION_START = "SYNC_START"; + public static final String ACTION_RETRY = "SYNC_RETRY"; + public static final String ACTION_CANCEL = "SYNC_CANCEL"; + public static final String ACTION_SUCCESS = "SYNC_SUCCESS"; + public static final String ACTION_FAILURE = "SYNC_FAILURE"; + public static final String ACTION_FINISH = "SYNC_FINISH"; + public static final String[] ALLOWED_ACTIONS = {ACTION_START, + ACTION_RETRY, ACTION_CANCEL, ACTION_SUCCESS, ACTION_FAILURE, ACTION_FINISH}; + private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() { + @Override + public void onReceive(Context context, Intent intent) { + String action = intent.getAction(); + + // switch() doesn't support strings in older JDK. + if (ACTION_START.equals(action)) { + clearOutputs(); + addView(getColoredView(LIGHTBLUE, "Request started")); + } else if (ACTION_FINISH.equals(action)) { + addView(getColoredView(LIGHTBLUE, "Request finished")); + } else if (ACTION_CANCEL.equals(action)) { + addView(getColoredView(LIGHTBLUE, "Request cancelled")); + } else if (ACTION_RETRY.equals(action)) { + addView(getColoredView(LIGHTBLUE, "Request retried")); + } else if (ACTION_FAILURE.equals(action) || ACTION_SUCCESS.equals(action)) { + debugThrowable(LOG_TAG, (Throwable) intent.getSerializableExtra(ExampleIntentService.INTENT_THROWABLE)); + if (ACTION_SUCCESS.equals(action)) { + debugStatusCode(LOG_TAG, intent.getIntExtra(ExampleIntentService.INTENT_STATUS_CODE, 0)); + debugHeaders(LOG_TAG, IntentUtil.deserializeHeaders(intent.getStringArrayExtra(ExampleIntentService.INTENT_HEADERS))); + byte[] returnedBytes = intent.getByteArrayExtra(ExampleIntentService.INTENT_DATA); + if (returnedBytes != null) { + debugResponse(LOG_TAG, new String(returnedBytes)); + } + } + } + } + }; + + @Override + protected void onStart() { + super.onStart(); + IntentFilter iFilter = new IntentFilter(); + for (String action : ALLOWED_ACTIONS) { + iFilter.addAction(action); + } + registerReceiver(broadcastReceiver, iFilter); + } + + @Override + protected void onPause() { + super.onPause(); + unregisterReceiver(broadcastReceiver); + } + + @Override + public ResponseHandlerInterface getResponseHandler() { + // no response handler on activity + return null; + } + + @Override + public String getDefaultURL() { + return "https://httpbin.org/get"; + } + + @Override + public boolean isRequestHeadersAllowed() { + return false; + } + + @Override + public boolean isRequestBodyAllowed() { + return false; + } + + @Override + public int getSampleTitle() { + return R.string.title_intent_service_sample; + } + + @Override + public RequestHandle executeSample(AsyncHttpClient client, String URL, Header[] headers, HttpEntity entity, ResponseHandlerInterface responseHandler) { + Intent serviceCall = new Intent(this, ExampleIntentService.class); + serviceCall.putExtra(ExampleIntentService.INTENT_URL, URL); + startService(serviceCall); + return null; + } +} diff --git a/sample/src/main/java/com/loopj/android/http/sample/JsonSample.java b/sample/src/main/java/com/loopj/android/http/sample/JsonSample.java new file mode 100755 index 000000000..59469ea9d --- /dev/null +++ b/sample/src/main/java/com/loopj/android/http/sample/JsonSample.java @@ -0,0 +1,96 @@ +/* + Android Asynchronous Http Client Sample + Copyright (c) 2014 Marek Sebera + https://github.com/android-async-http/android-async-http + + 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 + + https://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.loopj.android.http.sample; + +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.loopj.android.http.AsyncHttpClient; +import com.loopj.android.http.BaseJsonHttpResponseHandler; +import com.loopj.android.http.RequestHandle; +import com.loopj.android.http.ResponseHandlerInterface; +import com.loopj.android.http.sample.util.SampleJSON; + +import cz.msebera.android.httpclient.Header; +import cz.msebera.android.httpclient.HttpEntity; + +public class JsonSample extends SampleParentActivity { + + private static final String LOG_TAG = "JsonSample"; + + @Override + public RequestHandle executeSample(AsyncHttpClient client, String URL, Header[] headers, HttpEntity entity, ResponseHandlerInterface responseHandler) { + return client.get(this, URL, headers, null, responseHandler); + } + + @Override + public int getSampleTitle() { + return R.string.title_json_sample; + } + + @Override + public boolean isRequestBodyAllowed() { + return false; + } + + @Override + public boolean isRequestHeadersAllowed() { + return false; + } + + @Override + public String getDefaultURL() { + return PROTOCOL + "httpbin.org/headers"; + } + + @Override + public ResponseHandlerInterface getResponseHandler() { + return new BaseJsonHttpResponseHandler() { + + @Override + public void onStart() { + clearOutputs(); + } + + @Override + public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, SampleJSON response) { + debugHeaders(LOG_TAG, headers); + debugStatusCode(LOG_TAG, statusCode); + if (response != null) { + debugResponse(LOG_TAG, rawJsonResponse); + } + } + + @Override + public void onFailure(int statusCode, Header[] headers, Throwable throwable, String rawJsonData, SampleJSON errorResponse) { + debugHeaders(LOG_TAG, headers); + debugStatusCode(LOG_TAG, statusCode); + debugThrowable(LOG_TAG, throwable); + if (errorResponse != null) { + debugResponse(LOG_TAG, rawJsonData); + } + } + + @Override + protected SampleJSON parseResponse(String rawJsonData, boolean isFailure) throws Throwable { + return new ObjectMapper().readValues(new JsonFactory().createParser(rawJsonData), SampleJSON.class).next(); + } + + }; + } +} diff --git a/sample/src/main/java/com/loopj/android/http/sample/JsonStreamerSample.java b/sample/src/main/java/com/loopj/android/http/sample/JsonStreamerSample.java new file mode 100644 index 000000000..4d4d24d03 --- /dev/null +++ b/sample/src/main/java/com/loopj/android/http/sample/JsonStreamerSample.java @@ -0,0 +1,101 @@ +/* + Android Asynchronous Http Client Sample + Copyright (c) 2014 Marek Sebera + https://github.com/android-async-http/android-async-http + + 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 + + https://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.loopj.android.http.sample; + +import android.text.TextUtils; +import android.util.Log; + +import com.loopj.android.http.AsyncHttpClient; +import com.loopj.android.http.RequestHandle; +import com.loopj.android.http.RequestParams; +import com.loopj.android.http.ResponseHandlerInterface; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.Iterator; + +import cz.msebera.android.httpclient.Header; +import cz.msebera.android.httpclient.HttpEntity; + +/** + * This sample demonstrates how to upload JSON data using streams, resulting + * in a low-memory footprint even with extremely large data. + *

+ * Please note: You must prepare a server-side end-point to consume the uploaded + * data. This is because the data is uploaded using "application/json" content + * type and regular methods, expecting a multi-form content type, will fail to + * retrieve the POST'ed data. + * + * @author Noor Dawod + */ +public class JsonStreamerSample extends PostSample { + + private static final String LOG_TAG = "JsonStreamSample"; + + @Override + public RequestHandle executeSample(AsyncHttpClient client, String URL, Header[] headers, HttpEntity entity, ResponseHandlerInterface responseHandler) { + RequestParams params = new RequestParams(); + params.setUseJsonStreamer(true); + JSONObject body; + if (isRequestBodyAllowed() && (body = getBodyTextAsJSON()) != null) { + try { + Iterator keys = body.keys(); + Log.d(LOG_TAG, "JSON data:"); + while (keys.hasNext()) { + String key = (String) keys.next(); + Log.d(LOG_TAG, " " + key + ": " + body.get(key)); + params.put(key, body.get(key).toString()); + } + } catch (JSONException e) { + Log.w(LOG_TAG, "Unable to retrieve a JSON value", e); + } + } + return client.post(this, URL, headers, params, + RequestParams.APPLICATION_JSON, responseHandler); + } + + @Override + public HttpEntity getRequestEntity() { + // Unused in this sample. + return null; + } + + @Override + public int getSampleTitle() { + return R.string.title_json_streamer_sample; + } + + @Override + public boolean isRequestHeadersAllowed() { + return false; + } + + protected JSONObject getBodyTextAsJSON() { + String bodyText = getBodyText(); + if (bodyText != null && !TextUtils.isEmpty(bodyText)) { + try { + return new JSONObject(bodyText); + } catch (JSONException e) { + Log.e(LOG_TAG, "User's data is not a valid JSON object", e); + } + } + return null; + } +} diff --git a/sample/src/main/java/com/loopj/android/http/sample/PatchSample.java b/sample/src/main/java/com/loopj/android/http/sample/PatchSample.java new file mode 100644 index 000000000..10926a551 --- /dev/null +++ b/sample/src/main/java/com/loopj/android/http/sample/PatchSample.java @@ -0,0 +1,68 @@ +package com.loopj.android.http.sample; + +import com.loopj.android.http.AsyncHttpClient; +import com.loopj.android.http.AsyncHttpResponseHandler; +import com.loopj.android.http.RequestHandle; +import com.loopj.android.http.ResponseHandlerInterface; + +import cz.msebera.android.httpclient.Header; +import cz.msebera.android.httpclient.HttpEntity; + +public class PatchSample extends SampleParentActivity { + + private static final String LOG_TAG = "PatchSample"; + + @Override + public RequestHandle executeSample(AsyncHttpClient client, String URL, Header[] headers, HttpEntity entity, ResponseHandlerInterface responseHandler) { + return client.patch(this, URL, entity, null, responseHandler); + } + + @Override + public int getSampleTitle() { + return R.string.title_patch_sample; + } + + @Override + public boolean isRequestBodyAllowed() { + return false; + } + + @Override + public boolean isRequestHeadersAllowed() { + return false; + } + + @Override + public String getDefaultURL() { + return PROTOCOL + "httpbin.org/patch"; + } + + @Override + public ResponseHandlerInterface getResponseHandler() { + return new AsyncHttpResponseHandler() { + @Override + public void onStart() { + clearOutputs(); + } + + @Override + public void onSuccess(int statusCode, Header[] headers, byte[] response) { + debugHeaders(LOG_TAG, headers); + debugStatusCode(LOG_TAG, statusCode); + debugResponse(LOG_TAG, new String(response)); + } + + @Override + public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) { + debugHeaders(LOG_TAG, headers); + debugStatusCode(LOG_TAG, statusCode); + debugThrowable(LOG_TAG, e); + if (errorResponse != null) { + debugResponse(LOG_TAG, new String(errorResponse)); + } + } + }; + } + + +} diff --git a/sample/src/main/java/com/loopj/android/http/sample/PersistentCookiesSample.java b/sample/src/main/java/com/loopj/android/http/sample/PersistentCookiesSample.java new file mode 100644 index 000000000..69a72e2fb --- /dev/null +++ b/sample/src/main/java/com/loopj/android/http/sample/PersistentCookiesSample.java @@ -0,0 +1,121 @@ +/* + Android Asynchronous Http Client Sample + Copyright (c) 2014 Marek Sebera + https://github.com/android-async-http/android-async-http + + 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 + + https://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.loopj.android.http.sample; + +import android.os.Bundle; + +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.loopj.android.http.AsyncHttpClient; +import com.loopj.android.http.BaseJsonHttpResponseHandler; +import com.loopj.android.http.PersistentCookieStore; +import com.loopj.android.http.RequestHandle; +import com.loopj.android.http.ResponseHandlerInterface; +import com.loopj.android.http.sample.util.SampleJSON; + +import cz.msebera.android.httpclient.Header; +import cz.msebera.android.httpclient.HttpEntity; +import cz.msebera.android.httpclient.client.CookieStore; + +public class PersistentCookiesSample extends SampleParentActivity { + + private static final String LOG_TAG = "PersistentCookiesSample"; + + private CookieStore cookieStore; + + @Override + protected void onCreate(Bundle savedInstanceState) { + // Use the application's context so that memory leakage doesn't occur. + cookieStore = new PersistentCookieStore(getApplicationContext()); + + // Set the new cookie store. + getAsyncHttpClient().setCookieStore(cookieStore); + + super.onCreate(savedInstanceState); + } + + @Override + public int getSampleTitle() { + return R.string.title_persistent_cookies; + } + + @Override + public boolean isRequestBodyAllowed() { + return false; + } + + @Override + public boolean isRequestHeadersAllowed() { + return true; + } + + @Override + public String getDefaultURL() { + // The base URL for testing cookies. + String url = PROTOCOL + "httpbin.org/cookies"; + + // If the cookie store is empty, suggest a cookie. + if (cookieStore.getCookies().isEmpty()) { + url += "/set?time=" + System.currentTimeMillis(); + } + + return url; + } + + @Override + public ResponseHandlerInterface getResponseHandler() { + return new BaseJsonHttpResponseHandler() { + @Override + public void onStart() { + clearOutputs(); + } + + @Override + public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, SampleJSON response) { + debugHeaders(LOG_TAG, headers); + debugStatusCode(LOG_TAG, statusCode); + if (response != null) { + debugResponse(LOG_TAG, rawJsonResponse); + } + } + + @Override + public void onFailure(int statusCode, Header[] headers, Throwable throwable, String rawJsonData, SampleJSON errorResponse) { + debugHeaders(LOG_TAG, headers); + debugStatusCode(LOG_TAG, statusCode); + debugThrowable(LOG_TAG, throwable); + if (errorResponse != null) { + debugResponse(LOG_TAG, rawJsonData); + } + } + + @Override + protected SampleJSON parseResponse(String rawJsonData, boolean isFailure) throws Throwable { + return new ObjectMapper().readValues(new JsonFactory().createParser(rawJsonData), SampleJSON.class).next(); + } + }; + } + + @Override + public RequestHandle executeSample(AsyncHttpClient client, String URL, Header[] headers, HttpEntity entity, ResponseHandlerInterface responseHandler) { + client.setEnableRedirects(true); + return client.get(this, URL, headers, null, responseHandler); + } + +} diff --git a/sample/src/main/java/com/loopj/android/http/sample/PostSample.java b/sample/src/main/java/com/loopj/android/http/sample/PostSample.java new file mode 100755 index 000000000..815961f04 --- /dev/null +++ b/sample/src/main/java/com/loopj/android/http/sample/PostSample.java @@ -0,0 +1,85 @@ +/* + Android Asynchronous Http Client Sample + Copyright (c) 2014 Marek Sebera + https://github.com/android-async-http/android-async-http + + 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 + + https://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.loopj.android.http.sample; + +import com.loopj.android.http.AsyncHttpClient; +import com.loopj.android.http.AsyncHttpResponseHandler; +import com.loopj.android.http.RequestHandle; +import com.loopj.android.http.ResponseHandlerInterface; + +import cz.msebera.android.httpclient.Header; +import cz.msebera.android.httpclient.HttpEntity; + +public class PostSample extends SampleParentActivity { + private static final String LOG_TAG = "PostSample"; + + @Override + public RequestHandle executeSample(AsyncHttpClient client, String URL, Header[] headers, HttpEntity entity, ResponseHandlerInterface responseHandler) { + return client.post(this, URL, headers, entity, null, responseHandler); + } + + @Override + public int getSampleTitle() { + return R.string.title_post_sample; + } + + @Override + public boolean isRequestBodyAllowed() { + return true; + } + + @Override + public boolean isRequestHeadersAllowed() { + return true; + } + + @Override + public String getDefaultURL() { + return PROTOCOL + "httpbin.org/post"; + } + + @Override + public ResponseHandlerInterface getResponseHandler() { + return new AsyncHttpResponseHandler() { + + @Override + public void onStart() { + clearOutputs(); + } + + @Override + public void onSuccess(int statusCode, Header[] headers, byte[] response) { + debugHeaders(LOG_TAG, headers); + debugStatusCode(LOG_TAG, statusCode); + debugResponse(LOG_TAG, new String(response)); + } + + @Override + public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) { + debugHeaders(LOG_TAG, headers); + debugStatusCode(LOG_TAG, statusCode); + debugThrowable(LOG_TAG, e); + if (errorResponse != null) { + debugResponse(LOG_TAG, new String(errorResponse)); + } + } + }; + } +} + diff --git a/sample/src/main/java/com/loopj/android/http/sample/PrePostProcessingSample.java b/sample/src/main/java/com/loopj/android/http/sample/PrePostProcessingSample.java new file mode 100644 index 000000000..654dab769 --- /dev/null +++ b/sample/src/main/java/com/loopj/android/http/sample/PrePostProcessingSample.java @@ -0,0 +1,146 @@ +/* + Android Asynchronous Http Client Sample + Copyright (c) 2014 Marek Sebera + https://github.com/android-async-http/android-async-http + + 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 + + https://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.loopj.android.http.sample; + +import android.content.Context; +import android.graphics.Color; +import android.util.Log; + +import com.loopj.android.http.AsyncHttpClient; +import com.loopj.android.http.AsyncHttpRequest; +import com.loopj.android.http.AsyncHttpResponseHandler; +import com.loopj.android.http.RequestHandle; +import com.loopj.android.http.ResponseHandlerInterface; + +import java.util.Locale; + +import cz.msebera.android.httpclient.Header; +import cz.msebera.android.httpclient.HttpEntity; +import cz.msebera.android.httpclient.HttpResponse; +import cz.msebera.android.httpclient.client.methods.HttpUriRequest; +import cz.msebera.android.httpclient.impl.client.AbstractHttpClient; +import cz.msebera.android.httpclient.impl.client.DefaultHttpClient; +import cz.msebera.android.httpclient.protocol.HttpContext; + +public class PrePostProcessingSample extends SampleParentActivity { + + protected static final int LIGHTGREY = Color.parseColor("#E0E0E0"); + protected static final int DARKGREY = Color.parseColor("#888888"); + private static final String LOG_TAG = "PrePostProcessingSample"; + + @Override + public RequestHandle executeSample(AsyncHttpClient client, String URL, Header[] headers, HttpEntity entity, ResponseHandlerInterface responseHandler) { + return client.post(this, URL, headers, entity, null, responseHandler); + } + + @Override + public int getSampleTitle() { + return R.string.title_pre_post_processing; + } + + @Override + public boolean isRequestBodyAllowed() { + return true; + } + + @Override + public boolean isRequestHeadersAllowed() { + return true; + } + + @Override + public String getDefaultURL() { + return PROTOCOL + "httpbin.org/post"; + } + + @Override + public AsyncHttpRequest getHttpRequest(DefaultHttpClient client, HttpContext httpContext, HttpUriRequest uriRequest, String contentType, ResponseHandlerInterface responseHandler, Context context) { + return new PrePostProcessRequest(client, httpContext, uriRequest, responseHandler); + } + + @Override + public ResponseHandlerInterface getResponseHandler() { + return new AsyncHttpResponseHandler() { + + @Override + public void onPreProcessResponse(ResponseHandlerInterface instance, HttpResponse response) { + debugProcessing(LOG_TAG, "Pre", + "Response is about to be pre-processed", LIGHTGREY); + } + + @Override + public void onPostProcessResponse(ResponseHandlerInterface instance, HttpResponse response) { + debugProcessing(LOG_TAG, "Post", + "Response is about to be post-processed", DARKGREY); + } + + @Override + public void onStart() { + clearOutputs(); + } + + @Override + public void onSuccess(int statusCode, Header[] headers, byte[] response) { + debugHeaders(LOG_TAG, headers); + debugStatusCode(LOG_TAG, statusCode); + debugResponse(LOG_TAG, new String(response)); + } + + @Override + public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) { + debugHeaders(LOG_TAG, headers); + debugStatusCode(LOG_TAG, statusCode); + debugThrowable(LOG_TAG, e); + if (errorResponse != null) { + debugResponse(LOG_TAG, new String(errorResponse)); + } + } + }; + } + + protected void debugProcessing(String TAG, String state, String message, final int color) { + final String debugMessage = String.format(Locale.US, "%s-processing: %s", state, message); + Log.d(TAG, debugMessage); + runOnUiThread(new Runnable() { + @Override + public void run() { + addView(getColoredView(color, debugMessage)); + } + }); + } + + private class PrePostProcessRequest extends AsyncHttpRequest { + + public PrePostProcessRequest(AbstractHttpClient client, HttpContext httpContext, HttpUriRequest request, ResponseHandlerInterface responseHandler) { + super(client, httpContext, request, responseHandler); + } + + @Override + public void onPreProcessRequest(AsyncHttpRequest request) { + debugProcessing(LOG_TAG, "Pre", + "Request is about to be pre-processed", LIGHTGREY); + } + + @Override + public void onPostProcessRequest(AsyncHttpRequest request) { + debugProcessing(LOG_TAG, "Post", + "Request is about to be post-processed", DARKGREY); + } + } +} diff --git a/sample/src/main/java/com/loopj/android/http/sample/PutSample.java b/sample/src/main/java/com/loopj/android/http/sample/PutSample.java new file mode 100755 index 000000000..5cab76591 --- /dev/null +++ b/sample/src/main/java/com/loopj/android/http/sample/PutSample.java @@ -0,0 +1,85 @@ +/* + Android Asynchronous Http Client Sample + Copyright (c) 2014 Marek Sebera + https://github.com/android-async-http/android-async-http + + 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 + + https://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.loopj.android.http.sample; + +import com.loopj.android.http.AsyncHttpClient; +import com.loopj.android.http.AsyncHttpResponseHandler; +import com.loopj.android.http.RequestHandle; +import com.loopj.android.http.ResponseHandlerInterface; + +import cz.msebera.android.httpclient.Header; +import cz.msebera.android.httpclient.HttpEntity; + +public class PutSample extends SampleParentActivity { + private static final String LOG_TAG = "PutSample"; + + @Override + public RequestHandle executeSample(AsyncHttpClient client, String URL, Header[] headers, HttpEntity entity, ResponseHandlerInterface responseHandler) { + return client.put(this, URL, headers, entity, null, responseHandler); + } + + @Override + public int getSampleTitle() { + return R.string.title_put_sample; + } + + @Override + public boolean isRequestBodyAllowed() { + return true; + } + + @Override + public boolean isRequestHeadersAllowed() { + return true; + } + + @Override + public String getDefaultURL() { + return PROTOCOL + "httpbin.org/put"; + } + + @Override + public ResponseHandlerInterface getResponseHandler() { + return new AsyncHttpResponseHandler() { + + @Override + public void onStart() { + clearOutputs(); + } + + @Override + public void onSuccess(int statusCode, Header[] headers, byte[] response) { + debugHeaders(LOG_TAG, headers); + debugStatusCode(LOG_TAG, statusCode); + debugResponse(LOG_TAG, new String(response)); + } + + @Override + public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) { + debugHeaders(LOG_TAG, headers); + debugStatusCode(LOG_TAG, statusCode); + debugThrowable(LOG_TAG, e); + if (errorResponse != null) { + debugResponse(LOG_TAG, new String(errorResponse)); + } + } + }; + } + +} diff --git a/sample/src/main/java/com/loopj/android/http/sample/RangeResponseSample.java b/sample/src/main/java/com/loopj/android/http/sample/RangeResponseSample.java new file mode 100644 index 000000000..e7f2e3e84 --- /dev/null +++ b/sample/src/main/java/com/loopj/android/http/sample/RangeResponseSample.java @@ -0,0 +1,183 @@ +/* + Android Asynchronous Http Client Sample + Copyright (c) 2014 Marek Sebera + https://github.com/android-async-http/android-async-http + + 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 + + https://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.loopj.android.http.sample; + +import android.os.Bundle; +import android.util.Log; +import android.widget.Toast; + +import com.loopj.android.http.AsyncHttpClient; +import com.loopj.android.http.RangeFileAsyncHttpResponseHandler; +import com.loopj.android.http.RequestHandle; +import com.loopj.android.http.ResponseHandlerInterface; + +import java.io.File; +import java.io.IOException; + +import java.util.Locale; + +import cz.msebera.android.httpclient.Header; +import cz.msebera.android.httpclient.HttpEntity; +import cz.msebera.android.httpclient.client.methods.HttpUriRequest; + +/** + * This sample demonstrates use of {@link RangeFileAsyncHttpResponseHandler} to + * download a remote file in multiple requests. While this response handler + * class handles file storage, it's up to the app itself to request all chunks + * of the file. + *

+ * Also demonstrated a method to query the remote file's size prior to sending + * the actual GET requests. This ensures that the remote server is actually + * capable of supporting the "Range" header, necessary to make this sample work. + * + * @author Noor Dawod + */ +public class RangeResponseSample extends GetSample { + + public static final String LOG_TAG = "RangeResponseSample"; + + private static final String CONTENT_LENGTH = "Content-Length"; + private static final String ACCEPT_RANGES = "Accept-Ranges"; + private static final int CHUNK_SIZE = 10240; + + private File file; + private long fileSize = -1; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + try { + // Temporary file to host the URL's downloaded contents. + file = File.createTempFile("temp_", "_handled", getCacheDir()); + } catch (IOException e) { + Log.e(LOG_TAG, "Cannot create temporary file", e); + } + } + + @Override + protected void onDestroy() { + super.onDestroy(); + + // Remove temporary file. + if (file != null) { + if (!file.delete()) { + Log.e(LOG_TAG, String.format(Locale.US, "Couldn't remove temporary file in path: %s", file.getAbsolutePath())); + } + file = null; + } + } + + @Override + public boolean isRequestHeadersAllowed() { + return false; + } + + @Override + public String getDefaultURL() { + return "https://upload.wikimedia.org/wikipedia/commons/f/fa/Geysers_on_Mars.jpg"; + } + + @Override + public int getSampleTitle() { + return R.string.title_range_sample; + } + + @Override + public RequestHandle executeSample(AsyncHttpClient client, String URL, Header[] headers, HttpEntity entity, ResponseHandlerInterface responseHandler) { + if (fileSize > 0) { + // Send a GET query when we know the size of the remote file. + return client.get(this, URL, headers, null, responseHandler); + } else { + // Send a HEAD query to know the size of the remote file. + return client.head(this, URL, headers, null, responseHandler); + } + } + + public void sendNextRangeRequest() { + if (file.length() < fileSize) { + // File is still smaller than remote file; send a new request. + onRunButtonPressed(); + } + } + + @Override + public ResponseHandlerInterface getResponseHandler() { + return new RangeFileAsyncHttpResponseHandler(file) { + + @Override + public void onSuccess(int statusCode, Header[] headers, File file) { + debugHeaders(LOG_TAG, headers); + debugStatusCode(LOG_TAG, statusCode); + + if (fileSize < 1) { + boolean supportsRange = false; + // Cycle through the headers and look for the Content-Length header. + for (Header header : headers) { + String headerName = header.getName(); + if (CONTENT_LENGTH.equals(headerName)) { + fileSize = Long.parseLong(header.getValue()); + } else if (ACCEPT_RANGES.equals(headerName)) { + supportsRange = true; + } + } + + // Is the content length known? + if (!supportsRange || fileSize < 1) { + Toast.makeText( + RangeResponseSample.this, + "Unable to determine remote file's size, or\nremote server doesn't support ranges", + Toast.LENGTH_LONG + ).show(); + } + } + + // If remote file size is known, request next portion. + if (fileSize > 0) { + debugFileResponse(file); + // Send a new request for the same resource. + sendNextRangeRequest(); + } + } + + @Override + public void onFailure(int statusCode, Header[] headers, Throwable e, File file) { + debugHeaders(LOG_TAG, headers); + debugStatusCode(LOG_TAG, statusCode); + debugThrowable(LOG_TAG, e); + debugFileResponse(file); + } + + @Override + public void updateRequestHeaders(HttpUriRequest uriRequest) { + // Call super so appending could work. + super.updateRequestHeaders(uriRequest); + + // Length of the downloaded content thus far. + long length = file.length(); + + // Request the next portion of the file to be downloaded. + uriRequest.setHeader("Range", "bytes=" + length + "-" + (length + CHUNK_SIZE - 1)); + } + + void debugFileResponse(File file) { + debugResponse(LOG_TAG, "File size thus far: " + file.length() + " bytes"); + } + }; + } +} diff --git a/sample/src/main/java/com/loopj/android/http/sample/Redirect302Sample.java b/sample/src/main/java/com/loopj/android/http/sample/Redirect302Sample.java new file mode 100644 index 000000000..832b6a6eb --- /dev/null +++ b/sample/src/main/java/com/loopj/android/http/sample/Redirect302Sample.java @@ -0,0 +1,102 @@ +/* + Android Asynchronous Http Client Sample + Copyright (c) 2014 Marek Sebera + https://github.com/android-async-http/android-async-http + + 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 + + https://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.loopj.android.http.sample; + +import android.view.Menu; +import android.view.MenuItem; +import android.widget.Toast; + +import com.loopj.android.http.AsyncHttpClient; + +import cz.msebera.android.httpclient.client.HttpClient; +import cz.msebera.android.httpclient.impl.client.DefaultHttpClient; + +import java.util.Locale; + +public class Redirect302Sample extends GetSample { + + private static final int MENU_ENABLE_REDIRECTS = 10; + private static final int MENU_ENABLE_CIRCULAR_REDIRECTS = 11; + private static final int MENU_ENABLE_RELATIVE_REDIRECTs = 12; + private boolean enableRedirects = true; + private boolean enableRelativeRedirects = true; + private boolean enableCircularRedirects = true; + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + menu.add(Menu.NONE, MENU_ENABLE_REDIRECTS, Menu.NONE, "Enable redirects").setCheckable(true); + menu.add(Menu.NONE, MENU_ENABLE_RELATIVE_REDIRECTs, Menu.NONE, "Enable relative redirects").setCheckable(true); + menu.add(Menu.NONE, MENU_ENABLE_CIRCULAR_REDIRECTS, Menu.NONE, "Enable circular redirects").setCheckable(true); + return super.onCreateOptionsMenu(menu); + } + + @Override + public boolean onPrepareOptionsMenu(Menu menu) { + MenuItem menuItemEnableRedirects = menu.findItem(MENU_ENABLE_REDIRECTS); + if (menuItemEnableRedirects != null) + menuItemEnableRedirects.setChecked(enableRedirects); + MenuItem menuItemEnableRelativeRedirects = menu.findItem(MENU_ENABLE_RELATIVE_REDIRECTs); + if (menuItemEnableRelativeRedirects != null) + menuItemEnableRelativeRedirects.setChecked(enableRelativeRedirects); + MenuItem menuItemEnableCircularRedirects = menu.findItem(MENU_ENABLE_CIRCULAR_REDIRECTS); + if (menuItemEnableCircularRedirects != null) + menuItemEnableCircularRedirects.setChecked(enableCircularRedirects); + return super.onPrepareOptionsMenu(menu); + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + if (item.isCheckable()) { + item.setChecked(!item.isChecked()); + if (item.getItemId() == MENU_ENABLE_REDIRECTS) { + enableRedirects = item.isChecked(); + } else if (item.getItemId() == MENU_ENABLE_RELATIVE_REDIRECTs) { + enableRelativeRedirects = item.isChecked(); + } else if (item.getItemId() == MENU_ENABLE_CIRCULAR_REDIRECTS) { + enableCircularRedirects = item.isChecked(); + } + } + return super.onOptionsItemSelected(item); + } + + @Override + public String getDefaultURL() { + return PROTOCOL + "httpbin.org/redirect/6"; + } + + @Override + public int getSampleTitle() { + return R.string.title_redirect_302; + } + + @Override + public AsyncHttpClient getAsyncHttpClient() { + AsyncHttpClient ahc = super.getAsyncHttpClient(); + HttpClient client = ahc.getHttpClient(); + if (client instanceof DefaultHttpClient) { + Toast.makeText(this, + String.format(Locale.US, "redirects: %b\nrelative redirects: %b\ncircular redirects: %b", + enableRedirects, enableRelativeRedirects, enableCircularRedirects), + Toast.LENGTH_SHORT + ).show(); + ahc.setEnableRedirects(enableRedirects, enableRelativeRedirects, enableCircularRedirects); + } + return ahc; + } +} diff --git a/sample/src/main/java/com/loopj/android/http/sample/RequestParamsDebug.java b/sample/src/main/java/com/loopj/android/http/sample/RequestParamsDebug.java new file mode 100644 index 000000000..a753be40a --- /dev/null +++ b/sample/src/main/java/com/loopj/android/http/sample/RequestParamsDebug.java @@ -0,0 +1,160 @@ +package com.loopj.android.http.sample; + +import android.os.Bundle; +import android.widget.EditText; + +import com.loopj.android.http.AsyncHttpClient; +import com.loopj.android.http.RequestHandle; +import com.loopj.android.http.RequestParams; +import com.loopj.android.http.ResponseHandlerInterface; +import com.loopj.android.http.TextHttpResponseHandler; +import com.loopj.android.http.sample.util.API8Util; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import cz.msebera.android.httpclient.Header; +import cz.msebera.android.httpclient.HttpEntity; + +public class RequestParamsDebug extends SampleParentActivity { + + public static final String LOG_TAG = "RequestParamsDebug"; + private static final String DEMO_RP_CONTENT = "array=java\n" + + "array=C\n" + + "list=blue\n" + + "list=yellow\n" + + "set=music\n" + + "set=art\n" + + "map=first_name\n" + + "map=last_name\n"; + private EditText customParams; + + @Override + public ResponseHandlerInterface getResponseHandler() { + return new TextHttpResponseHandler() { + + @Override + public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) { + debugStatusCode(LOG_TAG, statusCode); + debugHeaders(LOG_TAG, headers); + debugResponse(LOG_TAG, responseString); + debugThrowable(LOG_TAG, throwable); + } + + @Override + public void onSuccess(int statusCode, Header[] headers, String responseString) { + debugStatusCode(LOG_TAG, statusCode); + debugHeaders(LOG_TAG, headers); + debugResponse(LOG_TAG, responseString); + } + }; + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + customParams = new EditText(this); + customParams.setLines(8); + customParams.setText(DEMO_RP_CONTENT); + customFieldsLayout.addView(customParams); + } + + @Override + public String getDefaultURL() { + return PROTOCOL + "httpbin.org/get"; + } + + @Override + public boolean isRequestHeadersAllowed() { + return false; + } + + @Override + public boolean isRequestBodyAllowed() { + return false; + } + + @Override + public int getSampleTitle() { + return R.string.title_request_params_debug; + } + + @Override + public RequestHandle executeSample(AsyncHttpClient client, String URL, Header[] headers, HttpEntity entity, ResponseHandlerInterface responseHandler) { + return getAsyncHttpClient().get(this, getDefaultURL(), getRequestParams(), getResponseHandler()); + } + + // TODO: allow parsing multiple values for each type, maybe like "type.key=value" ? + private RequestParams getRequestParams() { + RequestParams rp = new RequestParams(); + // contents of customParams custom field view + String customParamsText = customParams.getText().toString(); + String[] pairs = customParamsText.split("\n"); + // temp content holders + Map> mapOfMaps = new HashMap<>(); + Map> mapOfLists = new HashMap<>(); + Map mapOfArrays = new HashMap<>(); + Map> mapOfSets = new HashMap<>(); + for (String pair : pairs) { + String[] kv = pair.split("="); + if (kv.length != 2) + continue; + String key = kv[0].trim(); + String value = kv[1].trim(); + if ("array".equals(key)) { + String[] values = mapOfArrays.get(key); + if (values == null) { + values = new String[]{value}; + } else { + values = API8Util.copyOfRange(values, 0, values.length + 1); + values[values.length - 1] = value; + } + mapOfArrays.put(key, values); + } else if ("list".equals(key)) { + List values = mapOfLists.get(key); + if (values == null) { + values = new ArrayList<>(); + } + values.add(value); + mapOfLists.put(key, values); + } else if ("set".equals(key)) { + Set values = mapOfSets.get(key); + if (values == null) { + values = new HashSet<>(); + } + values.add(value); + mapOfSets.put(key, values); + } else if ("map".equals(key)) { + Map values = mapOfMaps.get(key); + if (values == null) { + values = new HashMap<>(); + } + values.put(key + values.size(), value); + mapOfMaps.put(key, values); + } + } + // fill in string list + for (Map.Entry> entry : mapOfLists.entrySet()) { + rp.put(entry.getKey(), entry.getValue()); + } + // fill in string array + for (Map.Entry entry : mapOfArrays.entrySet()) { + rp.put(entry.getKey(), entry.getValue()); + } + // fill in string set + for (Map.Entry> entry : mapOfSets.entrySet()) { + rp.put(entry.getKey(), entry.getValue()); + } + // fill in string map + for (Map.Entry> entry : mapOfMaps.entrySet()) { + rp.put(entry.getKey(), entry.getValue()); + } + // debug final URL construction into UI + debugResponse(LOG_TAG, rp.toString()); + return rp; + } +} diff --git a/sample/src/main/java/com/loopj/android/http/sample/ResumeDownloadSample.java b/sample/src/main/java/com/loopj/android/http/sample/ResumeDownloadSample.java new file mode 100644 index 000000000..b81902849 --- /dev/null +++ b/sample/src/main/java/com/loopj/android/http/sample/ResumeDownloadSample.java @@ -0,0 +1,85 @@ +package com.loopj.android.http.sample; + +import android.util.Log; + +import com.loopj.android.http.AsyncHttpClient; +import com.loopj.android.http.RangeFileAsyncHttpResponseHandler; +import com.loopj.android.http.RequestHandle; +import com.loopj.android.http.ResponseHandlerInterface; + +import java.io.File; +import java.io.IOException; + +import cz.msebera.android.httpclient.Header; +import cz.msebera.android.httpclient.HttpEntity; + +public class ResumeDownloadSample extends SampleParentActivity { + + private static final String LOG_TAG = "ResumeDownloadSample"; + private File downloadTarget; + + private File getDownloadTarget() { + try { + if (downloadTarget == null) { + downloadTarget = File.createTempFile("download_", "_resume", getCacheDir()); + } + } catch (IOException e) { + Log.e(LOG_TAG, "Couldn't create cache file to download to"); + } + return downloadTarget; + } + + @Override + public ResponseHandlerInterface getResponseHandler() { + return new RangeFileAsyncHttpResponseHandler(getDownloadTarget()) { + @Override + public void onFailure(int statusCode, Header[] headers, Throwable throwable, File file) { + debugStatusCode(LOG_TAG, statusCode); + debugHeaders(LOG_TAG, headers); + debugThrowable(LOG_TAG, throwable); + if (file != null) { + addView(getColoredView(LIGHTGREEN, "Download interrupted (" + statusCode + "): (bytes=" + file.length() + "), path: " + file.getAbsolutePath())); + } + } + + @Override + public void onSuccess(int statusCode, Header[] headers, File file) { + debugStatusCode(LOG_TAG, statusCode); + debugHeaders(LOG_TAG, headers); + if (file != null) { + addView(getColoredView(LIGHTGREEN, "Request succeeded (" + statusCode + "): (bytes=" + file.length() + "), path: " + file.getAbsolutePath())); + } + } + }; + } + + @Override + public String getDefaultHeaders() { + return "Range=bytes=10-20"; + } + + @Override + public String getDefaultURL() { + return PROTOCOL + "www.google.com/images/srpr/logo11w.png"; + } + + @Override + public boolean isRequestHeadersAllowed() { + return true; + } + + @Override + public boolean isRequestBodyAllowed() { + return false; + } + + @Override + public int getSampleTitle() { + return R.string.title_resume_download; + } + + @Override + public RequestHandle executeSample(AsyncHttpClient client, String URL, Header[] headers, HttpEntity entity, ResponseHandlerInterface responseHandler) { + return client.get(this, URL, headers, null, responseHandler); + } +} diff --git a/sample/src/main/java/com/loopj/android/http/sample/RetryRequestSample.java b/sample/src/main/java/com/loopj/android/http/sample/RetryRequestSample.java new file mode 100644 index 000000000..64c797c7f --- /dev/null +++ b/sample/src/main/java/com/loopj/android/http/sample/RetryRequestSample.java @@ -0,0 +1,85 @@ +/* + Android Asynchronous Http Client Sample + Copyright (c) 2014 Marek Sebera + https://github.com/android-async-http/android-async-http + + 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 + + https://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.loopj.android.http.sample; + +import android.os.Bundle; +import android.widget.Toast; + +import com.loopj.android.http.AsyncHttpClient; + +import java.io.IOException; +import java.net.SocketTimeoutException; +import java.net.UnknownHostException; + +import cz.msebera.android.httpclient.conn.ConnectTimeoutException; +import cz.msebera.android.httpclient.conn.ConnectionPoolTimeoutException; + +/** + * This sample demonstrates use of + * {@link AsyncHttpClient#allowRetryExceptionClass(java.lang.Class)} and + * {@link AsyncHttpClient#blockRetryExceptionClass(java.lang.Class)} to whitelist + * and blacklist certain Exceptions, respectively. + * + * @author Noor Dawod + */ +public class RetryRequestSample extends GetSample { + + private static boolean wasToastShown; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + // The following exceptions will be whitelisted, i.e.: When an exception + // of this type is raised, the request will be retried. + AsyncHttpClient.allowRetryExceptionClass(IOException.class); + AsyncHttpClient.allowRetryExceptionClass(SocketTimeoutException.class); + AsyncHttpClient.allowRetryExceptionClass(ConnectTimeoutException.class); + + // The following exceptions will be blacklisted, i.e.: When an exception + // of this type is raised, the request will not be retried and it will + // fail immediately. + AsyncHttpClient.blockRetryExceptionClass(UnknownHostException.class); + AsyncHttpClient.blockRetryExceptionClass(ConnectionPoolTimeoutException.class); + } + + @Override + protected void onResume() { + super.onResume(); + + if (!wasToastShown) { + wasToastShown = true; + Toast.makeText( + this, + "Exceptions' whitelist and blacklist updated\nSee RetryRequestSample.java for details", + Toast.LENGTH_LONG + ).show(); + } + } + + @Override + public String getDefaultURL() { + return PROTOCOL + "httpbin.org/ip"; + } + + @Override + public int getSampleTitle() { + return R.string.title_retry_handler; + } +} diff --git a/sample/src/main/java/com/loopj/android/http/sample/SampleInterface.java b/sample/src/main/java/com/loopj/android/http/sample/SampleInterface.java new file mode 100644 index 000000000..a259833c7 --- /dev/null +++ b/sample/src/main/java/com/loopj/android/http/sample/SampleInterface.java @@ -0,0 +1,71 @@ +/* + Android Asynchronous Http Client Sample + Copyright (c) 2014 Marek Sebera + https://github.com/android-async-http/android-async-http + + 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 + + https://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.loopj.android.http.sample; + +import android.content.Context; + +import com.loopj.android.http.AsyncHttpClient; +import com.loopj.android.http.AsyncHttpRequest; +import com.loopj.android.http.RequestHandle; +import com.loopj.android.http.ResponseHandlerInterface; + +import java.util.List; + +import cz.msebera.android.httpclient.Header; +import cz.msebera.android.httpclient.HttpEntity; +import cz.msebera.android.httpclient.client.methods.HttpUriRequest; +import cz.msebera.android.httpclient.impl.client.DefaultHttpClient; +import cz.msebera.android.httpclient.protocol.HttpContext; + +public interface SampleInterface { + + List getRequestHandles(); + + void addRequestHandle(RequestHandle handle); + + void onRunButtonPressed(); + + void onCancelButtonPressed(); + + Header[] getRequestHeaders(); + + HttpEntity getRequestEntity(); + + AsyncHttpClient getAsyncHttpClient(); + + void setAsyncHttpClient(AsyncHttpClient client); + + AsyncHttpRequest getHttpRequest(DefaultHttpClient client, HttpContext httpContext, HttpUriRequest uriRequest, String contentType, ResponseHandlerInterface responseHandler, Context context); + + ResponseHandlerInterface getResponseHandler(); + + String getDefaultURL(); + + String getDefaultHeaders(); + + boolean isRequestHeadersAllowed(); + + boolean isRequestBodyAllowed(); + + int getSampleTitle(); + + boolean isCancelButtonAllowed(); + + RequestHandle executeSample(AsyncHttpClient client, String URL, Header[] headers, HttpEntity entity, ResponseHandlerInterface responseHandler); +} diff --git a/sample/src/main/java/com/loopj/android/http/sample/SampleParentActivity.java b/sample/src/main/java/com/loopj/android/http/sample/SampleParentActivity.java new file mode 100755 index 000000000..165b2baf8 --- /dev/null +++ b/sample/src/main/java/com/loopj/android/http/sample/SampleParentActivity.java @@ -0,0 +1,402 @@ +/* + Android Asynchronous Http Client Sample + Copyright (c) 2014 Marek Sebera + https://github.com/android-async-http/android-async-http + + 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 + + https://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.loopj.android.http.sample; + +import android.annotation.TargetApi; +import android.app.Activity; +import android.app.AlertDialog; +import android.content.Context; +import android.content.DialogInterface; +import android.graphics.Color; +import android.os.Build; +import android.os.Bundle; +import android.util.Log; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.widget.Button; +import android.widget.EditText; +import android.widget.LinearLayout; +import android.widget.TextView; + +import com.loopj.android.http.AsyncHttpClient; +import com.loopj.android.http.AsyncHttpRequest; +import com.loopj.android.http.RequestHandle; +import com.loopj.android.http.ResponseHandlerInterface; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.io.UnsupportedEncodingException; +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; +import java.util.Locale; + +import cz.msebera.android.httpclient.Header; +import cz.msebera.android.httpclient.HttpEntity; +import cz.msebera.android.httpclient.client.methods.HttpUriRequest; +import cz.msebera.android.httpclient.entity.StringEntity; +import cz.msebera.android.httpclient.impl.client.DefaultHttpClient; +import cz.msebera.android.httpclient.message.BasicHeader; +import cz.msebera.android.httpclient.protocol.HttpContext; + +public abstract class SampleParentActivity extends Activity implements SampleInterface { + + protected static final String PROTOCOL_HTTP = "http://"; + protected static final String PROTOCOL_HTTPS = "https://"; + protected static final int LIGHTGREEN = Color.parseColor("#00FF66"); + protected static final int LIGHTRED = Color.parseColor("#FF3300"); + protected static final int YELLOW = Color.parseColor("#FFFF00"); + protected static final int LIGHTBLUE = Color.parseColor("#99CCFF"); + private static final String LOG_TAG = "SampleParentActivity"; + private static final int MENU_USE_HTTPS = 0; + private static final int MENU_CLEAR_VIEW = 1; + private static final int MENU_LOGGING_VERBOSITY = 2; + private static final int MENU_ENABLE_LOGGING = 3; + protected static String PROTOCOL = PROTOCOL_HTTPS; + private final List requestHandles = new LinkedList(); + public LinearLayout customFieldsLayout; + private AsyncHttpClient asyncHttpClient = new AsyncHttpClient() { + + @Override + protected AsyncHttpRequest newAsyncHttpRequest(DefaultHttpClient client, HttpContext httpContext, HttpUriRequest uriRequest, String contentType, ResponseHandlerInterface responseHandler, Context context) { + AsyncHttpRequest httpRequest = getHttpRequest(client, httpContext, uriRequest, contentType, responseHandler, context); + return httpRequest == null + ? super.newAsyncHttpRequest(client, httpContext, uriRequest, contentType, responseHandler, context) + : httpRequest; + } + }; + private EditText urlEditText, headersEditText, bodyEditText; + protected final View.OnClickListener onClickListener = new View.OnClickListener() { + @Override + public void onClick(View v) { + switch (v.getId()) { + case R.id.button_run: + onRunButtonPressed(); + break; + case R.id.button_cancel: + onCancelButtonPressed(); + break; + } + } + }; + private LinearLayout responseLayout; + private boolean useHttps = true; + private boolean enableLogging = true; + + protected static String throwableToString(Throwable t) { + if (t == null) + return null; + + StringWriter sw = new StringWriter(); + t.printStackTrace(new PrintWriter(sw)); + return sw.toString(); + } + + public static int getContrastColor(int color) { + double y = (299 * Color.red(color) + 587 * Color.green(color) + 114 * Color.blue(color)) / 1000; + return y >= 128 ? Color.BLACK : Color.WHITE; + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.parent_layout); + setTitle(getSampleTitle()); + + setHomeAsUpEnabled(); + + urlEditText = (EditText) findViewById(R.id.edit_url); + headersEditText = (EditText) findViewById(R.id.edit_headers); + bodyEditText = (EditText) findViewById(R.id.edit_body); + customFieldsLayout = (LinearLayout) findViewById(R.id.layout_custom); + Button runButton = (Button) findViewById(R.id.button_run); + Button cancelButton = (Button) findViewById(R.id.button_cancel); + LinearLayout headersLayout = (LinearLayout) findViewById(R.id.layout_headers); + LinearLayout bodyLayout = (LinearLayout) findViewById(R.id.layout_body); + responseLayout = (LinearLayout) findViewById(R.id.layout_response); + + urlEditText.setText(getDefaultURL()); + headersEditText.setText(getDefaultHeaders()); + + bodyLayout.setVisibility(isRequestBodyAllowed() ? View.VISIBLE : View.GONE); + headersLayout.setVisibility(isRequestHeadersAllowed() ? View.VISIBLE : View.GONE); + + runButton.setOnClickListener(onClickListener); + if (cancelButton != null) { + if (isCancelButtonAllowed()) { + cancelButton.setVisibility(View.VISIBLE); + cancelButton.setOnClickListener(onClickListener); + } else { + cancelButton.setEnabled(false); + } + } + } + + @Override + public boolean onPrepareOptionsMenu(Menu menu) { + MenuItem useHttpsMenuItem = menu.findItem(MENU_USE_HTTPS); + if (useHttpsMenuItem != null) { + useHttpsMenuItem.setChecked(useHttps); + } + MenuItem enableLoggingMenuItem = menu.findItem(MENU_ENABLE_LOGGING); + if (enableLoggingMenuItem != null) { + enableLoggingMenuItem.setChecked(enableLogging); + } + return super.onPrepareOptionsMenu(menu); + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + menu.add(Menu.NONE, MENU_USE_HTTPS, Menu.NONE, R.string.menu_use_https).setCheckable(true); + menu.add(Menu.NONE, MENU_CLEAR_VIEW, Menu.NONE, R.string.menu_clear_view); + menu.add(Menu.NONE, MENU_ENABLE_LOGGING, Menu.NONE, "Enable Logging").setCheckable(true); + menu.add(Menu.NONE, MENU_LOGGING_VERBOSITY, Menu.NONE, "Set Logging Verbosity"); + return super.onCreateOptionsMenu(menu); + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case MENU_USE_HTTPS: + useHttps = !useHttps; + PROTOCOL = useHttps ? PROTOCOL_HTTPS : PROTOCOL_HTTP; + urlEditText.setText(getDefaultURL()); + return true; + case MENU_ENABLE_LOGGING: + enableLogging = !enableLogging; + getAsyncHttpClient().setLoggingEnabled(enableLogging); + return true; + case MENU_LOGGING_VERBOSITY: + showLoggingVerbosityDialog(); + return true; + case MENU_CLEAR_VIEW: + clearOutputs(); + return true; + case android.R.id.home: + finish(); + return true; + } + return super.onOptionsItemSelected(item); + } + + @Override + public AsyncHttpRequest getHttpRequest(DefaultHttpClient client, HttpContext httpContext, HttpUriRequest uriRequest, String contentType, ResponseHandlerInterface responseHandler, Context context) { + return null; + } + + public List getRequestHandles() { + return requestHandles; + } + + @Override + public void addRequestHandle(RequestHandle handle) { + if (null != handle) { + requestHandles.add(handle); + } + } + + private void showLoggingVerbosityDialog() { + AlertDialog ad = new AlertDialog.Builder(this) + .setTitle("Set Logging Verbosity") + .setSingleChoiceItems(new String[]{ + "VERBOSE", + "DEBUG", + "INFO", + "WARN", + "ERROR", + "WTF" + }, getAsyncHttpClient().getLoggingLevel() - 2, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + getAsyncHttpClient().setLoggingLevel(which + 2); + dialog.dismiss(); + } + }) + .setCancelable(true) + .setNeutralButton("Cancel", null) + .create(); + ad.show(); + } + + public void onRunButtonPressed() { + addRequestHandle(executeSample(getAsyncHttpClient(), + getUrlText(getDefaultURL()), + getRequestHeaders(), + getRequestEntity(), + getResponseHandler())); + } + + public void onCancelButtonPressed() { + asyncHttpClient.cancelRequests(SampleParentActivity.this, true); + } + + public List

getRequestHeadersList() { + List
headers = new ArrayList
(); + String headersRaw = headersEditText.getText() == null ? null : headersEditText.getText().toString(); + + if (headersRaw != null && headersRaw.length() > 3) { + String[] lines = headersRaw.split("\\r?\\n"); + for (String line : lines) { + try { + int equalSignPos = line.indexOf('='); + if (1 > equalSignPos) { + throw new IllegalArgumentException("Wrong header format, may be 'Key=Value' only"); + } + + String headerName = line.substring(0, equalSignPos).trim(); + String headerValue = line.substring(1 + equalSignPos).trim(); + Log.d(LOG_TAG, String.format(Locale.US, "Added header: [%s:%s]", headerName, headerValue)); + + headers.add(new BasicHeader(headerName, headerValue)); + } catch (Throwable t) { + Log.e(LOG_TAG, "Not a valid header line: " + line, t); + } + } + } + return headers; + } + + public Header[] getRequestHeaders() { + List
headers = getRequestHeadersList(); + return headers.toArray(new Header[headers.size()]); + } + + public HttpEntity getRequestEntity() { + String bodyText; + if (isRequestBodyAllowed() && (bodyText = getBodyText()) != null) { + try { + return new StringEntity(bodyText); + } catch (UnsupportedEncodingException e) { + Log.e(LOG_TAG, "cannot create String entity", e); + } + } + return null; + } + + public String getUrlText() { + return getUrlText(null); + } + + public String getUrlText(String defaultText) { + return urlEditText != null && urlEditText.getText() != null + ? urlEditText.getText().toString() + : defaultText; + } + + public String getBodyText() { + return getBodyText(null); + } + + public String getBodyText(String defaultText) { + return bodyEditText != null && bodyEditText.getText() != null + ? bodyEditText.getText().toString() + : defaultText; + } + + public String getHeadersText() { + return getHeadersText(null); + } + + public String getHeadersText(String defaultText) { + return headersEditText != null && headersEditText.getText() != null + ? headersEditText.getText().toString() + : defaultText; + } + + protected final void debugHeaders(String TAG, Header[] headers) { + if (headers != null) { + Log.d(TAG, "Return Headers:"); + StringBuilder builder = new StringBuilder(); + for (Header h : headers) { + String _h = String.format(Locale.US, "%s : %s", h.getName(), h.getValue()); + Log.d(TAG, _h); + builder.append(_h); + builder.append("\n"); + } + addView(getColoredView(YELLOW, builder.toString())); + } + } + + protected final void debugThrowable(String TAG, Throwable t) { + if (t != null) { + Log.e(TAG, "AsyncHttpClient returned error", t); + addView(getColoredView(LIGHTRED, throwableToString(t))); + } + } + + protected final void debugResponse(String TAG, String response) { + if (response != null) { + Log.d(TAG, "Response data:"); + Log.d(TAG, response); + addView(getColoredView(LIGHTGREEN, response)); + } + } + + protected final void debugStatusCode(String TAG, int statusCode) { + String msg = String.format(Locale.US, "Return Status Code: %d", statusCode); + Log.d(TAG, msg); + addView(getColoredView(LIGHTBLUE, msg)); + } + + protected View getColoredView(int bgColor, String msg) { + TextView tv = new TextView(this); + tv.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); + tv.setText(msg); + tv.setBackgroundColor(bgColor); + tv.setPadding(10, 10, 10, 10); + tv.setTextColor(getContrastColor(bgColor)); + return tv; + } + + @Override + public String getDefaultHeaders() { + return null; + } + + protected final void addView(View v) { + responseLayout.addView(v); + } + + protected final void clearOutputs() { + responseLayout.removeAllViews(); + } + + public boolean isCancelButtonAllowed() { + return false; + } + + public AsyncHttpClient getAsyncHttpClient() { + return this.asyncHttpClient; + } + + @Override + public void setAsyncHttpClient(AsyncHttpClient client) { + this.asyncHttpClient = client; + } + + @TargetApi(Build.VERSION_CODES.HONEYCOMB) + private void setHomeAsUpEnabled() { + if (Build.VERSION.SDK_INT >= 11) { + if (getActionBar() != null) + getActionBar().setDisplayHomeAsUpEnabled(true); + } + } +} diff --git a/sample/src/main/java/com/loopj/android/http/sample/SaxSample.java b/sample/src/main/java/com/loopj/android/http/sample/SaxSample.java new file mode 100644 index 000000000..be310272c --- /dev/null +++ b/sample/src/main/java/com/loopj/android/http/sample/SaxSample.java @@ -0,0 +1,126 @@ +/* + Android Asynchronous Http Client Sample + Copyright (c) 2014 Marek Sebera + https://github.com/android-async-http/android-async-http + + 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 + + https://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.loopj.android.http.sample; + +import com.loopj.android.http.AsyncHttpClient; +import com.loopj.android.http.RequestHandle; +import com.loopj.android.http.ResponseHandlerInterface; +import com.loopj.android.http.SaxAsyncHttpResponseHandler; + +import org.xml.sax.Attributes; +import org.xml.sax.helpers.DefaultHandler; + +import java.util.ArrayList; +import java.util.List; + +import cz.msebera.android.httpclient.Header; +import cz.msebera.android.httpclient.HttpEntity; + +public class SaxSample extends SampleParentActivity { + + private static final String LOG_TAG = "SaxSample"; + private final SaxAsyncHttpResponseHandler saxAsyncHttpResponseHandler = new SaxAsyncHttpResponseHandler(new SAXTreeStructure()) { + @Override + public void onStart() { + clearOutputs(); + } + + @Override + public void onSuccess(int statusCode, Header[] headers, SAXTreeStructure saxTreeStructure) { + debugStatusCode(LOG_TAG, statusCode); + debugHeaders(LOG_TAG, headers); + debugHandler(saxTreeStructure); + } + + @Override + public void onFailure(int statusCode, Header[] headers, SAXTreeStructure saxTreeStructure) { + debugStatusCode(LOG_TAG, statusCode); + debugHeaders(LOG_TAG, headers); + debugHandler(saxTreeStructure); + } + + private void debugHandler(SAXTreeStructure handler) { + for (Tuple t : handler.responseViews) { + addView(getColoredView(t.color, t.text)); + } + } + }; + + @Override + public ResponseHandlerInterface getResponseHandler() { + return saxAsyncHttpResponseHandler; + } + + @Override + public String getDefaultURL() { + return "http://bin-iin.com/sitemap.xml"; + } + + @Override + public boolean isRequestHeadersAllowed() { + return false; + } + + @Override + public boolean isRequestBodyAllowed() { + return false; + } + + @Override + public int getSampleTitle() { + return R.string.title_sax_example; + } + + @Override + public RequestHandle executeSample(AsyncHttpClient client, String URL, Header[] headers, HttpEntity entity, ResponseHandlerInterface responseHandler) { + return client.get(this, URL, headers, null, responseHandler); + } + + private class Tuple { + public final Integer color; + public final String text; + + public Tuple(int _color, String _text) { + this.color = _color; + this.text = _text; + } + } + + private class SAXTreeStructure extends DefaultHandler { + + public final List responseViews = new ArrayList(); + + public void startElement(String namespaceURI, String localName, + String rawName, Attributes atts) { + responseViews.add(new Tuple(LIGHTBLUE, "Start Element: " + rawName)); + } + + public void endElement(String namespaceURI, String localName, + String rawName) { + responseViews.add(new Tuple(LIGHTBLUE, "End Element : " + rawName)); + } + + public void characters(char[] data, int off, int length) { + if (length > 0 && data[0] != '\n') { + responseViews.add(new Tuple(LIGHTGREEN, "Characters : " + new String(data, + off, length))); + } + } + } +} diff --git a/sample/src/main/java/com/loopj/android/http/sample/SynchronousClientSample.java b/sample/src/main/java/com/loopj/android/http/sample/SynchronousClientSample.java new file mode 100644 index 000000000..59ff04186 --- /dev/null +++ b/sample/src/main/java/com/loopj/android/http/sample/SynchronousClientSample.java @@ -0,0 +1,126 @@ +/* + Android Asynchronous Http Client Sample + Copyright (c) 2014 Marek Sebera + https://github.com/android-async-http/android-async-http + + 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 + + https://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.loopj.android.http.sample; + +import android.os.Bundle; +import android.util.Log; + +import com.loopj.android.http.AsyncHttpClient; +import com.loopj.android.http.AsyncHttpResponseHandler; +import com.loopj.android.http.RequestHandle; +import com.loopj.android.http.ResponseHandlerInterface; +import com.loopj.android.http.SyncHttpClient; + +import cz.msebera.android.httpclient.Header; +import cz.msebera.android.httpclient.HttpEntity; + +public class SynchronousClientSample extends GetSample { + private static final String LOG_TAG = "SyncSample"; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setAsyncHttpClient(new SyncHttpClient()); + } + + @Override + public int getSampleTitle() { + return R.string.title_synchronous; + } + + @Override + public boolean isRequestBodyAllowed() { + return false; + } + + @Override + public boolean isRequestHeadersAllowed() { + return true; + } + + @Override + public String getDefaultURL() { + return "https://httpbin.org/delay/6"; + } + + @Override + public RequestHandle executeSample(final AsyncHttpClient client, final String URL, final Header[] headers, HttpEntity entity, final ResponseHandlerInterface responseHandler) { + if (client instanceof SyncHttpClient) { + new Thread(new Runnable() { + @Override + public void run() { + Log.d(LOG_TAG, "Before Request"); + client.get(SynchronousClientSample.this, URL, headers, null, responseHandler); + Log.d(LOG_TAG, "After Request"); + } + }).start(); + } else { + Log.e(LOG_TAG, "Error, not using SyncHttpClient"); + } + /** + * SyncHttpClient does not return RequestHandle, + * it executes each request directly, + * therefore those requests are not in cancelable threads + * */ + return null; + } + + @Override + public ResponseHandlerInterface getResponseHandler() { + return new AsyncHttpResponseHandler() { + + @Override + public void onStart() { + runOnUiThread(new Runnable() { + @Override + public void run() { + clearOutputs(); + } + }); + } + + @Override + public void onSuccess(final int statusCode, final Header[] headers, final byte[] response) { + runOnUiThread(new Runnable() { + @Override + public void run() { + debugHeaders(LOG_TAG, headers); + debugStatusCode(LOG_TAG, statusCode); + debugResponse(LOG_TAG, new String(response)); + } + }); + } + + @Override + public void onFailure(final int statusCode, final Header[] headers, final byte[] errorResponse, final Throwable e) { + runOnUiThread(new Runnable() { + @Override + public void run() { + debugHeaders(LOG_TAG, headers); + debugStatusCode(LOG_TAG, statusCode); + debugThrowable(LOG_TAG, e); + if (errorResponse != null) { + debugResponse(LOG_TAG, new String(errorResponse)); + } + } + }); + } + }; + } +} diff --git a/sample/src/main/java/com/loopj/android/http/sample/ThreadingTimeoutSample.java b/sample/src/main/java/com/loopj/android/http/sample/ThreadingTimeoutSample.java new file mode 100755 index 000000000..f65ba17d8 --- /dev/null +++ b/sample/src/main/java/com/loopj/android/http/sample/ThreadingTimeoutSample.java @@ -0,0 +1,114 @@ +/* + Android Asynchronous Http Client Sample + Copyright (c) 2014 Marek Sebera + https://github.com/android-async-http/android-async-http + + 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 + + https://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.loopj.android.http.sample; + +import android.util.SparseArray; + +import com.loopj.android.http.AsyncHttpClient; +import com.loopj.android.http.AsyncHttpResponseHandler; +import com.loopj.android.http.RequestHandle; +import com.loopj.android.http.ResponseHandlerInterface; + +import java.util.Locale; + +import cz.msebera.android.httpclient.Header; +import cz.msebera.android.httpclient.HttpEntity; + +public class ThreadingTimeoutSample extends SampleParentActivity { + + private static final String LOG_TAG = "ThreadingTimeoutSample"; + protected final SparseArray states = new SparseArray(); + protected int counter = 0; + + @Override + public int getSampleTitle() { + return R.string.title_threading_timeout; + } + + @Override + public boolean isRequestBodyAllowed() { + return false; + } + + @Override + public boolean isRequestHeadersAllowed() { + return false; + } + + @Override + public boolean isCancelButtonAllowed() { + return true; + } + + @Override + public String getDefaultURL() { + return PROTOCOL + "httpbin.org/delay/6"; + } + + protected synchronized void setStatus(int id, String status) { + String current = states.get(id, null); + states.put(id, current == null ? status : current + "," + status); + clearOutputs(); + for (int i = 0; i < states.size(); i++) { + debugResponse(LOG_TAG, String.format(Locale.US, "%d (from %d): %s", states.keyAt(i), getCounter(), states.get(states.keyAt(i)))); + } + } + + @Override + public ResponseHandlerInterface getResponseHandler() { + return new AsyncHttpResponseHandler() { + + private final int id = counter++; + + @Override + public void onStart() { + setStatus(id, "START"); + } + + @Override + public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { + setStatus(id, "SUCCESS"); + } + + @Override + public void onFinish() { + setStatus(id, "FINISH"); + } + + @Override + public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { + setStatus(id, "FAILURE"); + } + + @Override + public void onCancel() { + setStatus(id, "CANCEL"); + } + }; + } + + public int getCounter() { + return counter; + } + + @Override + public RequestHandle executeSample(AsyncHttpClient client, String URL, Header[] headers, HttpEntity entity, ResponseHandlerInterface responseHandler) { + return client.get(this, URL, headers, null, responseHandler); + } +} diff --git a/sample/src/main/java/com/loopj/android/http/sample/UsePoolThreadSample.java b/sample/src/main/java/com/loopj/android/http/sample/UsePoolThreadSample.java new file mode 100644 index 000000000..a9e6da958 --- /dev/null +++ b/sample/src/main/java/com/loopj/android/http/sample/UsePoolThreadSample.java @@ -0,0 +1,114 @@ +package com.loopj.android.http.sample; + +import android.util.Log; + +import com.loopj.android.http.AsyncHttpResponseHandler; +import com.loopj.android.http.ResponseHandlerInterface; + +import java.io.File; + +import cz.msebera.android.httpclient.Header; + +public class UsePoolThreadSample extends GetSample { + + private static final String LOG_TAG = "UsePoolThreadSample"; + + @Override + public String getDefaultURL() { + return PROTOCOL + "httpbin.org/bytes/1024000"; + } + + @Override + public boolean isRequestHeadersAllowed() { + return false; + } + + @Override + public int getSampleTitle() { + return R.string.title_use_pool_thread; + } + + @Override + public ResponseHandlerInterface getResponseHandler() { + return new UsePoolThreadResponseHandler(); + } + + private class UsePoolThreadResponseHandler extends AsyncHttpResponseHandler { + + private final File destFile; + + public UsePoolThreadResponseHandler() { + super(); + + // Destination file to save the downloaded bytes to. + destFile = getRandomCacheFile(); + Log.d(LOG_TAG, "Bytes will be saved in file: " + destFile.getAbsolutePath()); + + // We wish to use the same pool thread to run the response. + setUsePoolThread(true); + } + + @Override + public void onSuccess(final int statusCode, final Header[] headers, final byte[] responseBody) { + // Response body includes 1MB of data, and it might take few + // milliseconds, maybe a second or two on old devices, to save it in + // the filesystem. However, since this callback method is running + // within the pool thread's execution scope, the UI thread will be + // relaxed to continue its work of updating the UI while this + // handler saves the bytes on disk. + + // Save the response body's bytes on disk. + saveBytesOnDisk(destFile, responseBody); + + // This callback is now running within the pool thread execution + // scope and not within Android's UI thread, so if we must update + // the UI, we'll have to dispatch a runnable to the UI thread. + runOnUiThread(new Runnable() { + + @Override + public void run() { + debugStatusCode(LOG_TAG, statusCode); + debugHeaders(LOG_TAG, headers); + if (responseBody != null) { + addView(getColoredView(LIGHTGREEN, "Request succeeded (" + statusCode + "): (bytes=" + destFile.length() + "), path: " + destFile.getAbsolutePath())); + } + } + }); + } + + @Override + public void onFailure(final int statusCode, final Header[] headers, final byte[] responseBody, final Throwable error) { + // This callback is now running within the pool thread execution + // scope and not within Android's UI thread, so if we must update + // the UI, we'll have to dispatch a runnable to the UI thread. + runOnUiThread(new Runnable() { + + @Override + public void run() { + debugStatusCode(LOG_TAG, statusCode); + debugHeaders(LOG_TAG, headers); + debugThrowable(LOG_TAG, error); + if (responseBody != null) { + addView(getColoredView(LIGHTGREEN, "Download interrupted (" + statusCode + "): (bytes=" + responseBody.length + "), path: " + destFile.getAbsolutePath())); + } + } + }); + } + + private File getRandomCacheFile() { + File dir = getCacheDir(); + if (dir == null) { + dir = getFilesDir(); + } + + return new File(dir, "sample-" + System.currentTimeMillis() + ".bin"); + } + + private void saveBytesOnDisk(File destination, byte[] bytes) { + // TODO: Spin your own implementation to save the bytes on disk/SD card. + if (bytes != null && destination != null) { + Log.d(LOG_TAG, "Saved " + bytes.length + " bytes into file: " + destination.getAbsolutePath()); + } + } + } +} diff --git a/sample/src/main/java/com/loopj/android/http/sample/WaypointsActivity.java b/sample/src/main/java/com/loopj/android/http/sample/WaypointsActivity.java new file mode 100755 index 000000000..f1dba9d7a --- /dev/null +++ b/sample/src/main/java/com/loopj/android/http/sample/WaypointsActivity.java @@ -0,0 +1,100 @@ +/* + Android Asynchronous Http Client Sample + Copyright (c) 2014 Marek Sebera + https://github.com/android-async-http/android-async-http + + 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 + + https://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.loopj.android.http.sample; + +import android.app.ListActivity; +import android.content.Intent; +import android.os.Bundle; +import android.view.View; +import android.widget.ArrayAdapter; +import android.widget.ListView; + +import java.util.ArrayList; +import java.util.List; + +public class WaypointsActivity extends ListActivity { + + private static final SampleConfig[] samplesConfig = new SampleConfig[]{ + new SampleConfig(R.string.title_get_sample, GetSample.class), + new SampleConfig(R.string.title_post_sample, PostSample.class), + new SampleConfig(R.string.title_delete_sample, DeleteSample.class), + new SampleConfig(R.string.title_put_sample, PutSample.class), + new SampleConfig(R.string.title_patch_sample, PatchSample.class), + new SampleConfig(R.string.title_head_sample, HeadSample.class), + new SampleConfig(R.string.title_json_sample, JsonSample.class), + new SampleConfig(R.string.title_json_streamer_sample, JsonStreamerSample.class), + new SampleConfig(R.string.title_sax_example, SaxSample.class), + new SampleConfig(R.string.title_file_sample, FileSample.class), + new SampleConfig(R.string.title_directory_sample, DirectorySample.class), + new SampleConfig(R.string.title_binary_sample, BinarySample.class), + new SampleConfig(R.string.title_gzip_sample, GzipSample.class), + new SampleConfig(R.string.title_redirect_302, Redirect302Sample.class), + new SampleConfig(R.string.title_threading_timeout, ThreadingTimeoutSample.class), + new SampleConfig(R.string.title_cancel_all, CancelAllRequestsSample.class), + new SampleConfig(R.string.title_cancel_handle, CancelRequestHandleSample.class), + new SampleConfig(R.string.title_cancel_tag, CancelRequestByTagSample.class), + new SampleConfig(R.string.title_synchronous, SynchronousClientSample.class), + new SampleConfig(R.string.title_intent_service_sample, IntentServiceSample.class), + new SampleConfig(R.string.title_post_files, FilesSample.class), + new SampleConfig(R.string.title_persistent_cookies, PersistentCookiesSample.class), + new SampleConfig(R.string.title_custom_ca, CustomCASample.class), + new SampleConfig(R.string.title_retry_handler, RetryRequestSample.class), + new SampleConfig(R.string.title_range_sample, RangeResponseSample.class), + new SampleConfig(R.string.title_401_unauth, Http401AuthSample.class), + new SampleConfig(R.string.title_pre_post_processing, PrePostProcessingSample.class), + new SampleConfig(R.string.title_content_type_http_entity, ContentTypeForHttpEntitySample.class), + new SampleConfig(R.string.title_resume_download, ResumeDownloadSample.class), + new SampleConfig(R.string.title_digest_auth, DigestAuthSample.class), + new SampleConfig(R.string.title_use_pool_thread, UsePoolThreadSample.class), + new SampleConfig(R.string.title_request_params_debug, RequestParamsDebug.class) + }; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setListAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, getTitlesList())); + } + + private List getTitlesList() { + List titles = new ArrayList<>(); + for (SampleConfig config : samplesConfig) { + titles.add(getString(config.titleId)); + } + return titles; + } + + @Override + protected void onListItemClick(ListView l, View v, int position, long id) { + if (position >= 0 && position < samplesConfig.length) + startActivity(new Intent(this, samplesConfig[position].targetClass)); + } + + private static class SampleConfig { + + final int titleId; + final Class targetClass; + + SampleConfig(int titleId, Class targetClass) { + this.titleId = titleId; + this.targetClass = targetClass; + } + + } + +} diff --git a/sample/src/main/java/com/loopj/android/http/sample/package-info.java b/sample/src/main/java/com/loopj/android/http/sample/package-info.java new file mode 100644 index 000000000..704f0d47d --- /dev/null +++ b/sample/src/main/java/com/loopj/android/http/sample/package-info.java @@ -0,0 +1,19 @@ +/* + Android Asynchronous Http Client + Copyright (c) 2014 Marek Sebera + https://github.com/android-async-http/android-async-http + + 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 + + https://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.loopj.android.http.sample; \ No newline at end of file diff --git a/sample/src/main/java/com/loopj/android/http/sample/services/ExampleIntentService.java b/sample/src/main/java/com/loopj/android/http/sample/services/ExampleIntentService.java new file mode 100644 index 000000000..53e069ec3 --- /dev/null +++ b/sample/src/main/java/com/loopj/android/http/sample/services/ExampleIntentService.java @@ -0,0 +1,89 @@ +package com.loopj.android.http.sample.services; + +import android.app.IntentService; +import android.content.Intent; +import android.util.Log; + +import com.loopj.android.http.AsyncHttpClient; +import com.loopj.android.http.AsyncHttpResponseHandler; +import com.loopj.android.http.SyncHttpClient; +import com.loopj.android.http.sample.IntentServiceSample; +import com.loopj.android.http.sample.util.IntentUtil; + +import java.util.Locale; + +import cz.msebera.android.httpclient.Header; + +public class ExampleIntentService extends IntentService { + + public static final String LOG_TAG = "ExampleIntentService:IntentServiceSample"; + public static final String INTENT_URL = "INTENT_URL"; + public static final String INTENT_STATUS_CODE = "INTENT_STATUS_CODE"; + public static final String INTENT_HEADERS = "INTENT_HEADERS"; + public static final String INTENT_DATA = "INTENT_DATA"; + public static final String INTENT_THROWABLE = "INTENT_THROWABLE"; + + private final AsyncHttpClient aClient = new SyncHttpClient(); + + public ExampleIntentService() { + super("ExampleIntentService"); + } + + @Override + public void onStart(Intent intent, int startId) { + Log.d(LOG_TAG, "onStart()"); + super.onStart(intent, startId); + } + + @Override + protected void onHandleIntent(Intent intent) { + if (intent != null && intent.hasExtra(INTENT_URL)) { + aClient.get(this, intent.getStringExtra(INTENT_URL), new AsyncHttpResponseHandler() { + @Override + public void onStart() { + sendBroadcast(new Intent(IntentServiceSample.ACTION_START)); + Log.d(LOG_TAG, "onStart"); + } + + @Override + public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { + Intent broadcast = new Intent(IntentServiceSample.ACTION_SUCCESS); + broadcast.putExtra(INTENT_STATUS_CODE, statusCode); + broadcast.putExtra(INTENT_HEADERS, IntentUtil.serializeHeaders(headers)); + broadcast.putExtra(INTENT_DATA, responseBody); + sendBroadcast(broadcast); + Log.d(LOG_TAG, "onSuccess"); + } + + @Override + public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { + Intent broadcast = new Intent(IntentServiceSample.ACTION_FAILURE); + broadcast.putExtra(INTENT_STATUS_CODE, statusCode); + broadcast.putExtra(INTENT_HEADERS, IntentUtil.serializeHeaders(headers)); + broadcast.putExtra(INTENT_DATA, responseBody); + broadcast.putExtra(INTENT_THROWABLE, error); + sendBroadcast(broadcast); + Log.d(LOG_TAG, "onFailure"); + } + + @Override + public void onCancel() { + sendBroadcast(new Intent(IntentServiceSample.ACTION_CANCEL)); + Log.d(LOG_TAG, "onCancel"); + } + + @Override + public void onRetry(int retryNo) { + sendBroadcast(new Intent(IntentServiceSample.ACTION_RETRY)); + Log.d(LOG_TAG, String.format(Locale.US, "onRetry: %d", retryNo)); + } + + @Override + public void onFinish() { + sendBroadcast(new Intent(IntentServiceSample.ACTION_FINISH)); + Log.d(LOG_TAG, "onFinish"); + } + }); + } + } +} diff --git a/sample/src/main/java/com/loopj/android/http/sample/services/package-info.java b/sample/src/main/java/com/loopj/android/http/sample/services/package-info.java new file mode 100644 index 000000000..df7d33ef2 --- /dev/null +++ b/sample/src/main/java/com/loopj/android/http/sample/services/package-info.java @@ -0,0 +1,19 @@ +/* + Android Asynchronous Http Client + Copyright (c) 2014 Marek Sebera + https://github.com/android-async-http/android-async-http + + 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 + + https://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.loopj.android.http.sample.services; \ No newline at end of file diff --git a/sample/src/main/java/com/loopj/android/http/sample/util/API8Util.java b/sample/src/main/java/com/loopj/android/http/sample/util/API8Util.java new file mode 100644 index 000000000..5f7364f4f --- /dev/null +++ b/sample/src/main/java/com/loopj/android/http/sample/util/API8Util.java @@ -0,0 +1,23 @@ +package com.loopj.android.http.sample.util; + +import java.lang.reflect.Array; + +public class API8Util { + + @SuppressWarnings("unchecked") + public static T[] copyOfRange(T[] original, int start, int end) { + int originalLength = original.length; // For exception priority compatibility. + if (start > end) { + throw new IllegalArgumentException(); + } + if (start < 0 || start > originalLength) { + throw new ArrayIndexOutOfBoundsException(); + } + int resultLength = end - start; + int copyLength = Math.min(resultLength, originalLength - start); + T[] result = (T[]) Array.newInstance(original.getClass().getComponentType(), resultLength); + System.arraycopy(original, start, result, 0, copyLength); + return result; + } + +} diff --git a/sample/src/main/java/com/loopj/android/http/sample/util/FileUtil.java b/sample/src/main/java/com/loopj/android/http/sample/util/FileUtil.java new file mode 100755 index 000000000..faa9b7f5d --- /dev/null +++ b/sample/src/main/java/com/loopj/android/http/sample/util/FileUtil.java @@ -0,0 +1,48 @@ +/* + Android Asynchronous Http Client Sample + Copyright (c) 2014 Marek Sebera + https://github.com/android-async-http/android-async-http + + 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 + + https://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.loopj.android.http.sample.util; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStream; +import java.io.InputStreamReader; + +// Source: https://stackoverflow.com/questions/12910503/android-read-file-as-string +public class FileUtil { + + public static String convertStreamToString(InputStream is) throws Exception { + BufferedReader reader = new BufferedReader(new InputStreamReader(is)); + StringBuilder sb = new StringBuilder(); + String line; + while ((line = reader.readLine()) != null) { + sb.append(line).append("\n"); + } + return sb.toString(); + } + + public static String getStringFromFile(File file) throws Exception { + FileInputStream fin = new FileInputStream(file); + String ret = convertStreamToString(fin); + //Make sure you close all streams. + fin.close(); + return ret; + } + +} diff --git a/sample/src/main/java/com/loopj/android/http/sample/util/IntentUtil.java b/sample/src/main/java/com/loopj/android/http/sample/util/IntentUtil.java new file mode 100644 index 000000000..dadb8be59 --- /dev/null +++ b/sample/src/main/java/com/loopj/android/http/sample/util/IntentUtil.java @@ -0,0 +1,32 @@ +package com.loopj.android.http.sample.util; + +import cz.msebera.android.httpclient.Header; +import cz.msebera.android.httpclient.message.BasicHeader; + +public class IntentUtil { + + public static String[] serializeHeaders(Header[] headers) { + if (headers == null) { + return new String[0]; + } + String[] rtn = new String[headers.length * 2]; + int index = -1; + for (Header h : headers) { + rtn[++index] = h.getName(); + rtn[++index] = h.getValue(); + } + return rtn; + } + + public static Header[] deserializeHeaders(String[] serialized) { + if (serialized == null || serialized.length % 2 != 0) { + return new Header[0]; + } + Header[] headers = new Header[serialized.length / 2]; + for (int i = 0, h = 0; h < headers.length; i++, h++) { + headers[h] = new BasicHeader(serialized[i], serialized[++i]); + } + return headers; + } + +} diff --git a/sample/src/main/java/com/loopj/android/http/sample/util/SampleJSON.java b/sample/src/main/java/com/loopj/android/http/sample/util/SampleJSON.java new file mode 100755 index 000000000..60413e5ed --- /dev/null +++ b/sample/src/main/java/com/loopj/android/http/sample/util/SampleJSON.java @@ -0,0 +1,77 @@ +/* + Android Asynchronous Http Client Sample + Copyright (c) 2014 Marek Sebera + https://github.com/android-async-http/android-async-http + + 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 + + https://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.loopj.android.http.sample.util; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class SampleJSON { + + private String Accept; + private String Referer; + private String AcceptLanguage; + private String Connection; + private String UserAgent; + + public String getAccept() { + return Accept; + } + + @JsonProperty("Accept") + public void setAccept(String accept) { + Accept = accept; + } + + public String getReferer() { + return Referer; + } + + @JsonProperty("Referer") + public void setReferer(String referer) { + Referer = referer; + } + + public String getAcceptLanguage() { + return AcceptLanguage; + } + + @JsonProperty("Accept-Language") + public void setAcceptLanguage(String acceptLanguage) { + AcceptLanguage = acceptLanguage; + } + + public String getConnection() { + return Connection; + } + + @JsonProperty("Connection") + public void setConnection(String connection) { + Connection = connection; + } + + public String getUserAgent() { + return UserAgent; + } + + @JsonProperty("User-Agent") + public void setUserAgent(String userAgent) { + UserAgent = userAgent; + } +} diff --git a/sample/src/main/java/com/loopj/android/http/sample/util/SecureSocketFactory.java b/sample/src/main/java/com/loopj/android/http/sample/util/SecureSocketFactory.java new file mode 100644 index 000000000..fddcafcbe --- /dev/null +++ b/sample/src/main/java/com/loopj/android/http/sample/util/SecureSocketFactory.java @@ -0,0 +1,197 @@ +/* + Android Asynchronous Http Client Sample + Copyright (c) 2014 Marek Sebera + https://github.com/android-async-http/android-async-http + + 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 + + https://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.loopj.android.http.sample.util; + +import android.util.Log; + +import com.loopj.android.http.AsyncHttpClient; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Field; +import java.net.InetAddress; +import java.net.Socket; +import java.security.InvalidKeyException; +import java.security.KeyManagementException; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.NoSuchProviderException; +import java.security.SignatureException; +import java.security.UnrecoverableKeyException; +import java.security.cert.Certificate; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; + +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSocket; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; + +import cz.msebera.android.httpclient.conn.ssl.SSLSocketFactory; + +/** + * A class to authenticate a secured connection against a custom CA using a BKS store. + * + * @author Noor Dawod + */ +public class SecureSocketFactory extends SSLSocketFactory { + + private static final String LOG_TAG = "SecureSocketFactory"; + + private final SSLContext sslCtx; + private final X509Certificate[] acceptedIssuers; + + /** + * Instantiate a new secured factory pertaining to the passed store. Be sure to initialize the + * store with the password using {@link java.security.KeyStore#load(java.io.InputStream, + * char[])} method. + * + * @param store The key store holding the certificate details + * @param alias The alias of the certificate to use + */ + public SecureSocketFactory(KeyStore store, String alias) + throws + CertificateException, + NoSuchAlgorithmException, + KeyManagementException, + KeyStoreException, + UnrecoverableKeyException { + + super(store); + + // Loading the CA certificate from store. + final Certificate rootca = store.getCertificate(alias); + + // Turn it to X509 format. + InputStream is = new ByteArrayInputStream(rootca.getEncoded()); + X509Certificate x509ca = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(is); + AsyncHttpClient.silentCloseInputStream(is); + + if (null == x509ca) { + throw new CertificateException("Embedded SSL certificate has expired."); + } + + // Check the CA's validity. + x509ca.checkValidity(); + + // Accepted CA is only the one installed in the store. + acceptedIssuers = new X509Certificate[]{x509ca}; + + sslCtx = SSLContext.getInstance("TLS"); + sslCtx.init( + null, + new TrustManager[]{ + new X509TrustManager() { + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { + } + + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { + Exception error = null; + + if (null == chain || 0 == chain.length) { + error = new CertificateException("Certificate chain is invalid."); + } else if (null == authType || 0 == authType.length()) { + error = new CertificateException("Authentication type is invalid."); + } else { + Log.i(LOG_TAG, "Chain includes " + chain.length + " certificates."); + try { + for (X509Certificate cert : chain) { + Log.i(LOG_TAG, "Server Certificate Details:"); + Log.i(LOG_TAG, "---------------------------"); + Log.i(LOG_TAG, "IssuerDN: " + cert.getIssuerDN().toString()); + Log.i(LOG_TAG, "SubjectDN: " + cert.getSubjectDN().toString()); + Log.i(LOG_TAG, "Serial Number: " + cert.getSerialNumber()); + Log.i(LOG_TAG, "Version: " + cert.getVersion()); + Log.i(LOG_TAG, "Not before: " + cert.getNotBefore().toString()); + Log.i(LOG_TAG, "Not after: " + cert.getNotAfter().toString()); + Log.i(LOG_TAG, "---------------------------"); + + // Make sure that it hasn't expired. + cert.checkValidity(); + + // Verify the certificate's public key chain. + cert.verify(rootca.getPublicKey()); + } + } catch (InvalidKeyException e) { + error = e; + } catch (NoSuchAlgorithmException e) { + error = e; + } catch (NoSuchProviderException e) { + error = e; + } catch (SignatureException e) { + error = e; + } + } + if (null != error) { + Log.e(LOG_TAG, "Certificate error", error); + throw new CertificateException(error); + } + } + + @Override + public X509Certificate[] getAcceptedIssuers() { + return acceptedIssuers; + } + } + }, + null + ); + + setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER); + } + + @Override + public Socket createSocket(Socket socket, String host, int port, boolean autoClose) + throws IOException { + + injectHostname(socket, host); + Socket sslSocket = sslCtx.getSocketFactory().createSocket(socket, host, port, autoClose); + + // throw an exception if the hostname does not match the certificate + getHostnameVerifier().verify(host, (SSLSocket) sslSocket); + + return sslSocket; + } + + @Override + public Socket createSocket() throws IOException { + return sslCtx.getSocketFactory().createSocket(); + } + + /** + * Pre-ICS Android had a bug resolving HTTPS addresses. This workaround fixes that bug. + * + * @param socket The socket to alter + * @param host Hostname to connect to + * @see https://code.google.com/p/android/issues/detail?id=13117#c14 + */ + private void injectHostname(Socket socket, String host) { + try { + Field field = InetAddress.class.getDeclaredField("hostName"); + field.setAccessible(true); + field.set(socket.getInetAddress(), host); + } catch (Exception ignored) { + } + } +} diff --git a/sample/src/main/java/com/loopj/android/http/sample/util/package-info.java b/sample/src/main/java/com/loopj/android/http/sample/util/package-info.java new file mode 100644 index 000000000..7d28904fd --- /dev/null +++ b/sample/src/main/java/com/loopj/android/http/sample/util/package-info.java @@ -0,0 +1,19 @@ +/* + Android Asynchronous Http Client + Copyright (c) 2014 Marek Sebera + https://github.com/android-async-http/android-async-http + + 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 + + https://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.loopj.android.http.sample.util; \ No newline at end of file diff --git a/sample/src/main/res/drawable-hdpi/ic_launcher.png b/sample/src/main/res/drawable-hdpi/ic_launcher.png new file mode 100644 index 000000000..d95d16f9e Binary files /dev/null and b/sample/src/main/res/drawable-hdpi/ic_launcher.png differ diff --git a/sample/src/main/res/drawable-mdpi/ic_launcher.png b/sample/src/main/res/drawable-mdpi/ic_launcher.png new file mode 100644 index 000000000..75b78337f Binary files /dev/null and b/sample/src/main/res/drawable-mdpi/ic_launcher.png differ diff --git a/sample/src/main/res/drawable-xhdpi/ic_launcher.png b/sample/src/main/res/drawable-xhdpi/ic_launcher.png new file mode 100644 index 000000000..52a6abdd7 Binary files /dev/null and b/sample/src/main/res/drawable-xhdpi/ic_launcher.png differ diff --git a/sample/src/main/res/drawable-xxhdpi/ic_launcher.png b/sample/src/main/res/drawable-xxhdpi/ic_launcher.png new file mode 100644 index 000000000..d75067ca9 Binary files /dev/null and b/sample/src/main/res/drawable-xxhdpi/ic_launcher.png differ diff --git a/sample/src/main/res/drawable-xxxhdpi/ic_launcher.png b/sample/src/main/res/drawable-xxxhdpi/ic_launcher.png new file mode 100644 index 000000000..927c4a26c Binary files /dev/null and b/sample/src/main/res/drawable-xxxhdpi/ic_launcher.png differ diff --git a/sample/src/main/res/layout-v14/parent_layout.xml b/sample/src/main/res/layout-v14/parent_layout.xml new file mode 100755 index 000000000..bf796eb99 --- /dev/null +++ b/sample/src/main/res/layout-v14/parent_layout.xml @@ -0,0 +1,100 @@ + + + + + + + + + + + +