Commit 09c88efe authored by Chok's avatar Chok
Browse files

chok: init commit

parent 02cfb854
Pipeline #18 failed with stages
in 0 seconds
# EditorConfig helps developers define and maintain consistent
# coding styles between different editors and IDEs
# editorconfig.org
root = true
[*]
# Change these settings to your own preference
indent_style = space
indent_size = 2
# We recommend you to keep these unchanged
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.md]
trim_trailing_whitespace = false
github: silkimen
---
name: "\U0001F41BBug report"
about: Create a report to help us improve
title: "[Bug] [platform] your issue title"
labels: ''
assignees: ''
---
**Describe the bug**
A clear and concise description of what the bug is and what you expected to happen.
**System info**
- affected HTTP plugin version: [e.g. 2.1.1]
- affected platform(s) and version(s): [e.g. iOS 12.2]
- affected device(s): [e.g. iPhone 8]
- cordova version: [e.g. 6.5.0]
- cordova platform version(s): [e.g. android 7.0.0, browser 5.0.3]
**Are you using ionic-native-wrapper?**
- ionic-native-wrapper version: [e.g. 5.8.0]
- did you check [ionic-native issue tracker](https://github.com/ionic-team/ionic-native/issues) for your problem?
**Minimum viable code to reproduce**
If applicable, add formatted sample coding to help explain your problem.
e.g.:
```js
cordova.plugin.http.setDataSerializer('urlencoded');
```
**Screenshots**
If applicable, add screenshots to help explain your problem.
---
name: "\U0001F680Feature request"
about: Suggest an idea for this project
title: "[Feature]"
labels: ''
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. e.g. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen. If applicable, add formatted sample coding to help explain your idea.
```js
// do some fancy stuff here
```
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
---
name: "\U0001F914Support question"
about: Ask the community
title: ''
labels: question
assignees: ''
---
**You've got questions?**
We primarily use GitHub as an issue tracker; for usage and support questions, please check out these resources below. Thanks! 😁
* README.md: https://github.com/silkimen/cordova-plugin-advanced-http/blob/master/README.md
* StackOverflow: https://stackoverflow.com/questions/tagged/cordova-plugin-advanced-http using the tag `cordova-plugin-advanced-http`
* Wiki: https://github.com/silkimen/cordova-plugin-advanced-http/wiki
And don't forget: If you get help, help others. Good karma rulez!
name: Cordova HTTP Plugin CI
on: [push]
env:
nodejs: "16.x"
BROWSERSTACK_USERNAME: ${{ secrets.BROWSERSTACK_USERNAME }}
BROWSERSTACK_ACCESS_KEY: ${{ secrets.BROWSERSTACK_ACCESS_KEY }}
jobs:
test-www-interface:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Install Node.js ${{ env.nodejs }}
uses: actions/setup-node@v1
with:
node-version: ${{ env.nodejs }}
- name: Install node modules
run: npm ci
- name: Run WWW interface tests
run: npm run test:js
build-ios:
runs-on: macOS-latest
steps:
- uses: actions/checkout@v1
- name: Install Node.js ${{ env.nodejs }}
uses: actions/setup-node@v1
with:
node-version: ${{ env.nodejs }}
- name: Install node modules
run: npm ci
- name: Update test cert for httpbin.org
run: npm run update:cert
# need to find a solution for signing iOS App so we can build for device target instead simulator
- name: Build test app
run: scripts/build-test-app.sh --ios --emulator
- name: Upload artifact to BrowserStack
if: env.BROWSERSTACK_USERNAME != ''
run: scripts/upload-browserstack.sh --ios
# need to have an App for device target
# - name: Run e2e tests
# if: env.BROWSERSTACK_USERNAME != ''
# run: scripts/test-app.sh --ios --device
build-android:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Install Node.js ${{ env.nodejs }}
uses: actions/setup-node@v1
with:
node-version: ${{ env.nodejs }}
- name: Install node modules
run: npm ci
- name: Install JDK 1.8
uses: actions/setup-java@v1
with:
java-version: 1.8
- name: Update test cert for httpbin.org
run: npm run update:cert
- name: Add workaround for missing DX files in build-tools 32 (https://stackoverflow.com/a/68430992)
run: ln -s $ANDROID_HOME/build-tools/32.0.0/d8 $ANDROID_HOME/build-tools/32.0.0/dx && ln -s $ANDROID_HOME/build-tools/32.0.0/lib/d8.jar $ANDROID_HOME/build-tools/32.0.0/lib/dx.jar
- name: Build test app
run: scripts/build-test-app.sh --android --device
- name: Upload artifact to BrowserStack
if: env.BROWSERSTACK_USERNAME != ''
run: scripts/upload-browserstack.sh --android
- name: Run e2e tests
if: env.BROWSERSTACK_USERNAME != ''
run: scripts/test-app.sh --android --device
# For most projects, this workflow file will not need changing; you simply need
# to commit it to your repository.
#
# You may wish to alter this file to override the set of languages analyzed,
# or to provide custom queries or build logic.
name: "CodeQL"
on:
push:
branches: [master]
pull_request:
# The branches below must be a subset of the branches above
branches: [master]
schedule:
- cron: '0 20 * * 3'
jobs:
analyze:
name: Analyze
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
# Override automatic language detection by changing the below list
# Supported options are ['csharp', 'cpp', 'go', 'java', 'javascript', 'python']
language: ['javascript']
# Learn more...
# https://docs.github.com/en/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#overriding-automatic-language-detection
steps:
- name: Checkout repository
uses: actions/checkout@v2
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v1
with:
languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file.
# By default, queries listed here will override any specified in a config file.
# Prefix the list here with "+" to use these queries and those in the config file.
# queries: ./path/to/local/query, your-org/your-repo/queries@main
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
uses: github/codeql-action/autobuild@v1
# ℹ️ Command-line programs to run using the OS shell.
# 📚 https://git.io/JvXDl
# ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
# and modify them (or add more) to build your code if your project
# uses a compiled language
#- run: |
# make bootstrap
# make release
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v1
cache:
directories:
- node_modules
addons:
sauce_connect: true
matrix:
include:
- name: "iOS Build & Test"
language: objective-c
sudo: false
os: osx
osx_image: xcode12.5
before_install:
- export LANG=en_US.UTF-8 &&
nvm use 14
install:
- npm install
script:
- npm run test:js &&
npm run update:cert &&
scripts/build-test-app.sh --ios --emulator &&
scripts/upload-saucelabs.sh --ios &&
scripts/test-app.sh --ios --emulator;
- name: "Android Build & Test"
language: android
sudo: required
android:
components:
- tools
- platform-tools
- build-tools-30.0.1
- android-28
- extra-android-support
- extra-android-m2repository
- extra-google-m2repository
before_install:
- export LANG=en_US.UTF-8 &&
curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash - &&
sudo apt-get install -y nodejs
- yes | sdkmanager --update
install:
- npm install
script:
- npm run test:js &&
npm run update:cert &&
scripts/build-test-app.sh --android --emulator &&
scripts/upload-saucelabs.sh --android &&
scripts/test-app.sh --android --emulator;
{
"editor.tabSize": 2
}
\ No newline at end of file
# Changelog
# 3.3.1
- Fixed #427: missing connection check on Android (thanks moshe5745)
- Fixed #459: namespace collision on iOS when another plugin is also using AFNetworking (thanks zafirskthelifehacker)
- Fixed #429: intermediate CA certs are not respected on iOS when using client certs (thanks pavrda)
- Fixed #444: errors are not handled when invalid header values are applied on browser (thanks @MobisysGmbH)
- Fixed #441: sensible data can be cached in cache.db on iOS (thanks dtarnawsky)
# 3.3.0
- Feature #451: expose response object on `downloadFile()` (thanks to @MobisysGmbH)
# 3.2.2
- Fixed #438: requests not working correctly on browser platform because request options are not processed correctly
## 3.2.1
- Fixed #425: plugin crashes on Android SDK levels < 24
- Fixed #418: deprecated AFNetworking method causes app crash (thanks meiram-tr)
- Fixed #404: wrong timeout implementation (thanks YouYue123)
## 3.2.0
- Feature #420: implement blacklist feature to disable SSL/TLS versions on Android (thanks to @MobisysGmbH)
## 3.1.1
- Fixed #372: malformed empty multipart request on Android
- Fixed #399: memory leakage leads to app crashes on iOS (thanks avargaskun)
## 3.1.0
- Feature #272: add support for aborting requests (thanks russaa)
## 3.0.1
- Fixed #359: memory leakage leads to app crashes on Android
- Fixed #355: responseType "json" not working with valid JSON response on browser (thanks millerg6711)
## 3.0.0
- Feature #158: support removing headers which were previously set via "setHeader"
- Fixed #345: empty file names are not handled correctly (thanks ikosta)
- :warning: **Breaking Change**: Dropped support for Android < 5.1
- :warning: **Breaking Change**: Removed "disableRedirect", use "setFollowRedirect" instead
- :warning: **Breaking Change**: Removed "setSSLCertMode", use "setServerTrustMode" instead
## 2.5.1
- Fixed #334: empty JSON response triggers error even though request is successful (thanks antikalk)
- Fixed #248: clearCookies() does not work on iOS
## 2.5.0
- Feature #56: add support for X.509 client certificate based authentication
## 2.4.1
- Fixed #296: multipart requests are not serialized on browser platform
- Fixed #301: data is not decoded correctly when responseType is "json" (thanks antikalk)
- Fixed #300: FormData object containing null or undefined value is not serialized correctly
## 2.4.0
- Feature #291: add support for sending 'raw' requests (thanks to jachstet-sea and chuchuva)
- Feature #155: add OPTIONS method
- Feature #283: improve error message on timeout on browser platform
## 2.3.1
- Fixed #275: getAllCookies() is broken because of a typo (thanks ath0mas)
## 2.3.0
- Feature #101: Support "multipart/form-data" requests (thanks SDA SE Open Industry Solutions)
#### Important information
This feature depends on several Web APIs. See https://github.com/silkimen/cordova-plugin-advanced-http/wiki/Web-APIs-required-for-Multipart-requests for more info.
## 2.2.0
- Feature #239: add enumeration style object for error codes
- Feature #253: add support for response type "json"
- Feature #127: add multiple file upload (thanks SDA SE Open Industry Solutions and nilswitschel)
## 2.1.1
- Fixed #224: response type "arraybuffer" and "blob" not working on browser platform
## 2.1.0
- Feature #216: Support for response type `arraybuffer`
- Feature #171: Support for response type `blob`
- Feature #205: Add preference for configuring OKHTTP version (thanks RougeCiel)
## 2.0.11
- Fixed #221: headers not set on Android when request fails due to non-success status code
## 2.0.10
- Fixed #218: headers are used as params on browser platform
## 2.0.9
- Fixed #204: broken support for cordova-android < 7.0
- :warning: **Deprecation**: Deprecated "disableRedirect" in favor of "setFollowRedirect"
## 2.0.8
- Fixed #198: cookie header is always passed even if there is no cookie
- Fixed #201: browser implementation is broken due to broken dependency
- Fixed #197: iOS crashes when multiple request are done simultaneously (reverted a8e3637)
- Fixed #189: error code mappings are not precise
- Fixed #200: compatibility with Java 6 is broken due to string switch on Android
- :warning: **Deprecation**: Deprecated "setSSLCertMode" in favor of "setServerTrustMode"
## 2.0.7
- Fixed #195: URLs are double-encoded on Android
## 2.0.6
- Fixed #187: setSSLCertMode with "default" throws an error on Android
- Fixed #115: HTTP connections are not kept alive on iOS (thanks MorpheusDe97)
## 2.0.5
- Fixed #185: need more detailed SSL error message
## 2.0.4
- Fixed #179: sending empty string with utf8 serializer throws an exception
## 2.0.3
- Fixed #172: plugin does not respect user installed CA certs on Android
#### Important information
We've changed a default behavior on Android. User installed CA certs are respected now.
If you don't want this for your needs, you can switch back to old behavior by setting SSL cert mode to `legacy`.
## 2.0.2
- Fixed #142: Plugin affected by REDoS Issue of tough-cookie
- Fixed #157: Arguments are double URL-encoded on "downloadFile" (thanks TheZopo)
- Fixed #164: Arguments are double URL-encoded on "head" (thanks ath0mas)
## 2.0.1
- Fixed #136: Content-Type header non-overwritable on browser platform
## 2.0.0
- Feature #103: implement HTTP SSL cert modes
- :warning: **Breaking Change**: Removed AngularJS (v1) integration service
- :warning: **Breaking Change**: Removed "enableSSLPinning" and "acceptAllCerts", use "setSSLCertMode" instead
- :warning: **Breaking Change**: Certificates must be placed in "www/certificates" folder
## 1.11.1
- Fixed #92: headers not deserialized on platform "browser"
## 1.11.0
- Feature #77: allow overriding global settings for each single request
- Feature #11: add support for "browser" platform
## 1.10.2
- Fixed #78: overriding header "Content-Type" not working on Android
- Fixed #79: PATCH operation not working on Android API level 19 and older (thanks chax)
- Fixed #83: App crashes on error during download operation on iOS (thanks troyanskiy)
- Fixed #76: upload sequence is not respecting order of operations needed by some sites (thanks Johny101)
- :warning: **Deprecation**: AngularJS service is deprecated now and will be removed anytime soon
## 1.10.1
- Fixed #71: does not encode query string in URL correctly on Android
- Fixed #72: app crashes if response encoding is not UTF-8 (thanks jkfb)
## 1.10.0
- Feature #34: add new serializer "utf8" sending utf-8 encoded plain text (thanks robertocapuano)
## 1.9.1
- Fixed #45: does not encode arrays correctly as HTTP GET parameter on Android
- Fixed #54: requests are not responding on iOS with non-string values in header object
- Fixed #58: white-list of allowed content-types should be removed for iOS
## v1.9.0
- Feature #44: "getCookieString" method is exposed
- Feature #43: added support for content type "application/javascript" on iOS (thanks wh33ler)
- Feature #46: "setCookie" allows adding custom cookies
## v1.8.1
- Fixed #27: "uploadFile" method doesn't return data object on iOS (thanks Faisalali23 and laiyinjie)
- Fixed #40: generic error codes are different on Android and iOS
## v1.8.0
- Feature #33: response object contains response url
## v1.7.1
- Fixed #36: setting basic authentication not working correctly (thanks jkfb)
- Fixed #35: Android headers are not normalized (not returned in lowercase)
- Fixed #26: JSON request with array data is not working on Android (JSON error)
## v1.7.0
- Feature #24: "setHeader" allows configuring headers for specified host
## v1.6.2
- Change #29: removed "validateDomainName" (see info notice)
- Fixed #31: request fails throwing error on erroneous cookies
- Fixed #28: added support for content type "application/hal+json" on iOS (thanks ryandegruyter)
#### Important information
We've decided to remove the `validateDomainName()` method, because people were complaining that `acceptAllCerts(true)` is not behaving as expected. And also it's not a good idea to disable domain name validation while using valid certs, because it pretends having a secure connection, but it isn't.
You should either use valid certs with domain name validation enabled (safe for production use) or accept any certs without domain name validation (only for private dev environments). I strongly discourage using fake certs in public networks.
Therefore we are disabling domain name validation automatically, when you set `acceptAllCerts(true)`. So if you were using `validateDomainName()` function, you need to remove this function call for v1.6.2+.
## v1.6.1
- Fixed #23: PATCH method broken on android
## v1.6.0
- Feature #18: implemented PATCH method (thanks akhatri for android implementation)
- Feature #21: added redirection control (thanks to notsyncing and kesozjura)
- Fixed #16: cordova tries to run build script during plugin install
## v1.5.10
- Fixed #10: fix gzip decompression when request header accepts gzip compression (thanks to DayBr3ak)
- Fixed #13: fix angular integration for `setDataSerializer` (thanks to RangerRick)
- Added some missing documentation (thanks to RangerRick)
## v1.5.9
- Fixed case-sensitive folder name of Android source files
## v1.5.8
- Use the same error codes if a request timed out
## v1.5.7
- Fixed a bug in cookie handling (cookies containing an "Expires" string)
- Added setRequestTimeout function to set the timeout in seconds for all further requests
## v1.5.6
- All response header keys are converted to lowercase (iOS only)
## v1.5.5
- added a function to remove all cookies for a URL
## v1.5.4
- fixed an error if the response has no "headers" field
## v1.5.3
- handles cookies correctly on non-success response from server
- throws error when a callback function is missing
## v1.5.2
- fixed missing file "umd-tough-cookie.js“ (caused by missing file ".npmignore")
## v1.5.1
- fixed case-sensitive path name of android source files ("CordovaHTTP" --> "cordovahttp")
## v1.5.0
- added cookie handling
- cookies are persisted via web storage API
## v1.4.0
- forked from "cordova-plugin-http" v1.2.0 (see https://github.com/wymsee/cordova-HTTP)
- added configuration for data serializer
- added HTTP methods PUT and DELETE
# Previous changelog (cordova-plugin-http)
## v1.2.0
- Added support for TLSv1.1 and TLSv1.2 for android versions 4.1-4.4 (API levels 16-19)
### Potentially Breaking Changes that really shouldn't matter because you shouldn't be using SSLv3
- Dropped SSLv3 support for all API Levels < 20. It will now only work on API Levels 20-22.
## v1.1.0
- Fixed the body of errors not being returned in iOS
- Updated AFNetworking to 3.1.0
### Potentially Breaking Changes
- Disable encoding get() URLS in android (Thanks to devgeeks)
## v1.0.3
- Fixed version number in plugin.xml
## v1.0.2
- Fixed bug using useBasicAuth and setHeader from angular
## v1.0.1
- updated README
## v1.0.0
- Added getBasicAuthHeader function
- Added necessary iOS framework (Thanks to EddyVerbruggen)
- Request internet permission in android (Thanks to mbektchiev)
- Fix acceptAllCerts doesn't call callbacks (Thanks to EddyVerbruggen)
- Add validateDomainName (Thanks to denisbabineau)
- Add HEAD request support (untested) (Thanks to denisbabineau)
### Potentially Breaking Changes
- Update cordova file plugin dependency (Thanks to denisbabineau)
- useBasicAuthHeader and setHeader are now synchronous functions
- updated AFNetworking to 3.0.4 - only iOS 7+ is now supported
- updated http-request to 6.0
## v0.1.4
- Support for certificates in www/certificates folder (Thanks to EddyVerbruggen)
## v0.1.3
- Update AFNetworking to 2.4.1 for iOS bug fix in Xcode 6
## v0.1.2
- Fixed plugin.xml for case sensitive filesystems (Thanks to andrey-tsaplin)
## v0.1.1
- Fixed a bug that prevented building
## v0.1.0
- Initial release
## Contributions not noted above
- Fixed examples (Thanks to devgeeks)
- Reports SSL Handshake errors rather than giving a generic error (Thanks to devgeeks)
- Exporting http as a module (Thanks to pvsaikrishna)
- Added Limitations section to readme (Thanks to cvillerm)
- Fixed examples (Thanks to hideov)
# Contributing to Advanced HTTP Plugin
We'd love for you to contribute to our source code and to make Advanced HTTP even better than it is
today! Here are the guidelines we'd like you to follow:
- [Issues and Bugs](#issue)
- [Feature Requests](#feature)
- [Submission Guidelines](#submit)
## <a name="issue"></a> Found an Issue?
If you find a bug in the source code or a mistake in the documentation, you can help us by
submitting an issue to our [GitHub Repository](https://github.com/silkimen/cordova-plugin-advanced-http/issues).
Even better you can submit a Pull Request with a fix.
## <a name="feature"></a> Want a Feature?
You can request a new feature by submitting an issue to our
[GitHub Repository](https://github.com/silkimen/cordova-plugin-advanced-http/issues).
If you would like to implement a new feature then consider what kind of change it is:
* **Major Changes** that you wish to contribute to the project should be discussed first so that we
can better coordinate our efforts, prevent duplication of work, and help you to craft the change
so that it is successfully accepted into the project. Please submit an issue to our GitHub Repository
for discussion.
* **Small Changes** can be crafted and submitted to the GitHub Repository as a Pull Request.
## <a name="submit"></a> Submission Guidelines
### Submitting an Issue
Before you submit your issue search the archive, maybe your question was already answered.
If your issue appears to be a bug, and hasn't been reported, open a new issue. Help us to maximize
the effort we can spend fixing issues and adding new features, by not reporting duplicate issues.
Providing the following information will increase the chances of your issue being dealt with
quickly:
* **Overview of the Issue** - if an error is being thrown a non-minified stack trace helps
* **Motivation for or Use Case** - explain why this is a bug for you
* **Advanced HTTP Version(s)** - is it a regression?
* **Operating System** - is this a problem with all supported OS or only specific ones?
* **Related Issues** - has a similar issue been reported before?
* **Suggest a Fix** - if you can't fix the bug yourself, perhaps you can point to what might be
causing the problem (line of code or commit)
**If you get help, help others. Good karma rulez!**
### Submitting a Pull Request
Before you submit your pull request consider the following guidelines:
* Search [GitHub](https://github.com/silkimen/cordova-plugin-advanced-http/pulls) for an open or
closed Pull Request that relates to your submission. You don't want to duplicate effort.
* Make your changes in a new git branch:
```shell
git checkout -b my-fix-branch master
```
* Create your patch
* Commit your changes using a descriptive commit message
* Push your branch to GitHub:
```shell
git push origin my-fix-branch
```
In GitHub, send a pull request to `cordova-plugin-advanced-http:master`.
If we suggest changes or the [CI build fails](#cibuild), then:
* Make the required updates.
* Commit your changes to your branch (e.g. `my-fix-branch`).
* Push the changes to your GitHub repository (this will update your Pull Request).
That's it! Thank you for your contribution!
### <a name="cibuild"></a> Pull Request Feedback
You can always check the results of the latest CI builds on
[Travis CI](https://travis-ci.org/silkimen/cordova-plugin-advanced-http/).
You can use this information to inspect failing tests in your PR.
## Attribution
This document is adapted from
[AngularJS' Contribution Guidelines](https://github.com/angular/angular.js/blob/master/CONTRIBUTING.md)
The MIT License (MIT)
Copyright (c) 2019 Sefa Ilkimen
Copyright (c) 2017 Mobisys GmbH
Copyright (c) 2014 Wymsee, Inc
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
This diff is collapsed.
# Cordova Plugin Advanced Http
## Getting started
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
## Add your files
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
```
cd existing_repo
git remote add origin http://dev.silverlakemobility.com/gitlab/cordova-custom/cordova-plugin-advanced-http.git
git branch -M main
git push -uf origin main
```
## Integrate with your tools
- [ ] [Set up project integrations](http://dev.silverlakemobility.com/gitlab/cordova-custom/cordova-plugin-advanced-http/-/settings/integrations)
## Collaborate with your team
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Automatically merge when pipeline succeeds](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
## Test and Deploy
Use the built-in continuous integration in GitLab.
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
***
# Editing this README
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template.
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## Name
Choose a self-explaining name for your project.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
## License
For open source projects, say how it is licensed.
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
{
"name": "cordova-plugin-advanced-http",
"version": "3.3.1",
"description": "Cordova / Phonegap plugin for communicating with HTTP servers using SSL pinning",
"scripts": {
"update:cert": "node ./scripts/update-e2e-server-cert.js && node ./scripts/update-e2e-client-cert.js",
"build:browser": "./scripts/build-test-app.sh --browser",
"build:android": "./scripts/build-test-app.sh --android --emulator",
"build:ios": "./scripts/build-test-app.sh --ios --emulator",
"test:android": "npm run update:cert && npm run build:android && ./scripts/test-app.sh --android --emulator",
"test:ios": "npm run update:cert && npm run build:ios && ./scripts/test-app.sh --ios --emulator",
"test:app": "npm run test:android && npm run test:ios",
"test:js": "mocha ./test/js-specs.js",
"test": "npm run test:js && npm run test:app",
"release": "npm run test && ./scripts/release.sh"
},
"cordova": {
"id": "cordova-plugin-advanced-http",
"platforms": [
"ios",
"android"
]
},
"repository": {
"type": "git",
"url": "git+https://github.com/silkimen/cordova-plugin-advanced-http.git"
},
"keywords": [
"cordova",
"device",
"ecosystem:cordova",
"cordova-ios",
"cordova-android",
"ssl",
"tls"
],
"engines": [
{
"name": "cordova",
"version": ">=4.0.0"
}
],
"author": "Wymsee",
"contributors": [
"devgeeks",
"EddyVerbruggen",
"mbektchiev",
"denisbabineau",
"andrey-tsaplin",
"pvsaikrishna",
"cvillerm",
"hideov",
"silkimen"
],
"license": "MIT",
"bugs": {
"url": "https://github.com/silkimen/cordova-plugin-advanced-http/issues"
},
"homepage": "https://github.com/silkimen/cordova-plugin-advanced-http#readme",
"devDependencies": {
"chai": "4.3.6",
"colors": "1.4.0",
"cordova": "11.0.0",
"mocha": "9.2.2",
"umd-tough-cookie": "3.0.0",
"wd": "1.14.0",
"xml2js": "0.4.23"
}
}
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<plugin xmlns="http://www.phonegap.com/ns/plugins/1.0" xmlns:android="http://schemas.android.com/apk/res/android" id="cordova-plugin-advanced-http" version="3.3.1">
<name>Advanced HTTP plugin</name>
<description>
Cordova / Phonegap plugin for communicating with HTTP servers using SSL pinning
</description>
<engines>
<engine name="cordova" version=">=4.0.0"/>
</engines>
<dependency id="cordova-plugin-file" version=">=2.0.0"/>
<preference name="AndroidBlacklistSecureSocketProtocols" default="SSLv3,TLSv1"/>
<js-module src="www/cookie-handler.js" name="cookie-handler"/>
<js-module src="www/dependency-validator.js" name="dependency-validator"/>
<js-module src="www/error-codes.js" name="error-codes"/>
<js-module src="www/global-configs.js" name="global-configs"/>
<js-module src="www/helpers.js" name="helpers"/>
<js-module src="www/js-util.js" name="js-util"/>
<js-module src="www/local-storage-store.js" name="local-storage-store"/>
<js-module src="www/lodash.js" name="lodash"/>
<js-module src="www/messages.js" name="messages"/>
<js-module src="www/ponyfills.js" name="ponyfills"/>
<js-module src="www/public-interface.js" name="public-interface"/>
<js-module src="www/umd-tough-cookie.js" name="tough-cookie"/>
<js-module src="www/url-util.js" name="url-util"/>
<js-module src="www/advanced-http.js" name="http">
<clobbers target="cordova.plugin.http"/>
</js-module>
<platform name="ios">
<config-file target="config.xml" parent="/*">
<feature name="CordovaHttpPlugin">
<param name="ios-package" value="CordovaHttpPlugin"/>
</feature>
</config-file>
<header-file src="src/ios/CordovaHttpPlugin.h"/>
<header-file src="src/ios/BinaryRequestSerializer.h"/>
<header-file src="src/ios/BinaryResponseSerializer.h"/>
<header-file src="src/ios/TextResponseSerializer.h"/>
<header-file src="src/ios/TextRequestSerializer.h"/>
<header-file src="src/ios/SM_AFNetworking/SM_AFHTTPSessionManager.h"/>
<header-file src="src/ios/SM_AFNetworking/SM_AFNetworking.h"/>
<header-file src="src/ios/SM_AFNetworking/SM_AFNetworkReachabilityManager.h"/>
<header-file src="src/ios/SM_AFNetworking/SM_AFSecurityPolicy.h"/>
<header-file src="src/ios/SM_AFNetworking/SM_AFURLRequestSerialization.h"/>
<header-file src="src/ios/SM_AFNetworking/SM_AFURLResponseSerialization.h"/>
<header-file src="src/ios/SM_AFNetworking/SM_AFURLSessionManager.h"/>
<header-file src="src/ios/SDNetworkActivityIndicator/SDNetworkActivityIndicator.h"/>
<source-file src="src/ios/CordovaHttpPlugin.m"/>
<source-file src="src/ios/BinaryRequestSerializer.m"/>
<source-file src="src/ios/BinaryResponseSerializer.m"/>
<source-file src="src/ios/TextResponseSerializer.m"/>
<source-file src="src/ios/TextRequestSerializer.m"/>
<source-file src="src/ios/SM_AFNetworking/SM_AFHTTPSessionManager.m"/>
<source-file src="src/ios/SM_AFNetworking/SM_AFNetworkReachabilityManager.m"/>
<source-file src="src/ios/SM_AFNetworking/SM_AFSecurityPolicy.m"/>
<source-file src="src/ios/SM_AFNetworking/SM_AFURLRequestSerialization.m"/>
<source-file src="src/ios/SM_AFNetworking/SM_AFURLResponseSerialization.m"/>
<source-file src="src/ios/SM_AFNetworking/SM_AFURLSessionManager.m"/>
<source-file src="src/ios/SDNetworkActivityIndicator/SDNetworkActivityIndicator.m"/>
<framework src="Security.framework"/>
<framework src="SystemConfiguration.framework"/>
</platform>
<platform name="android">
<config-file target="res/xml/config.xml" parent="/*">
<feature name="CordovaHttpPlugin">
<param name="android-package" value="com.silkimen.cordovahttp.CordovaHttpPlugin"/>
</feature>
</config-file>
<config-file target="AndroidManifest.xml" parent="/manifest">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
</config-file>
<source-file src="src/android/com/silkimen/cordovahttp/CordovaClientAuth.java" target-dir="src/com/silkimen/cordovahttp"/>
<source-file src="src/android/com/silkimen/cordovahttp/CordovaHttpBase.java" target-dir="src/com/silkimen/cordovahttp"/>
<source-file src="src/android/com/silkimen/cordovahttp/CordovaHttpDownload.java" target-dir="src/com/silkimen/cordovahttp"/>
<source-file src="src/android/com/silkimen/cordovahttp/CordovaHttpOperation.java" target-dir="src/com/silkimen/cordovahttp"/>
<source-file src="src/android/com/silkimen/cordovahttp/CordovaHttpPlugin.java" target-dir="src/com/silkimen/cordovahttp"/>
<source-file src="src/android/com/silkimen/cordovahttp/CordovaHttpResponse.java" target-dir="src/com/silkimen/cordovahttp"/>
<source-file src="src/android/com/silkimen/cordovahttp/CordovaHttpUpload.java" target-dir="src/com/silkimen/cordovahttp"/>
<source-file src="src/android/com/silkimen/cordovahttp/CordovaObservableCallbackContext.java" target-dir="src/com/silkimen/cordovahttp"/>
<source-file src="src/android/com/silkimen/cordovahttp/CordovaServerTrust.java" target-dir="src/com/silkimen/cordovahttp"/>
<source-file src="src/android/com/silkimen/http/HttpBodyDecoder.java" target-dir="src/com/silkimen/http"/>
<source-file src="src/android/com/silkimen/http/HttpRequest.java" target-dir="src/com/silkimen/http"/>
<source-file src="src/android/com/silkimen/http/JsonUtils.java" target-dir="src/com/silkimen/http"/>
<source-file src="src/android/com/silkimen/http/KeyChainKeyManager.java" target-dir="src/com/silkimen/http"/>
<source-file src="src/android/com/silkimen/http/TLSConfiguration.java" target-dir="src/com/silkimen/http"/>
<source-file src="src/android/com/silkimen/http/TLSSocketFactory.java" target-dir="src/com/silkimen/http"/>
</platform>
<platform name="browser">
<config-file target="config.xml" parent="/*">
<feature name="CordovaHttpPlugin">
<param name="browser-package" value="CordovaHttpPlugin"/>
</feature>
</config-file>
<js-module src="src/browser/cordova-http-plugin.js" name="http-proxy">
<runs/>
</js-module>
</platform>
</plugin>
\ No newline at end of file
# Customized
# v3.3.1
local_plugins\cordova-plugin-advanced-http\3.3.1\cordova-plugin-advanced-http\src\android\com\silkimen\cordovahttp\CordovaHttpBase.java
- Removed request.acceptCharset("UTF-8");
====
File changed (apps/showroom-mb/local_plugins/cordova-plugin-advanced-http/3.3.1/cordova-plugin-advanced-http/src/android/com/silkimen/cordovahttp/CordovaServerTrust.java)
<Remove this>
this.tlsConfiguration.setHostnameVerifier(this.noOpVerifier);
<Change to>
this.tlsConfiguration.setHostnameVerifier(null);
<Remove this>
this.noOpVerifier = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
====
File changed (apps/showroom-mb/local_plugins/cordova-plugin-advanced-http/3.3.1/cordova-plugin-advanced-http/src/android/com/silkimen/http/TLSConfiguration.java)
Line 52:
- From
SSLContext context = SSLContext.getInstance("TLS");
- To
SSLContext context = SSLContext.getInstance("TLSv1.2");
<Remove this>
private final HostnameVerifier noOpVerifier;
====
File changed (apps/showroom-mb/local_plugins/cordova-plugin-advanced-http/3.3.1/cordova-plugin-advanced-http/src/android/com/silkimen/cordovahttp/CordovaClientAuth.java)
Line 75:
- From
private void loadFromBuffer() {
try {
KeyStore keyStore = KeyStore.getInstance("PKCS12");
String keyManagerFactoryAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(keyManagerFactoryAlgorithm);
ByteArrayInputStream stream = new ByteArrayInputStream(this.rawPkcs);
keyStore.load(stream, this.pkcsPassword.toCharArray());
keyManagerFactory.init(keyStore, this.pkcsPassword.toCharArray());
this.tlsConfiguration.setKeyManagers(keyManagerFactory.getKeyManagers());
this.callbackContext.success();
} catch (Exception e) {
Log.e(TAG, "Couldn't load given PKCS12 container for authentication", e);
this.callbackContext.error("Couldn't load given PKCS12 container for authentication");
}
}
- To
private void loadFromBuffer() {
try {
KeyStore keyStore = KeyStore.getInstance("PKCS12");
String keyManagerFactoryAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(keyManagerFactoryAlgorithm);
ByteArrayInputStream stream = new ByteArrayInputStream(this.rawPkcs);
keyStore.load(stream, this.pkcsPassword.toCharArray());
keyManagerFactory.init(keyStore, this.pkcsPassword.toCharArray());
this.tlsConfiguration.setKeyManagers(keyManagerFactory.getKeyManagers());
this.callbackContext.success();
} catch (NoSuchAlgorithmException | KeyStoreException e) {
Log.e(TAG, "Couldn't load given PKCS12 container for authentication", e);
this.callbackContext.error("Couldn't load given PKCS12 container for authentication");
} catch (UnrecoverableKeyException e) {
throw new RuntimeException(e);
} catch (CertificateException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
# Redmine #19928 - Jenn Hong
affected path: showroom-nx/apps/showroom-mb/local_plugins/cordova-plugin-advanced-http/3.3.1/cordova-plugin-advanced-http/src/android/com/silkimen/http/HttpRequest.java
===========
Line 25 - Add new import for able to use Log class from the Android framework
import android.util.Log;
Line 683 - Add logging in catch block for error occurred
From-
catch (IOException e) {
// Ignored
}
To -
catch (IOException e) {
Log.e("Error closing resource", "An error occurred while closing the resource", e);
}
===========
# Installation
If your platforms having the existing plugin, remove it first. Make sure platforms & plugins do not have the plugins.
- Remove plugin
cordova plugin rm cordova-plugin-advanced-http
- Add plugin
cordova plugin add ./apps/showroom-mb/local_plugins/cordova-plugin-advanced-http/3.3.1/cordova-plugin-advanced-http
package com.silkimen.cordovahttp;
import android.app.Activity;
import android.content.Context;
import android.security.KeyChain;
import android.security.KeyChainAliasCallback;
import android.security.KeyChainException;
import android.util.Log;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import org.apache.cordova.CallbackContext;
import com.silkimen.http.KeyChainKeyManager;
import com.silkimen.http.TLSConfiguration;
class CordovaClientAuth implements Runnable, KeyChainAliasCallback {
private static final String TAG = "Cordova-Plugin-HTTP";
private String mode;
private String aliasString;
private byte[] rawPkcs;
private String pkcsPassword;
private Activity activity;
private Context context;
private TLSConfiguration tlsConfiguration;
private CallbackContext callbackContext;
public CordovaClientAuth(final String mode, final String aliasString, final byte[] rawPkcs,
final String pkcsPassword, final Activity activity, final Context context, final TLSConfiguration configContainer,
final CallbackContext callbackContext) {
this.mode = mode;
this.aliasString = aliasString;
this.rawPkcs = rawPkcs;
this.pkcsPassword = pkcsPassword;
this.activity = activity;
this.tlsConfiguration = configContainer;
this.context = context;
this.callbackContext = callbackContext;
}
@Override
public void run() {
if ("systemstore".equals(this.mode)) {
this.loadFromSystemStore();
} else if ("buffer".equals(this.mode)) {
this.loadFromBuffer();
} else {
this.disableClientAuth();
}
}
private void loadFromSystemStore() {
if (this.aliasString == null) {
KeyChain.choosePrivateKeyAlias(this.activity, this, null, null, null, -1, null);
} else {
this.alias(this.aliasString);
}
}
private void loadFromBuffer() {
try {
KeyStore keyStore = KeyStore.getInstance("PKCS12");
String keyManagerFactoryAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(keyManagerFactoryAlgorithm);
ByteArrayInputStream stream = new ByteArrayInputStream(this.rawPkcs);
keyStore.load(stream, this.pkcsPassword.toCharArray());
keyManagerFactory.init(keyStore, this.pkcsPassword.toCharArray());
this.tlsConfiguration.setKeyManagers(keyManagerFactory.getKeyManagers());
this.callbackContext.success();
} catch (NoSuchAlgorithmException | KeyStoreException e) {
Log.e(TAG, "Couldn't load given PKCS12 container for authentication", e);
this.callbackContext.error("Couldn't load given PKCS12 container for authentication");
} catch (UnrecoverableKeyException e) {
throw new RuntimeException(e);
} catch (CertificateException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private void disableClientAuth() {
this.tlsConfiguration.setKeyManagers(null);
this.callbackContext.success();
}
@Override
public void alias(final String alias) {
try {
if (alias == null) {
throw new Exception("Couldn't get a consent for private key access");
}
PrivateKey key = KeyChain.getPrivateKey(this.context, alias);
X509Certificate[] chain = KeyChain.getCertificateChain(this.context, alias);
KeyManager keyManager = new KeyChainKeyManager(alias, key, chain);
this.tlsConfiguration.setKeyManagers(new KeyManager[] { keyManager });
this.callbackContext.success(alias);
} catch (Exception e) {
Log.e(TAG, "Couldn't load private key and certificate pair with given alias \"" + alias + "\" for authentication",
e);
this.callbackContext.error(
"Couldn't load private key and certificate pair with given alias \"" + alias + "\" for authentication");
}
}
}
package com.silkimen.cordovahttp;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.io.UnsupportedEncodingException;
import java.net.SocketTimeoutException;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import javax.net.ssl.SSLException;
import com.silkimen.http.HttpBodyDecoder;
import com.silkimen.http.HttpRequest;
import com.silkimen.http.HttpRequest.HttpRequestException;
import com.silkimen.http.JsonUtils;
import com.silkimen.http.TLSConfiguration;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Base64;
import android.util.Log;
abstract class CordovaHttpBase implements Runnable {
protected static final String TAG = "Cordova-Plugin-HTTP";
protected String method;
protected String url;
protected String serializer = "none";
protected String responseType;
protected Object data;
protected JSONObject headers;
protected int connectTimeout;
protected int readTimeout;
protected boolean followRedirects;
protected TLSConfiguration tlsConfiguration;
protected CordovaObservableCallbackContext callbackContext;
public CordovaHttpBase(String method, String url, String serializer, Object data, JSONObject headers, int connectTimeout,
int readTimeout, boolean followRedirects, String responseType, TLSConfiguration tlsConfiguration,
CordovaObservableCallbackContext callbackContext) {
this.method = method;
this.url = url;
this.serializer = serializer;
this.data = data;
this.headers = headers;
this.connectTimeout = connectTimeout;
this.readTimeout = readTimeout;
this.followRedirects = followRedirects;
this.responseType = responseType;
this.tlsConfiguration = tlsConfiguration;
this.callbackContext = callbackContext;
}
public CordovaHttpBase(String method, String url, JSONObject headers, int connectTimeout, int readTimeout, boolean followRedirects,
String responseType, TLSConfiguration tlsConfiguration, CordovaObservableCallbackContext callbackContext) {
this.method = method;
this.url = url;
this.headers = headers;
this.connectTimeout = connectTimeout;
this.readTimeout = readTimeout;
this.followRedirects = followRedirects;
this.responseType = responseType;
this.tlsConfiguration = tlsConfiguration;
this.callbackContext = callbackContext;
}
@Override
public void run() {
CordovaHttpResponse response = new CordovaHttpResponse();
HttpRequest request = null;
try {
request = this.createRequest();
this.prepareRequest(request);
this.sendBody(request);
this.processResponse(request, response);
request.disconnect();
request.stream().close();
} catch (HttpRequestException e) {
Throwable cause = e.getCause();
String message = cause.getMessage();
if (cause instanceof SSLException) {
response.setStatus(-2);
response.setErrorMessage("TLS connection could not be established: " + e.getMessage());
Log.w(TAG, "TLS connection could not be established", e);
} else if (cause instanceof UnknownHostException) {
response.setStatus(-3);
response.setErrorMessage("Host could not be resolved: " + e.getMessage());
Log.w(TAG, "Host could not be resolved", e);
} else if (cause instanceof SocketTimeoutException) {
response.setStatus(-4);
response.setErrorMessage("Request timed out: " + e.getMessage());
Log.w(TAG, "Request timed out", e);
} else if (cause instanceof InterruptedIOException && "thread interrupted".equals(message.toLowerCase())) {
this.setAborted(request, response);
} else {
response.setStatus(-1);
response.setErrorMessage("There was an error with the request: " + message);
Log.w(TAG, "Generic request error", e);
}
} catch (InterruptedException ie) {
this.setAborted(request, response);
} catch (Exception e) {
response.setStatus(-1);
response.setErrorMessage(e.getMessage());
Log.e(TAG, "An unexpected error occured", e);
}
try {
if (response.hasFailed()) {
this.callbackContext.error(response.toJSON());
} else {
this.callbackContext.success(response.toJSON());
}
} catch (JSONException e) {
Log.e(TAG, "An unexpected error occured while creating HTTP response object", e);
}
}
protected HttpRequest createRequest() throws JSONException {
return new HttpRequest(this.url, this.method);
}
protected void prepareRequest(HttpRequest request) throws JSONException, IOException {
request.followRedirects(this.followRedirects);
request.connectTimeout(this.connectTimeout);
request.readTimeout(this.readTimeout);
request.uncompress(true);
if (this.tlsConfiguration.getHostnameVerifier() != null) {
request.setHostnameVerifier(this.tlsConfiguration.getHostnameVerifier());
}
request.setSSLSocketFactory(this.tlsConfiguration.getTLSSocketFactory());
// setup content type before applying headers, so user can override it
this.setContentType(request);
request.headers(JsonUtils.getStringMap(this.headers));
}
protected void setContentType(HttpRequest request) {
if ("json".equals(this.serializer)) {
request.contentType("application/json", "UTF-8");
} else if ("utf8".equals(this.serializer)) {
request.contentType("text/plain", "UTF-8");
} else if ("raw".equals(this.serializer)) {
request.contentType("application/octet-stream");
} else if ("urlencoded".equals(this.serializer)) {
// intentionally left blank, because content type is set in HttpRequest.form()
} else if ("multipart".equals(this.serializer)) {
// intentionally left blank, because content type is set in HttpRequest.part()
}
}
protected void sendBody(HttpRequest request) throws HttpRequestException, JSONException, UnsupportedEncodingException, URISyntaxException, FileNotFoundException {
if (this.data == null) {
return;
}
if ("json".equals(this.serializer)) {
request.send(this.data.toString());
} else if ("utf8".equals(this.serializer)) {
request.send(((JSONObject) this.data).getString("text"));
} else if ("raw".equals(this.serializer)) {
request.send(Base64.decode((String)this.data, Base64.DEFAULT));
} else if ("urlencoded".equals(this.serializer)) {
request.form(JsonUtils.getObjectMap((JSONObject) this.data));
} else if ("multipart".equals(this.serializer)) {
JSONArray buffers = ((JSONObject) this.data).getJSONArray("buffers");
JSONArray names = ((JSONObject) this.data).getJSONArray("names");
JSONArray fileNames = ((JSONObject) this.data).getJSONArray("fileNames");
JSONArray types = ((JSONObject) this.data).getJSONArray("types");
for (int i = 0; i < buffers.length(); ++i) {
byte[] bytes = Base64.decode(buffers.getString(i), Base64.DEFAULT);
String name = names.getString(i);
if (fileNames.isNull(i)) {
request.part(name, new String(bytes, "UTF-8"));
} else {
request.part(name, fileNames.getString(i), types.getString(i), new ByteArrayInputStream(bytes));
}
}
// prevent sending malformed empty multipart requests (#372)
if (buffers.length() == 0) {
request.contentType("multipart/form-data; boundary=00content0boundary00");
request.send("\r\n--00content0boundary00--\r\n");
}
}
}
protected void processResponse(HttpRequest request, CordovaHttpResponse response) throws Exception {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
request.receive(outputStream);
response.setStatus(request.code());
response.setUrl(request.url().toString());
response.setHeaders(request.headers());
if (request.code() >= 200 && request.code() < 300) {
if ("text".equals(this.responseType) || "json".equals(this.responseType)) {
String decoded = HttpBodyDecoder.decodeBody(outputStream.toByteArray(), request.charset());
response.setBody(decoded);
} else {
response.setData(outputStream.toByteArray());
}
} else {
response.setErrorMessage(HttpBodyDecoder.decodeBody(outputStream.toByteArray(), request.charset()));
}
}
protected void setAborted(HttpRequest request, CordovaHttpResponse response) {
response.setStatus(-8);
response.setErrorMessage("Request was aborted");
if (request != null) {
try {
request.disconnect();
} catch(Exception any){
Log.w(TAG, "Failed to close aborted request", any);
}
}
Log.i(TAG, "Request was aborted");
}
}
package com.silkimen.cordovahttp;
import java.io.File;
import java.net.URI;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSocketFactory;
import com.silkimen.http.HttpRequest;
import com.silkimen.http.TLSConfiguration;
import org.apache.cordova.file.FileUtils;
import org.json.JSONObject;
class CordovaHttpDownload extends CordovaHttpBase {
private String filePath;
public CordovaHttpDownload(String url, JSONObject headers, String filePath, int connectTimeout, int readTimeout,
boolean followRedirects, TLSConfiguration tlsConfiguration, CordovaObservableCallbackContext callbackContext) {
super("GET", url, headers, connectTimeout, readTimeout, followRedirects, "text", tlsConfiguration, callbackContext);
this.filePath = filePath;
}
@Override
protected void processResponse(HttpRequest request, CordovaHttpResponse response) throws Exception {
response.setStatus(request.code());
response.setUrl(request.url().toString());
response.setHeaders(request.headers());
if (request.code() >= 200 && request.code() < 300) {
File file = new File(new URI(this.filePath));
JSONObject fileEntry = FileUtils.getFilePlugin().getEntryForFile(file);
request.receive(file);
response.setFileEntry(fileEntry);
} else {
response.setErrorMessage("There was an error downloading the file");
}
}
}
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment