mirror of
https://github.com/silkimen/cordova-plugin-advanced-http.git
synced 2026-01-31 00:00:03 +08:00
Compare commits
81 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1f5b0f5b49 | ||
|
|
af5e06902e | ||
|
|
73f37d6a35 | ||
|
|
3678f5f6e1 | ||
|
|
41861aa2ec | ||
|
|
91573159e3 | ||
|
|
b4ff7735de | ||
|
|
60c042164a | ||
|
|
342022d3a7 | ||
|
|
dbe28b284f | ||
|
|
fe1a0fdbf7 | ||
|
|
32a250fbd5 | ||
|
|
cb84860bb1 | ||
|
|
7f5345eafd | ||
|
|
54cbb840e2 | ||
|
|
866034ea18 | ||
|
|
6615f1bf53 | ||
|
|
3ee42a41e4 | ||
|
|
8acefd2791 | ||
|
|
f6adf1e920 | ||
|
|
0c26ada847 | ||
|
|
3d20ab6b8c | ||
|
|
6fc8a7e06d | ||
|
|
00dc85cdac | ||
|
|
c86874a01a | ||
|
|
86fc3892a4 | ||
|
|
469ace48b5 | ||
|
|
b1ad996585 | ||
|
|
1218a57e5f | ||
|
|
320ed35022 | ||
|
|
845f90d43f | ||
|
|
f6c3ea7f66 | ||
|
|
d52eb08982 | ||
|
|
57c87db5a1 | ||
|
|
8ea1f3aed6 | ||
|
|
e41684cc79 | ||
|
|
d393d3ca78 | ||
|
|
479c644b1d | ||
|
|
bfa446c7fd | ||
|
|
c92f07775b | ||
|
|
9870dde50a | ||
|
|
ed08534cf3 | ||
|
|
ea15617fae | ||
|
|
87c915f7c0 | ||
|
|
1f4ccd37b4 | ||
|
|
343c536a3b | ||
|
|
38da25bb75 | ||
|
|
42175e27ad | ||
|
|
43b65fa887 | ||
|
|
48445786b6 | ||
|
|
08ec3203e9 | ||
|
|
9684c03685 | ||
|
|
8f3cfb11d0 | ||
| d48512c8df | |||
| ee2d727c2b | |||
| 0ae3756a74 | |||
|
|
935e7d6ba3 | ||
|
|
5b8f20e1c4 | ||
|
|
b3b97306f4 | ||
|
|
6a9a22f81e | ||
|
|
b20faa9c3c | ||
|
|
d66b4b7645 | ||
|
|
fb77849d10 | ||
|
|
e2919e51e1 | ||
|
|
ad1d500eae | ||
|
|
36d7e1813c | ||
|
|
1bafe6cdd9 | ||
|
|
1dd5ee59c8 | ||
|
|
6f68aab736 | ||
|
|
c2a2ebc31b | ||
|
|
c9bff478d8 | ||
|
|
9ff32f1892 | ||
|
|
16ac763a2a | ||
|
|
80315156ad | ||
|
|
5499f2a8b8 | ||
|
|
9d870e7748 | ||
|
|
c2a0317b8f | ||
|
|
7c1836e87f | ||
|
|
87ddbbe3b1 | ||
|
|
4687bad20d | ||
|
|
6797d2c3e0 |
6
.eslintignore
Normal file
6
.eslintignore
Normal file
@@ -0,0 +1,6 @@
|
||||
node_modules
|
||||
temp
|
||||
platforms
|
||||
**/*.min.js
|
||||
www/umd-tough-cookie.js
|
||||
www/lodash.js
|
||||
25
.eslintrc.json
Normal file
25
.eslintrc.json
Normal file
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"env": {
|
||||
"browser": true,
|
||||
"node": true,
|
||||
"es2020": true
|
||||
},
|
||||
"extends": [
|
||||
"eslint:recommended"
|
||||
],
|
||||
"parserOptions": {
|
||||
"ecmaVersion": 2020,
|
||||
"sourceType": "script"
|
||||
},
|
||||
"overrides": [
|
||||
{
|
||||
"files": [
|
||||
"test/**/*.js",
|
||||
"www/**/*.js"
|
||||
],
|
||||
"env": {
|
||||
"mocha": true
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
197
.github/workflows/ci.yml
vendored
197
.github/workflows/ci.yml
vendored
@@ -1,65 +1,166 @@
|
||||
name: Cordova HTTP Plugin CI
|
||||
|
||||
on: [push]
|
||||
on:
|
||||
push:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
ci_reason:
|
||||
description: "Optional note for manual runs"
|
||||
required: false
|
||||
|
||||
env:
|
||||
nodejs: '10.x'
|
||||
node_version: "22.x"
|
||||
java_distribution: "zulu"
|
||||
java_version: "17"
|
||||
gradle_version: "7.6.1"
|
||||
BROWSERSTACK_USERNAME: ${{ secrets.BROWSERSTACK_USERNAME }}
|
||||
BROWSERSTACK_ACCESS_KEY: ${{ secrets.BROWSERSTACK_ACCESS_KEY }}
|
||||
|
||||
jobs:
|
||||
lint:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
- name: Install node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: ${{ env.node_version }}
|
||||
cache: npm
|
||||
cache-dependency-path: package-lock.json
|
||||
- name: Install node modules
|
||||
run: npm ci
|
||||
- name: Run ESLint
|
||||
run: npm run lint
|
||||
|
||||
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 testjs
|
||||
- uses: actions/checkout@v1
|
||||
- name: Install node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: ${{ env.node_version }}
|
||||
cache: npm
|
||||
cache-dependency-path: package-lock.json
|
||||
- name: Install node modules
|
||||
run: npm ci
|
||||
- name: Run WWW interface tests
|
||||
run: npm run test:js
|
||||
|
||||
build-ios:
|
||||
runs-on: macOS-latest
|
||||
outputs:
|
||||
run-tests: ${{ steps.should-run-tests.outputs.run_tests }}
|
||||
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 updatecert
|
||||
- name: Build test app
|
||||
run: scripts/build-test-app.sh --ios --emulator
|
||||
- uses: actions/checkout@v1
|
||||
- name: Install node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: ${{ env.node_version }}
|
||||
cache: npm
|
||||
cache-dependency-path: package-lock.json
|
||||
- id: should-run-tests
|
||||
# need to find a solution for signing iOS App so we can build for device target instead simulator
|
||||
# for now we skip iOS tests on BrowserStack
|
||||
run: echo "run_tests=false" >> "$GITHUB_OUTPUT"
|
||||
- name: Install node modules
|
||||
run: npm ci
|
||||
- name: Update test cert for httpbin.org
|
||||
run: npm run update:cert
|
||||
- name: Build test app
|
||||
run: scripts/build-test-app.sh --ios --emulator
|
||||
- name: Upload artifact to BrowserStack
|
||||
if: steps.should-run-tests.outputs.run_tests == 'true'
|
||||
run: scripts/upload-browserstack.sh --ios
|
||||
|
||||
test-ios:
|
||||
needs: build-ios
|
||||
if: needs.build-ios.outputs.run-tests == 'true'
|
||||
runs-on: macOS-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
- name: Install node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: ${{ env.node_version }}
|
||||
cache: npm
|
||||
cache-dependency-path: package-lock.json
|
||||
- name: Install node modules
|
||||
run: npm ci
|
||||
- name: Run e2e tests (iOS)
|
||||
run: scripts/test-app.sh --ios --device
|
||||
|
||||
build-android:
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
BROWSERSTACK_USERNAME: ${{ secrets.BROWSERSTACK_USERNAME }}
|
||||
BROWSERSTACK_ACCESS_KEY: ${{ secrets.BROWSERSTACK_ACCESS_KEY }}
|
||||
outputs:
|
||||
run-tests: ${{ steps.should-run-tests.outputs.run_tests }}
|
||||
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 updatecert
|
||||
- name: Add workaround for missing DX files in build-tools 31 (https://stackoverflow.com/a/68430992)
|
||||
run: ln -s $ANDROID_HOME/build-tools/31.0.0/d8 $ANDROID_HOME/build-tools/31.0.0/dx && ln -s $ANDROID_HOME/build-tools/31.0.0/lib/d8.jar $ANDROID_HOME/build-tools/31.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
|
||||
- uses: actions/checkout@v1
|
||||
- name: Install node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: ${{ env.node_version }}
|
||||
cache: npm
|
||||
cache-dependency-path: package-lock.json
|
||||
- id: should-run-tests
|
||||
run: |
|
||||
if [ -n "${BROWSERSTACK_USERNAME}" ]; then
|
||||
echo "run_tests=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "run_tests=false" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
- name: Install node modules
|
||||
run: npm ci
|
||||
- name: Install JDK
|
||||
uses: actions/setup-java@v2
|
||||
with:
|
||||
distribution: ${{ env.java_distribution }}
|
||||
java-version: ${{ env.java_version }}
|
||||
java-package: jdk
|
||||
- name: Ensure Android build-tools 33.0.2
|
||||
run: yes | "${ANDROID_HOME}/cmdline-tools/latest/bin/sdkmanager" "build-tools;33.0.2"
|
||||
- name: Install Gradle
|
||||
run: |
|
||||
set -euo pipefail
|
||||
curl -sSL "https://services.gradle.org/distributions/gradle-${{ env.gradle_version }}-bin.zip" -o gradle.zip
|
||||
unzip -q gradle.zip -d "$HOME/gradle"
|
||||
echo "$HOME/gradle/gradle-${{ env.gradle_version }}/bin" >> "$GITHUB_PATH"
|
||||
rm gradle.zip
|
||||
- name: Update test cert for httpbin.org
|
||||
run: npm run update:cert
|
||||
- name: Shim missing DX binaries (https://stackoverflow.com/a/68430992)
|
||||
run: |
|
||||
set -euo pipefail
|
||||
BUILD_TOOLS_PATH="$(ls -d $ANDROID_HOME/build-tools/*/ | sort -V | tail -n 1)"
|
||||
D8_BIN="${BUILD_TOOLS_PATH}d8"
|
||||
DX_BIN="${BUILD_TOOLS_PATH}dx"
|
||||
D8_JAR="${BUILD_TOOLS_PATH}lib/d8.jar"
|
||||
DX_JAR="${BUILD_TOOLS_PATH}lib/dx.jar"
|
||||
if [ -f "$D8_BIN" ] && [ ! -e "$DX_BIN" ]; then
|
||||
ln -s "$D8_BIN" "$DX_BIN"
|
||||
fi
|
||||
if [ -f "$D8_JAR" ] && [ ! -e "$DX_JAR" ]; then
|
||||
ln -s "$D8_JAR" "$DX_JAR"
|
||||
fi
|
||||
- name: Build test app
|
||||
run: scripts/build-test-app.sh --android --device
|
||||
- name: Upload artifact to BrowserStack
|
||||
if: steps.should-run-tests.outputs.run_tests == 'true'
|
||||
run: scripts/upload-browserstack.sh --android
|
||||
|
||||
test-android:
|
||||
needs: build-android
|
||||
if: needs.build-android.outputs.run-tests == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
- name: Install node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: ${{ env.node_version }}
|
||||
cache: npm
|
||||
cache-dependency-path: package-lock.json
|
||||
- name: Install node modules
|
||||
run: npm ci
|
||||
- name: Run e2e tests (Android)
|
||||
run: scripts/test-app.sh --android --device
|
||||
|
||||
119
.github/workflows/codeql-analysis.yml
vendored
119
.github/workflows/codeql-analysis.yml
vendored
@@ -3,60 +3,101 @@
|
||||
#
|
||||
# You may wish to alter this file to override the set of languages analyzed,
|
||||
# or to provide custom queries or build logic.
|
||||
name: "CodeQL"
|
||||
#
|
||||
# ******** NOTE ********
|
||||
# We have attempted to detect the languages in your repository. Please check
|
||||
# the `language` matrix defined below to confirm you have the correct set of
|
||||
# supported CodeQL languages.
|
||||
#
|
||||
name: "CodeQL Advanced"
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [master]
|
||||
branches: ["master"]
|
||||
pull_request:
|
||||
# The branches below must be a subset of the branches above
|
||||
branches: [master]
|
||||
branches: ["master"]
|
||||
schedule:
|
||||
- cron: '0 20 * * 3'
|
||||
- cron: "0 0 * * 0"
|
||||
|
||||
jobs:
|
||||
analyze:
|
||||
name: Analyze
|
||||
runs-on: ubuntu-latest
|
||||
name: Analyze (${{ matrix.language }})
|
||||
# Runner size impacts CodeQL analysis time. To learn more, please see:
|
||||
# - https://gh.io/recommended-hardware-resources-for-running-codeql
|
||||
# - https://gh.io/supported-runners-and-hardware-resources
|
||||
# - https://gh.io/using-larger-runners (GitHub.com only)
|
||||
# Consider using larger runners or machines with greater resources for possible analysis time improvements.
|
||||
runs-on: ${{ (matrix.language == 'swift' && 'macos-latest') || 'ubuntu-latest' }}
|
||||
permissions:
|
||||
# required for all workflows
|
||||
security-events: write
|
||||
|
||||
# required to fetch internal or private CodeQL packs
|
||||
packages: read
|
||||
|
||||
# only required for workflows in private repositories
|
||||
actions: read
|
||||
contents: read
|
||||
|
||||
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
|
||||
|
||||
include:
|
||||
- language: actions
|
||||
build-mode: none
|
||||
- language: java-kotlin
|
||||
build-mode: none # This mode only analyzes Java. Set this to 'autobuild' or 'manual' to analyze Kotlin too.
|
||||
- language: javascript-typescript
|
||||
build-mode: none
|
||||
# CodeQL supports the following values keywords for 'language': 'actions', 'c-cpp', 'csharp', 'go', 'java-kotlin', 'javascript-typescript', 'python', 'ruby', 'rust', 'swift'
|
||||
# Use `c-cpp` to analyze code written in C, C++ or both
|
||||
# Use 'java-kotlin' to analyze code written in Java, Kotlin or both
|
||||
# Use 'javascript-typescript' to analyze code written in JavaScript, TypeScript or both
|
||||
# To learn more about changing the languages that are analyzed or customizing the build mode for your analysis,
|
||||
# see https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/customizing-your-advanced-setup-for-code-scanning.
|
||||
# If you are analyzing a compiled language, you can modify the 'build-mode' for that language to customize how
|
||||
# your codebase is analyzed, see https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/codeql-code-scanning-for-compiled-languages
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v2
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
# 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
|
||||
# Add any setup steps before running the `github/codeql-action/init` action.
|
||||
# This includes steps like installing compilers or runtimes (`actions/setup-node`
|
||||
# or others). This is typically only required for manual builds.
|
||||
# - name: Setup runtime (example)
|
||||
# uses: actions/setup-example@v1
|
||||
|
||||
# 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
|
||||
# Initializes the CodeQL tools for scanning.
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@v4
|
||||
with:
|
||||
languages: ${{ matrix.language }}
|
||||
build-mode: ${{ matrix.build-mode }}
|
||||
# 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.
|
||||
|
||||
# ℹ️ Command-line programs to run using the OS shell.
|
||||
# 📚 https://git.io/JvXDl
|
||||
# For more details on CodeQL's query packs, refer to: https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs
|
||||
# queries: security-extended,security-and-quality
|
||||
|
||||
# ✏️ 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
|
||||
# If the analyze step fails for one of the languages you are analyzing with
|
||||
# "We were unable to automatically build your code", modify the matrix above
|
||||
# to set the build mode to "manual" for that language. Then modify this step
|
||||
# to build your code.
|
||||
# ℹ️ Command-line programs to run using the OS shell.
|
||||
# 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
|
||||
- name: Run manual build steps
|
||||
if: matrix.build-mode == 'manual'
|
||||
shell: bash
|
||||
run: |
|
||||
echo 'If you are using a "manual" build mode for one or more of the' \
|
||||
'languages you are analyzing, replace this with the commands to build' \
|
||||
'your code, for example:'
|
||||
echo ' make bootstrap'
|
||||
echo ' make release'
|
||||
exit 1
|
||||
|
||||
#- run: |
|
||||
# make bootstrap
|
||||
# make release
|
||||
|
||||
- name: Perform CodeQL Analysis
|
||||
uses: github/codeql-action/analyze@v1
|
||||
- name: Perform CodeQL Analysis
|
||||
uses: github/codeql-action/analyze@v4
|
||||
with:
|
||||
category: "/language:${{matrix.language}}"
|
||||
|
||||
58
.travis.yml
58
.travis.yml
@@ -1,58 +0,0 @@
|
||||
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 testjs &&
|
||||
npm run updatecert &&
|
||||
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-28.0.3
|
||||
- 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 testjs &&
|
||||
npm run updatecert &&
|
||||
scripts/build-test-app.sh --android --emulator &&
|
||||
scripts/upload-saucelabs.sh --android &&
|
||||
scripts/test-app.sh --android --emulator;
|
||||
22
CHANGELOG.md
22
CHANGELOG.md
@@ -1,5 +1,27 @@
|
||||
# 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)
|
||||
|
||||
@@ -73,10 +73,5 @@ If we suggest changes or the [CI build fails](#cibuild), then:
|
||||
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 always check the results of the latest CI builds on [Github Actions](https://github.com/silkimen/cordova-plugin-advanced-http/actions).
|
||||
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)
|
||||
|
||||
76
README.md
76
README.md
@@ -3,10 +3,7 @@ Cordova Advanced HTTP
|
||||
[](https://www.npmjs.com/package/cordova-plugin-advanced-http?activeTab=versions)
|
||||
[](https://opensource.org/licenses/mit-license.php)
|
||||
[](https://www.npmjs.com/package/cordova-plugin-advanced-http)
|
||||
|
||||
[](https://travis-ci.com/silkimen/cordova-plugin-advanced-http)
|
||||
[](https://github.com/silkimen/cordova-plugin-advanced-http/actions)
|
||||
|
||||
[](https://github.com/silkimen/cordova-plugin-advanced-http/actions)
|
||||
|
||||
Cordova / Phonegap plugin for communicating with HTTP servers. Supports iOS, Android and [Browser](#browserSupport).
|
||||
|
||||
@@ -43,6 +40,10 @@ e.g. blacklist `SSLv3` and `TLSv1`:
|
||||
<preference name="AndroidBlacklistSecureSocketProtocols" value="SSLv3,TLSv1" />
|
||||
```
|
||||
|
||||
## Currently known issues
|
||||
|
||||
- [abort](#abort)ing sent requests is not working reliably
|
||||
|
||||
## Usage
|
||||
|
||||
### Plain Cordova
|
||||
@@ -124,12 +125,26 @@ This defaults to `urlencoded`. You can also override the default content type he
|
||||
:warning: `multipart` depends on several Web API standards which need to be supported in your web view. Check out https://github.com/silkimen/cordova-plugin-advanced-http/wiki/Web-APIs-required-for-Multipart-requests for more info.
|
||||
|
||||
### setRequestTimeout
|
||||
Set the "read" timeout in seconds. This is the timeout interval to use when waiting for additional data.
|
||||
|
||||
Set how long to wait for a request to respond, in seconds.
|
||||
For Android, this will set both [connectTimeout](https://developer.android.com/reference/java/net/URLConnection#getConnectTimeout()) and [readTimeout](https://developer.android.com/reference/java/net/URLConnection#setReadTimeout(int)).
|
||||
For iOS, this will set [timeout interval](https://developer.apple.com/documentation/foundation/nsmutableurlrequest/1414063-timeoutinterval).
|
||||
For browser platform, this will set [timeout](https://developer.mozilla.org/fr/docs/Web/API/XMLHttpRequest/timeout).
|
||||
```js
|
||||
cordova.plugin.http.setRequestTimeout(5.0);
|
||||
```
|
||||
|
||||
### setConnectTimeout (Android Only)
|
||||
Set connect timeout for Android
|
||||
```js
|
||||
cordova.plugin.http.setRequestTimeout(5.0);
|
||||
```
|
||||
|
||||
### setReadTimeout (Android Only)
|
||||
Set read timeout for Android
|
||||
```js
|
||||
cordova.plugin.http.setReadTimeout(5.0);
|
||||
```
|
||||
|
||||
### setFollowRedirect<a name="setFollowRedirect"></a>
|
||||
Configure if it should follow redirects automatically. This defaults to true.
|
||||
|
||||
@@ -145,7 +160,7 @@ cordova.plugin.http.getCookieString(url);
|
||||
```
|
||||
|
||||
### setCookie
|
||||
Add a custom cookie. Takes a URL, a cookie string and an options object. See [ToughCookie documentation](https://github.com/salesforce/tough-cookie#setcookiecookieorstring-currenturl-options-cberrcookie) for allowed options.
|
||||
Add a custom cookie. Takes a URL, a cookie string and an options object. See [ToughCookie documentation](https://github.com/salesforce/tough-cookie#setcookiecookieorstring-currenturl-options-cberrcookie) for allowed options. Cookie will persist until removed with [removeCookies](#removecookies) or [clearCookies](#clearcookies).
|
||||
|
||||
```js
|
||||
cordova.plugin.http.setCookie(url, cookie, options);
|
||||
@@ -396,21 +411,32 @@ cordova.plugin.http.uploadFile("https://google.com/", {
|
||||
```
|
||||
|
||||
### downloadFile<a name="downloadFile"></a>
|
||||
Downloads a file and saves it to the device. Takes a URL, parameters, headers, and a filePath. See [post](#post) documentation for details on what is returned on failure. On success this function returns a cordova [FileEntry object](http://cordova.apache.org/docs/en/3.3.0/cordova_file_file.md.html#FileEntry).
|
||||
Downloads a file and saves it to the device. Takes a URL, parameters, headers, and a filePath. See [post](#post) documentation for details on what is returned on failure. On success this function returns a cordova [FileEntry object](http://cordova.apache.org/docs/en/3.3.0/cordova_file_file.md.html#FileEntry) as first and the response object as second parameter.
|
||||
|
||||
```js
|
||||
cordova.plugin.http.downloadFile("https://google.com/", {
|
||||
id: '12',
|
||||
message: 'test'
|
||||
}, { Authorization: 'OAuth2: token' }, 'file:///somepicture.jpg', function(entry) {
|
||||
// prints the filename
|
||||
console.log(entry.name);
|
||||
cordova.plugin.http.downloadFile(
|
||||
"https://google.com/",
|
||||
{ id: '12', message: 'test' },
|
||||
{ Authorization: 'OAuth2: token' },
|
||||
'file:///somepicture.jpg',
|
||||
// success callback
|
||||
function(entry, response) {
|
||||
// prints the filename
|
||||
console.log(entry.name);
|
||||
|
||||
// prints the filePath
|
||||
console.log(entry.fullPath);
|
||||
}, function(response) {
|
||||
console.error(response.error);
|
||||
});
|
||||
// prints the filePath
|
||||
console.log(entry.fullPath);
|
||||
|
||||
// prints all header key/value pairs
|
||||
Object.keys(response.headers).forEach(function (key) {
|
||||
console.log(key, response.headers[key]);
|
||||
});
|
||||
},
|
||||
// error callback
|
||||
function(response) {
|
||||
console.error(response.error);
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
### abort<a name="abort"></a>
|
||||
@@ -427,12 +453,15 @@ If the request is still in progress, the request's `failure` callback will be in
|
||||
var requestId = cordova.plugin.http.downloadFile("https://google.com/", {
|
||||
id: '12',
|
||||
message: 'test'
|
||||
}, { Authorization: 'OAuth2: token' }, 'file:///somepicture.jpg', function(entry) {
|
||||
}, { Authorization: 'OAuth2: token' }, 'file:///somepicture.jpg', function(entry, response) {
|
||||
// prints the filename
|
||||
console.log(entry.name);
|
||||
|
||||
// prints the filePath
|
||||
console.log(entry.fullPath);
|
||||
|
||||
// prints the status code
|
||||
console.log(response.status);
|
||||
}, function(response) {
|
||||
// if request was actually aborted, failure callback with status -8 will be invoked
|
||||
if(response.status === -8){
|
||||
@@ -482,7 +511,6 @@ We made a few modifications to the networking libraries.
|
||||
This plugin uses amazing cloud services to maintain quality. CI Builds and E2E testing are powered by:
|
||||
|
||||
* [GitHub Actions](https://github.com/features/actions)
|
||||
* [Travis CI](https://travis-ci.org/)
|
||||
* [BrowserStack](https://www.browserstack.com/)
|
||||
* [Sauce Labs](https://saucelabs.com/)
|
||||
* [httpbin.org](https://httpbin.org/)
|
||||
@@ -494,7 +522,7 @@ First, install current package with `npm install` to fetch dev dependencies.
|
||||
|
||||
Then, to execute Javascript tests:
|
||||
```shell
|
||||
npm run testjs
|
||||
npm run test:js
|
||||
```
|
||||
|
||||
And, to execute E2E tests:
|
||||
@@ -505,8 +533,8 @@ And, to execute E2E tests:
|
||||
- run
|
||||
- updating client and server certificates, building test app, and running e2e tests
|
||||
```shell
|
||||
npm run testandroid
|
||||
npm run testios
|
||||
npm run test:android
|
||||
npm run test:ios
|
||||
```
|
||||
|
||||
## Contribute & Develop
|
||||
|
||||
8789
package-lock.json
generated
8789
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
34
package.json
34
package.json
@@ -1,17 +1,18 @@
|
||||
{
|
||||
"name": "cordova-plugin-advanced-http",
|
||||
"version": "3.2.0",
|
||||
"version": "3.3.1",
|
||||
"description": "Cordova / Phonegap plugin for communicating with HTTP servers using SSL pinning",
|
||||
"scripts": {
|
||||
"updatecert": "node ./scripts/update-e2e-server-cert.js && node ./scripts/update-e2e-client-cert.js",
|
||||
"buildbrowser": "./scripts/build-test-app.sh --browser",
|
||||
"buildandroid": "./scripts/build-test-app.sh --android --emulator",
|
||||
"buildios": "./scripts/build-test-app.sh --ios --emulator",
|
||||
"testandroid": "npm run updatecert && npm run buildandroid && ./scripts/test-app.sh --android --emulator",
|
||||
"testios": "npm run updatecert && npm run buildios && ./scripts/test-app.sh --ios --emulator",
|
||||
"testapp": "npm run testandroid && npm run testios",
|
||||
"testjs": "mocha ./test/js-specs.js",
|
||||
"test": "npm run testjs && npm run testapp",
|
||||
"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",
|
||||
"lint": "eslint . --ext .js",
|
||||
"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": {
|
||||
@@ -58,12 +59,13 @@
|
||||
},
|
||||
"homepage": "https://github.com/silkimen/cordova-plugin-advanced-http#readme",
|
||||
"devDependencies": {
|
||||
"chai": "4.2.0",
|
||||
"chai": "4.3.6",
|
||||
"colors": "1.4.0",
|
||||
"cordova": "10.0.0",
|
||||
"mocha": "8.2.0",
|
||||
"umd-tough-cookie": "2.4.3",
|
||||
"wd": "1.12.1",
|
||||
"xml2js": "0.4.23"
|
||||
"cordova": "11.0.0",
|
||||
"eslint": "^8.57.0",
|
||||
"mocha": "9.2.2",
|
||||
"umd-tough-cookie": "3.0.0",
|
||||
"wd": "1.14.0",
|
||||
"xml2js": "0.5.0"
|
||||
}
|
||||
}
|
||||
|
||||
29
plugin.xml
29
plugin.xml
@@ -1,5 +1,5 @@
|
||||
<?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.2.0">
|
||||
<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
|
||||
@@ -36,25 +36,25 @@
|
||||
<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/AFNetworking/AFHTTPSessionManager.h"/>
|
||||
<header-file src="src/ios/AFNetworking/AFNetworking.h"/>
|
||||
<header-file src="src/ios/AFNetworking/AFNetworkReachabilityManager.h"/>
|
||||
<header-file src="src/ios/AFNetworking/AFSecurityPolicy.h"/>
|
||||
<header-file src="src/ios/AFNetworking/AFURLRequestSerialization.h"/>
|
||||
<header-file src="src/ios/AFNetworking/AFURLResponseSerialization.h"/>
|
||||
<header-file src="src/ios/AFNetworking/AFURLSessionManager.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/AFNetworking/AFHTTPSessionManager.m"/>
|
||||
<source-file src="src/ios/AFNetworking/AFNetworkReachabilityManager.m"/>
|
||||
<source-file src="src/ios/AFNetworking/AFSecurityPolicy.m"/>
|
||||
<source-file src="src/ios/AFNetworking/AFURLRequestSerialization.m"/>
|
||||
<source-file src="src/ios/AFNetworking/AFURLResponseSerialization.m"/>
|
||||
<source-file src="src/ios/AFNetworking/AFURLSessionManager.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"/>
|
||||
@@ -67,6 +67,7 @@
|
||||
</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"/>
|
||||
|
||||
@@ -17,13 +17,20 @@ if [ $PLATFORM = "android" ]; then
|
||||
-F "file=@$TEMP/platforms/android/app/build/outputs/apk/debug/app-debug.apk" \
|
||||
-F "data={\"custom_id\": \"HttpTestAppAndroid\"}"
|
||||
else
|
||||
rm -rf $TEMP/HttpDemo.ipa
|
||||
pushd $TEMP/platforms/ios/build/emulator
|
||||
rm -rf ./Payload
|
||||
mkdir -p ./Payload
|
||||
cp -r ./HttpDemo.app ./Payload/HttpDemo.app
|
||||
zip -r $TEMP/HttpDemo.ipa ./Payload
|
||||
popd
|
||||
rm -rf "$TEMP/HttpDemo.ipa"
|
||||
IOS_BUILD_DIR="$TEMP/platforms/ios/build/Debug-iphonesimulator"
|
||||
APP_PATH="$IOS_BUILD_DIR/HttpDemo.app"
|
||||
if [ ! -d "$APP_PATH" ]; then
|
||||
echo "Unable to locate $APP_PATH" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
PAYLOAD_DIR="$TEMP/Payload"
|
||||
rm -rf "$PAYLOAD_DIR"
|
||||
mkdir -p "$PAYLOAD_DIR"
|
||||
cp -R "$APP_PATH" "$PAYLOAD_DIR/HttpDemo.app"
|
||||
(cd "$TEMP" && zip -qr HttpDemo.ipa Payload)
|
||||
rm -rf "$PAYLOAD_DIR"
|
||||
|
||||
curl -u $BROWSERSTACK_USERNAME:$BROWSERSTACK_ACCESS_KEY \
|
||||
-X POST \
|
||||
|
||||
@@ -35,13 +35,14 @@ abstract class CordovaHttpBase implements Runnable {
|
||||
protected String responseType;
|
||||
protected Object data;
|
||||
protected JSONObject headers;
|
||||
protected int timeout;
|
||||
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 timeout,
|
||||
boolean followRedirects, String responseType, TLSConfiguration tlsConfiguration,
|
||||
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;
|
||||
@@ -49,20 +50,22 @@ abstract class CordovaHttpBase implements Runnable {
|
||||
this.serializer = serializer;
|
||||
this.data = data;
|
||||
this.headers = headers;
|
||||
this.timeout = timeout;
|
||||
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 timeout, boolean followRedirects,
|
||||
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.timeout = timeout;
|
||||
this.connectTimeout = connectTimeout;
|
||||
this.readTimeout = readTimeout;
|
||||
this.followRedirects = followRedirects;
|
||||
this.responseType = responseType;
|
||||
this.tlsConfiguration = tlsConfiguration;
|
||||
@@ -128,8 +131,8 @@ abstract class CordovaHttpBase implements Runnable {
|
||||
|
||||
protected void prepareRequest(HttpRequest request) throws JSONException, IOException {
|
||||
request.followRedirects(this.followRedirects);
|
||||
request.readTimeout(this.timeout);
|
||||
request.acceptCharset("UTF-8");
|
||||
request.connectTimeout(this.connectTimeout);
|
||||
request.readTimeout(this.readTimeout);
|
||||
request.uncompress(true);
|
||||
|
||||
if (this.tlsConfiguration.getHostnameVerifier() != null) {
|
||||
|
||||
@@ -15,10 +15,10 @@ import org.json.JSONObject;
|
||||
class CordovaHttpDownload extends CordovaHttpBase {
|
||||
private String filePath;
|
||||
|
||||
public CordovaHttpDownload(String url, JSONObject headers, String filePath, int timeout, boolean followRedirects,
|
||||
TLSConfiguration tlsConfiguration, CordovaObservableCallbackContext callbackContext) {
|
||||
public CordovaHttpDownload(String url, JSONObject headers, String filePath, int connectTimeout, int readTimeout,
|
||||
boolean followRedirects, TLSConfiguration tlsConfiguration, CordovaObservableCallbackContext callbackContext) {
|
||||
|
||||
super("GET", url, headers, timeout, followRedirects, "text", tlsConfiguration, callbackContext);
|
||||
super("GET", url, headers, connectTimeout, readTimeout, followRedirects, "text", tlsConfiguration, callbackContext);
|
||||
this.filePath = filePath;
|
||||
}
|
||||
|
||||
|
||||
@@ -9,16 +9,16 @@ import org.json.JSONObject;
|
||||
|
||||
class CordovaHttpOperation extends CordovaHttpBase {
|
||||
public CordovaHttpOperation(String method, String url, String serializer, Object data, JSONObject headers,
|
||||
int timeout, boolean followRedirects, String responseType, TLSConfiguration tlsConfiguration,
|
||||
int connectTimeout, int readTimeout, boolean followRedirects, String responseType, TLSConfiguration tlsConfiguration,
|
||||
CordovaObservableCallbackContext callbackContext) {
|
||||
|
||||
super(method, url, serializer, data, headers, timeout, followRedirects, responseType, tlsConfiguration,
|
||||
super(method, url, serializer, data, headers, connectTimeout, readTimeout, followRedirects, responseType, tlsConfiguration,
|
||||
callbackContext);
|
||||
}
|
||||
|
||||
public CordovaHttpOperation(String method, String url, JSONObject headers, int timeout, boolean followRedirects,
|
||||
public CordovaHttpOperation(String method, String url, JSONObject headers, int connectTimeout, int readTimeout, boolean followRedirects,
|
||||
String responseType, TLSConfiguration tlsConfiguration, CordovaObservableCallbackContext callbackContext) {
|
||||
|
||||
super(method, url, headers, timeout, followRedirects, responseType, tlsConfiguration, callbackContext);
|
||||
super(method, url, headers, connectTimeout, readTimeout, followRedirects, responseType, tlsConfiguration, callbackContext);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,6 +16,9 @@ import org.json.JSONArray;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import android.content.Context;
|
||||
import android.net.ConnectivityManager;
|
||||
import android.net.NetworkInfo;
|
||||
import android.util.Log;
|
||||
import android.util.Base64;
|
||||
|
||||
@@ -67,6 +70,23 @@ public class CordovaHttpPlugin extends CordovaPlugin implements Observer {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ("setServerTrustMode".equals(action)) {
|
||||
return this.setServerTrustMode(args, callbackContext);
|
||||
} else if ("setClientAuthMode".equals(action)) {
|
||||
return this.setClientAuthMode(args, callbackContext);
|
||||
} else if ("abort".equals(action)) {
|
||||
return this.abort(args, callbackContext);
|
||||
}
|
||||
|
||||
if (!isNetworkAvailable()) {
|
||||
CordovaHttpResponse response = new CordovaHttpResponse();
|
||||
response.setStatus(-6);
|
||||
response.setErrorMessage("No network connection available");
|
||||
callbackContext.error(response.toJSON());
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
if ("get".equals(action)) {
|
||||
return this.executeHttpRequestWithoutData(action, args, callbackContext);
|
||||
} else if ("head".equals(action)) {
|
||||
@@ -85,12 +105,6 @@ public class CordovaHttpPlugin extends CordovaPlugin implements Observer {
|
||||
return this.uploadFiles(args, callbackContext);
|
||||
} else if ("downloadFile".equals(action)) {
|
||||
return this.downloadFile(args, callbackContext);
|
||||
} else if ("setServerTrustMode".equals(action)) {
|
||||
return this.setServerTrustMode(args, callbackContext);
|
||||
} else if ("setClientAuthMode".equals(action)) {
|
||||
return this.setClientAuthMode(args, callbackContext);
|
||||
} else if ("abort".equals(action)) {
|
||||
return this.abort(args, callbackContext);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
@@ -101,15 +115,16 @@ public class CordovaHttpPlugin extends CordovaPlugin implements Observer {
|
||||
|
||||
String url = args.getString(0);
|
||||
JSONObject headers = args.getJSONObject(1);
|
||||
int timeout = args.getInt(2) * 1000;
|
||||
boolean followRedirect = args.getBoolean(3);
|
||||
String responseType = args.getString(4);
|
||||
int connectTimeout = args.getInt(2) * 1000;
|
||||
int readTimeout = args.getInt(3) * 1000;
|
||||
boolean followRedirect = args.getBoolean(4);
|
||||
String responseType = args.getString(5);
|
||||
Integer reqId = args.getInt(6);
|
||||
|
||||
Integer reqId = args.getInt(5);
|
||||
CordovaObservableCallbackContext observableCallbackContext = new CordovaObservableCallbackContext(callbackContext, reqId);
|
||||
|
||||
CordovaHttpOperation request = new CordovaHttpOperation(method.toUpperCase(), url, headers, timeout, followRedirect,
|
||||
responseType, this.tlsConfiguration, observableCallbackContext);
|
||||
CordovaHttpOperation request = new CordovaHttpOperation(method.toUpperCase(), url, headers, connectTimeout, readTimeout,
|
||||
followRedirect, responseType, this.tlsConfiguration, observableCallbackContext);
|
||||
|
||||
startRequest(reqId, observableCallbackContext, request);
|
||||
|
||||
@@ -123,15 +138,16 @@ public class CordovaHttpPlugin extends CordovaPlugin implements Observer {
|
||||
Object data = args.get(1);
|
||||
String serializer = args.getString(2);
|
||||
JSONObject headers = args.getJSONObject(3);
|
||||
int timeout = args.getInt(4) * 1000;
|
||||
boolean followRedirect = args.getBoolean(5);
|
||||
String responseType = args.getString(6);
|
||||
int connectTimeout = args.getInt(4) * 1000;
|
||||
int readTimeout = args.getInt(5) * 1000;
|
||||
boolean followRedirect = args.getBoolean(6);
|
||||
String responseType = args.getString(7);
|
||||
Integer reqId = args.getInt(8);
|
||||
|
||||
Integer reqId = args.getInt(7);
|
||||
CordovaObservableCallbackContext observableCallbackContext = new CordovaObservableCallbackContext(callbackContext, reqId);
|
||||
|
||||
CordovaHttpOperation request = new CordovaHttpOperation(method.toUpperCase(), url, serializer, data, headers,
|
||||
timeout, followRedirect, responseType, this.tlsConfiguration, observableCallbackContext);
|
||||
connectTimeout, readTimeout, followRedirect, responseType, this.tlsConfiguration, observableCallbackContext);
|
||||
|
||||
startRequest(reqId, observableCallbackContext, request);
|
||||
|
||||
@@ -143,14 +159,15 @@ public class CordovaHttpPlugin extends CordovaPlugin implements Observer {
|
||||
JSONObject headers = args.getJSONObject(1);
|
||||
JSONArray filePaths = args.getJSONArray(2);
|
||||
JSONArray uploadNames = args.getJSONArray(3);
|
||||
int timeout = args.getInt(4) * 1000;
|
||||
boolean followRedirect = args.getBoolean(5);
|
||||
String responseType = args.getString(6);
|
||||
int connectTimeout = args.getInt(4) * 1000;
|
||||
int readTimeout = args.getInt(5) * 1000;
|
||||
boolean followRedirect = args.getBoolean(6);
|
||||
String responseType = args.getString(7);
|
||||
Integer reqId = args.getInt(8);
|
||||
|
||||
Integer reqId = args.getInt(7);
|
||||
CordovaObservableCallbackContext observableCallbackContext = new CordovaObservableCallbackContext(callbackContext, reqId);
|
||||
|
||||
CordovaHttpUpload upload = new CordovaHttpUpload(url, headers, filePaths, uploadNames, timeout, followRedirect,
|
||||
CordovaHttpUpload upload = new CordovaHttpUpload(url, headers, filePaths, uploadNames, connectTimeout, readTimeout, followRedirect,
|
||||
responseType, this.tlsConfiguration, this.cordova.getActivity().getApplicationContext(), observableCallbackContext);
|
||||
|
||||
startRequest(reqId, observableCallbackContext, upload);
|
||||
@@ -162,14 +179,15 @@ public class CordovaHttpPlugin extends CordovaPlugin implements Observer {
|
||||
String url = args.getString(0);
|
||||
JSONObject headers = args.getJSONObject(1);
|
||||
String filePath = args.getString(2);
|
||||
int timeout = args.getInt(3) * 1000;
|
||||
boolean followRedirect = args.getBoolean(4);
|
||||
int connectTimeout = args.getInt(3) * 1000;
|
||||
int readTimeout = args.getInt(4) * 1000;
|
||||
boolean followRedirect = args.getBoolean(5);
|
||||
Integer reqId = args.getInt(6);
|
||||
|
||||
Integer reqId = args.getInt(5);
|
||||
CordovaObservableCallbackContext observableCallbackContext = new CordovaObservableCallbackContext(callbackContext, reqId);
|
||||
|
||||
CordovaHttpDownload download = new CordovaHttpDownload(url, headers, filePath, timeout, followRedirect,
|
||||
this.tlsConfiguration, observableCallbackContext);
|
||||
CordovaHttpDownload download = new CordovaHttpDownload(url, headers, filePath, connectTimeout, readTimeout,
|
||||
followRedirect, this.tlsConfiguration, observableCallbackContext);
|
||||
|
||||
startRequest(reqId, observableCallbackContext, download);
|
||||
|
||||
@@ -245,4 +263,11 @@ public class CordovaHttpPlugin extends CordovaPlugin implements Observer {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isNetworkAvailable() {
|
||||
ConnectivityManager connectivityManager = (ConnectivityManager) cordova.getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
|
||||
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
|
||||
|
||||
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,11 +25,11 @@ class CordovaHttpUpload extends CordovaHttpBase {
|
||||
private JSONArray uploadNames;
|
||||
private Context applicationContext;
|
||||
|
||||
public CordovaHttpUpload(String url, JSONObject headers, JSONArray filePaths, JSONArray uploadNames, int timeout,
|
||||
public CordovaHttpUpload(String url, JSONObject headers, JSONArray filePaths, JSONArray uploadNames, int connectTimeout, int readTimeout,
|
||||
boolean followRedirects, String responseType, TLSConfiguration tlsConfiguration,
|
||||
Context applicationContext, CordovaObservableCallbackContext callbackContext) {
|
||||
|
||||
super("POST", url, headers, timeout, followRedirects, responseType, tlsConfiguration, callbackContext);
|
||||
super("POST", url, headers, connectTimeout, readTimeout, followRedirects, responseType, tlsConfiguration, callbackContext);
|
||||
this.filePaths = filePaths;
|
||||
this.uploadNames = uploadNames;
|
||||
this.applicationContext = applicationContext;
|
||||
|
||||
@@ -71,7 +71,7 @@ class CordovaServerTrust implements Runnable {
|
||||
this.tlsConfiguration.setTrustManagers(this.noOpTrustManagers);
|
||||
} else if ("pinned".equals(this.mode)) {
|
||||
this.tlsConfiguration.setHostnameVerifier(null);
|
||||
this.tlsConfiguration.setTrustManagers(this.getTrustManagers(this.getCertsFromBundle("www/certificates")));
|
||||
this.tlsConfiguration.setTrustManagers(this.getTrustManagers(this.getCertsFromBundle(getWebAssetDir() + "/certificates")));
|
||||
} else {
|
||||
this.tlsConfiguration.setHostnameVerifier(null);
|
||||
this.tlsConfiguration.setTrustManagers(this.getTrustManagers(this.getCertsFromKeyStore("AndroidCAStore")));
|
||||
@@ -84,6 +84,14 @@ class CordovaServerTrust implements Runnable {
|
||||
}
|
||||
}
|
||||
|
||||
private String getWebAssetDir() {
|
||||
return isRunningOnCapacitor()? "public" : "www";
|
||||
}
|
||||
|
||||
private boolean isRunningOnCapacitor() {
|
||||
return this.activity.getClass().getSuperclass().getName().contains("com.getcapacitor");
|
||||
}
|
||||
|
||||
private TrustManager[] getTrustManagers(KeyStore store) throws GeneralSecurityException {
|
||||
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
|
||||
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
|
||||
|
||||
@@ -5,8 +5,8 @@ import java.net.InetAddress;
|
||||
import java.net.Socket;
|
||||
import java.net.UnknownHostException;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.stream.Stream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import javax.net.ssl.SSLContext;
|
||||
import javax.net.ssl.SSLSocket;
|
||||
@@ -15,11 +15,15 @@ import javax.net.ssl.SSLSocketFactory;
|
||||
public class TLSSocketFactory extends SSLSocketFactory {
|
||||
|
||||
private SSLSocketFactory delegate;
|
||||
private String[] blacklistedProtocols;
|
||||
private List<String> blacklistedProtocols;
|
||||
|
||||
public TLSSocketFactory(SSLContext context, String[] blacklistedProtocols) {
|
||||
this.delegate = context.getSocketFactory();
|
||||
this.blacklistedProtocols = Arrays.stream(blacklistedProtocols).map(String::trim).toArray(String[]::new);
|
||||
this.blacklistedProtocols = new ArrayList();
|
||||
|
||||
for (int i = 0; i < blacklistedProtocols.length; ++i) {
|
||||
this.blacklistedProtocols.add(blacklistedProtocols[i].trim());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -65,12 +69,15 @@ public class TLSSocketFactory extends SSLSocketFactory {
|
||||
}
|
||||
|
||||
String[] supported = ((SSLSocket) socket).getSupportedProtocols();
|
||||
List<String> filtered = new ArrayList();
|
||||
|
||||
String[] filtered = Arrays.stream(supported).filter(
|
||||
val -> Arrays.stream(this.blacklistedProtocols).noneMatch(val::equals)
|
||||
).toArray(String[]::new);
|
||||
for (int i = 0; i < supported.length; ++i) {
|
||||
if (!this.blacklistedProtocols.contains(supported[i])) {
|
||||
filtered.add(supported[i]);
|
||||
}
|
||||
}
|
||||
|
||||
((SSLSocket) socket).setEnabledProtocols(filtered);
|
||||
((SSLSocket) socket).setEnabledProtocols(filtered.toArray(new String[0]));
|
||||
|
||||
return socket;
|
||||
}
|
||||
|
||||
65
src/browser/cordova-http-plugin.js
vendored
65
src/browser/cordova-http-plugin.js
vendored
@@ -151,23 +151,27 @@ function setHeaders(xhr, headers) {
|
||||
}
|
||||
|
||||
function sendRequest(method, withData, opts, success, failure) {
|
||||
var data, serializer, headers, timeout, followRedirect, responseType, reqId;
|
||||
var data, serializer, headers, readTimeout, followRedirect, responseType, reqId;
|
||||
var url = opts[0];
|
||||
|
||||
if (withData) {
|
||||
data = opts[1];
|
||||
serializer = opts[2];
|
||||
headers = opts[3];
|
||||
timeout = opts[4];
|
||||
followRedirect = opts[5];
|
||||
responseType = opts[6];
|
||||
reqId = opts[7];
|
||||
// connect timeout not applied
|
||||
// connectTimeout = opts[4];
|
||||
readTimeout = opts[5];
|
||||
followRedirect = opts[6];
|
||||
responseType = opts[7];
|
||||
reqId = opts[8];
|
||||
} else {
|
||||
headers = opts[1];
|
||||
timeout = opts[2];
|
||||
followRedirect = opts[3];
|
||||
responseType = opts[4];
|
||||
reqId = opts[5];
|
||||
// connect timeout not applied
|
||||
// connectTimeout = opts[2];
|
||||
readTimeout = opts[3];
|
||||
followRedirect = opts[4];
|
||||
responseType = opts[5];
|
||||
reqId = opts[6];
|
||||
}
|
||||
|
||||
var onSuccess = injectRequestIdHandler(reqId, success);
|
||||
@@ -189,7 +193,7 @@ function sendRequest(method, withData, opts, success, failure) {
|
||||
}
|
||||
|
||||
switch (serializer) {
|
||||
case 'json':
|
||||
case 'json': {
|
||||
setDefaultContentType(headers, 'application/json; charset=utf8');
|
||||
processedData = serializeJsonData(data);
|
||||
|
||||
@@ -198,18 +202,21 @@ function sendRequest(method, withData, opts, success, failure) {
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
case 'utf8':
|
||||
case 'utf8': {
|
||||
setDefaultContentType(headers, 'text/plain; charset=utf8');
|
||||
processedData = data.text;
|
||||
break;
|
||||
}
|
||||
|
||||
case 'urlencoded':
|
||||
case 'urlencoded': {
|
||||
setDefaultContentType(headers, 'application/x-www-form-urlencoded');
|
||||
processedData = serializeParams(data);
|
||||
break;
|
||||
}
|
||||
|
||||
case 'multipart':
|
||||
case 'multipart': {
|
||||
const contentType = getHeaderValue(headers, 'Content-Type');
|
||||
|
||||
// intentionally don't set a default content type
|
||||
@@ -220,17 +227,31 @@ function sendRequest(method, withData, opts, success, failure) {
|
||||
|
||||
processedData = processMultipartData(data);
|
||||
break;
|
||||
}
|
||||
|
||||
case 'raw':
|
||||
case 'raw': {
|
||||
setDefaultContentType(headers, 'application/octet-stream');
|
||||
processedData = data;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// requesting text instead of JSON because it's parsed in the response handler
|
||||
xhr.responseType = responseType === 'json' ? 'text' : responseType;
|
||||
xhr.timeout = timeout * 1000;
|
||||
setHeaders(xhr, headers);
|
||||
|
||||
// we can't set connect timeout and read timeout separately on browser platform
|
||||
xhr.timeout = readTimeout * 1000;
|
||||
|
||||
try {
|
||||
setHeaders(xhr, headers);
|
||||
} catch(error) {
|
||||
return onFail({
|
||||
status: -1,
|
||||
error: error,
|
||||
url: url,
|
||||
headers: headers
|
||||
});
|
||||
}
|
||||
|
||||
xhr.onerror = function () {
|
||||
return onFail(createXhrFailureObject(xhr));
|
||||
@@ -267,7 +288,7 @@ function sendRequest(method, withData, opts, success, failure) {
|
||||
xhr.send(processedData);
|
||||
}
|
||||
|
||||
function abort(opts, success, failure) {
|
||||
function abort(opts, success) {
|
||||
var reqId = opts[0];
|
||||
var result = false;
|
||||
|
||||
@@ -302,19 +323,19 @@ var browserInterface = {
|
||||
abort: function (success, failure, opts) {
|
||||
return abort(opts, success, failure);
|
||||
},
|
||||
uploadFile: function (success, failure, opts) {
|
||||
uploadFile: function (success, failure) {
|
||||
return failure('advanced-http: function "uploadFile" not supported on browser platform');
|
||||
},
|
||||
uploadFiles: function (success, failure, opts) {
|
||||
uploadFiles: function (success, failure) {
|
||||
return failure('advanced-http: function "uploadFiles" not supported on browser platform');
|
||||
},
|
||||
downloadFile: function (success, failure, opts) {
|
||||
downloadFile: function (success, failure) {
|
||||
return failure('advanced-http: function "downloadFile" not supported on browser platform');
|
||||
},
|
||||
setServerTrustMode: function (success, failure, opts) {
|
||||
setServerTrustMode: function (success, failure) {
|
||||
return failure('advanced-http: function "setServerTrustMode" not supported on browser platform');
|
||||
},
|
||||
setClientAuthMode: function (success, failure, opts) {
|
||||
setClientAuthMode: function (success, failure) {
|
||||
return failure('advanced-http: function "setClientAuthMode" not supported on browser platform');
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "AFURLRequestSerialization.h"
|
||||
#import "SM_AFURLRequestSerialization.h"
|
||||
|
||||
@interface BinaryRequestSerializer : AFHTTPRequestSerializer
|
||||
@interface BinaryRequestSerializer : SM_AFHTTPRequestSerializer
|
||||
|
||||
+ (instancetype)serializer;
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
return serializer;
|
||||
}
|
||||
|
||||
#pragma mark - AFURLRequestSerialization
|
||||
#pragma mark - SM_AFURLRequestSerialization
|
||||
|
||||
- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
|
||||
withParameters:(id)parameters
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "AFURLResponseSerialization.h"
|
||||
#import "SM_AFURLResponseSerialization.h"
|
||||
|
||||
@interface BinaryResponseSerializer : AFHTTPResponseSerializer
|
||||
@interface BinaryResponseSerializer : SM_AFHTTPResponseSerializer
|
||||
|
||||
+ (instancetype)serializer;
|
||||
|
||||
|
||||
@@ -85,20 +85,20 @@ static BOOL AFErrorOrUnderlyingErrorHasCodeInDomain(NSError *error, NSInteger co
|
||||
if (response && [response isKindOfClass:[NSHTTPURLResponse class]]) {
|
||||
if (self.acceptableStatusCodes && ![self.acceptableStatusCodes containsIndex:(NSUInteger)response.statusCode] && [response URL]) {
|
||||
NSMutableDictionary *mutableUserInfo = [@{
|
||||
NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Request failed: %@ (%ld)", @"AFNetworking", nil), [NSHTTPURLResponse localizedStringForStatusCode:response.statusCode], (long)response.statusCode],
|
||||
NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Request failed: %@ (%ld)", @"SM_AFNetworking", nil), [NSHTTPURLResponse localizedStringForStatusCode:response.statusCode], (long)response.statusCode],
|
||||
NSURLErrorFailingURLErrorKey: [response URL],
|
||||
AFNetworkingOperationFailingURLResponseErrorKey: response,
|
||||
SM_AFNetworkingOperationFailingURLResponseErrorKey: response,
|
||||
} mutableCopy];
|
||||
|
||||
if (data) {
|
||||
mutableUserInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] = data;
|
||||
mutableUserInfo[SM_AFNetworkingOperationFailingURLResponseDataErrorKey] = data;
|
||||
|
||||
// trying to decode error message in body
|
||||
mutableUserInfo[AFNetworkingOperationFailingURLResponseBodyErrorKey] = [self decodeResponseData:data withEncoding:[self getEncoding:response]];
|
||||
mutableUserInfo[SM_AFNetworkingOperationFailingURLResponseBodyErrorKey] = [self decodeResponseData:data withEncoding:[self getEncoding:response]];
|
||||
}
|
||||
|
||||
if (error) {
|
||||
*error = [NSError errorWithDomain:AFURLResponseSerializationErrorDomain code:NSURLErrorBadServerResponse userInfo:mutableUserInfo];
|
||||
*error = [NSError errorWithDomain:SM_AFURLResponseSerializationErrorDomain code:NSURLErrorBadServerResponse userInfo:mutableUserInfo];
|
||||
}
|
||||
|
||||
return NO;
|
||||
@@ -108,14 +108,14 @@ static BOOL AFErrorOrUnderlyingErrorHasCodeInDomain(NSError *error, NSInteger co
|
||||
return YES;
|
||||
}
|
||||
|
||||
#pragma mark - AFURLResponseSerialization
|
||||
#pragma mark - SM_AFURLResponseSerialization
|
||||
|
||||
- (id)responseObjectForResponse:(NSURLResponse *)response
|
||||
data:(NSData *)data
|
||||
error:(NSError *__autoreleasing *)error
|
||||
{
|
||||
if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
|
||||
if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) {
|
||||
if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, SM_AFURLResponseSerializationErrorDomain)) {
|
||||
return nil;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,31 +4,31 @@
|
||||
#import "BinaryResponseSerializer.h"
|
||||
#import "TextResponseSerializer.h"
|
||||
#import "TextRequestSerializer.h"
|
||||
#import "AFHTTPSessionManager.h"
|
||||
#import "SM_AFHTTPSessionManager.h"
|
||||
#import "SDNetworkActivityIndicator.h"
|
||||
|
||||
@interface CordovaHttpPlugin()
|
||||
|
||||
- (void)addRequest:(NSNumber*)reqId forTask:(NSURLSessionDataTask*)task;
|
||||
- (void)removeRequest:(NSNumber*)reqId;
|
||||
- (void)setRequestHeaders:(NSDictionary*)headers forManager:(AFHTTPSessionManager*)manager;
|
||||
- (void)setRequestHeaders:(NSDictionary*)headers forManager:(SM_AFHTTPSessionManager*)manager;
|
||||
- (void)handleSuccess:(NSMutableDictionary*)dictionary withResponse:(NSHTTPURLResponse*)response andData:(id)data;
|
||||
- (void)handleError:(NSMutableDictionary*)dictionary withResponse:(NSHTTPURLResponse*)response error:(NSError*)error;
|
||||
- (NSNumber*)getStatusCode:(NSError*) error;
|
||||
- (NSMutableDictionary*)copyHeaderFields:(NSDictionary*)headerFields;
|
||||
- (void)setTimeout:(NSTimeInterval)timeout forManager:(AFHTTPSessionManager*)manager;
|
||||
- (void)setRedirect:(bool)redirect forManager:(AFHTTPSessionManager*)manager;
|
||||
- (void)setTimeout:(NSTimeInterval)timeout forManager:(SM_AFHTTPSessionManager*)manager;
|
||||
- (void)setRedirect:(bool)redirect forManager:(SM_AFHTTPSessionManager*)manager;
|
||||
|
||||
@end
|
||||
|
||||
@implementation CordovaHttpPlugin {
|
||||
AFSecurityPolicy *securityPolicy;
|
||||
SM_AFSecurityPolicy *securityPolicy;
|
||||
NSURLCredential *x509Credential;
|
||||
NSMutableDictionary *reqDict;
|
||||
}
|
||||
|
||||
- (void)pluginInitialize {
|
||||
securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
|
||||
securityPolicy = [SM_AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
|
||||
reqDict = [NSMutableDictionary dictionary];
|
||||
}
|
||||
|
||||
@@ -40,19 +40,19 @@
|
||||
[reqDict removeObjectForKey:reqId];
|
||||
}
|
||||
|
||||
- (void)setRequestSerializer:(NSString*)serializerName forManager:(AFHTTPSessionManager*)manager {
|
||||
- (void)setRequestSerializer:(NSString*)serializerName forManager:(SM_AFHTTPSessionManager*)manager {
|
||||
if ([serializerName isEqualToString:@"json"]) {
|
||||
manager.requestSerializer = [AFJSONRequestSerializer serializer];
|
||||
manager.requestSerializer = [SM_AFJSONRequestSerializer serializer];
|
||||
} else if ([serializerName isEqualToString:@"utf8"]) {
|
||||
manager.requestSerializer = [TextRequestSerializer serializer];
|
||||
} else if ([serializerName isEqualToString:@"raw"]) {
|
||||
manager.requestSerializer = [BinaryRequestSerializer serializer];
|
||||
} else {
|
||||
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
|
||||
manager.requestSerializer = [SM_AFHTTPRequestSerializer serializer];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)setupAuthChallengeBlock:(AFHTTPSessionManager*)manager {
|
||||
- (void)setupAuthChallengeBlock:(SM_AFHTTPSessionManager*)manager {
|
||||
[manager setSessionDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition(
|
||||
NSURLSession * _Nonnull session,
|
||||
NSURLAuthenticationChallenge * _Nonnull challenge,
|
||||
@@ -79,13 +79,13 @@
|
||||
}];
|
||||
}
|
||||
|
||||
- (void)setRequestHeaders:(NSDictionary*)headers forManager:(AFHTTPSessionManager*)manager {
|
||||
- (void)setRequestHeaders:(NSDictionary*)headers forManager:(SM_AFHTTPSessionManager*)manager {
|
||||
[headers enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
|
||||
[manager.requestSerializer setValue:obj forHTTPHeaderField:key];
|
||||
}];
|
||||
}
|
||||
|
||||
- (void)setRedirect:(bool)followRedirect forManager:(AFHTTPSessionManager*)manager {
|
||||
- (void)setRedirect:(bool)followRedirect forManager:(SM_AFHTTPSessionManager*)manager {
|
||||
[manager setTaskWillPerformHTTPRedirectionBlock:^NSURLRequest * _Nonnull(NSURLSession * _Nonnull session,
|
||||
NSURLSessionTask * _Nonnull task, NSURLResponse * _Nonnull response, NSURLRequest * _Nonnull request) {
|
||||
|
||||
@@ -97,11 +97,11 @@
|
||||
}];
|
||||
}
|
||||
|
||||
- (void)setTimeout:(NSTimeInterval)timeout forManager:(AFHTTPSessionManager*)manager {
|
||||
- (void)setTimeout:(NSTimeInterval)timeout forManager:(SM_AFHTTPSessionManager*)manager {
|
||||
[manager.requestSerializer setTimeoutInterval:timeout];
|
||||
}
|
||||
|
||||
- (void)setResponseSerializer:(NSString*)responseType forManager:(AFHTTPSessionManager*)manager {
|
||||
- (void)setResponseSerializer:(NSString*)responseType forManager:(SM_AFHTTPSessionManager*)manager {
|
||||
if ([responseType isEqualToString: @"text"] || [responseType isEqualToString: @"json"]) {
|
||||
manager.responseSerializer = [TextResponseSerializer serializer];
|
||||
} else {
|
||||
@@ -133,8 +133,8 @@
|
||||
[dictionary setObject:[self copyHeaderFields:response.allHeaderFields] forKey:@"headers"];
|
||||
if(!aborted){
|
||||
[dictionary setObject:[NSNumber numberWithInt:(int)response.statusCode] forKey:@"status"];
|
||||
if (error.userInfo[AFNetworkingOperationFailingURLResponseBodyErrorKey]) {
|
||||
[dictionary setObject:error.userInfo[AFNetworkingOperationFailingURLResponseBodyErrorKey] forKey:@"error"];
|
||||
if (error.userInfo[SM_AFNetworkingOperationFailingURLResponseBodyErrorKey]) {
|
||||
[dictionary setObject:error.userInfo[SM_AFNetworkingOperationFailingURLResponseBodyErrorKey] forKey:@"error"];
|
||||
}
|
||||
}
|
||||
} else if(!aborted) {
|
||||
@@ -193,19 +193,20 @@
|
||||
}
|
||||
|
||||
- (void)executeRequestWithoutData:(CDVInvokedUrlCommand*)command withMethod:(NSString*) method {
|
||||
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
|
||||
SM_AFHTTPSessionManager *manager = [SM_AFHTTPSessionManager manager];
|
||||
|
||||
NSString *url = [command.arguments objectAtIndex:0];
|
||||
NSDictionary *headers = [command.arguments objectAtIndex:1];
|
||||
NSTimeInterval timeoutInSeconds = [[command.arguments objectAtIndex:2] doubleValue];
|
||||
bool followRedirect = [[command.arguments objectAtIndex:3] boolValue];
|
||||
NSString *responseType = [command.arguments objectAtIndex:4];
|
||||
NSNumber *reqId = [command.arguments objectAtIndex:5];
|
||||
NSTimeInterval connectTimeout = [[command.arguments objectAtIndex:2] doubleValue];
|
||||
NSTimeInterval readTimeout = [[command.arguments objectAtIndex:3] doubleValue];
|
||||
bool followRedirect = [[command.arguments objectAtIndex:4] boolValue];
|
||||
NSString *responseType = [command.arguments objectAtIndex:5];
|
||||
NSNumber *reqId = [command.arguments objectAtIndex:6];
|
||||
|
||||
[self setRequestSerializer: @"default" forManager: manager];
|
||||
[self setupAuthChallengeBlock: manager];
|
||||
[self setRequestHeaders: headers forManager: manager];
|
||||
[self setTimeout:timeoutInSeconds forManager:manager];
|
||||
[self setTimeout:readTimeout forManager:manager];
|
||||
[self setRedirect:followRedirect forManager:manager];
|
||||
[self setResponseSerializer:responseType forManager:manager];
|
||||
|
||||
@@ -253,21 +254,22 @@
|
||||
}
|
||||
|
||||
- (void)executeRequestWithData:(CDVInvokedUrlCommand*)command withMethod:(NSString*)method {
|
||||
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
|
||||
SM_AFHTTPSessionManager *manager = [SM_AFHTTPSessionManager manager];
|
||||
|
||||
NSString *url = [command.arguments objectAtIndex:0];
|
||||
NSDictionary *data = [command.arguments objectAtIndex:1];
|
||||
NSString *serializerName = [command.arguments objectAtIndex:2];
|
||||
NSDictionary *headers = [command.arguments objectAtIndex:3];
|
||||
NSTimeInterval timeoutInSeconds = [[command.arguments objectAtIndex:4] doubleValue];
|
||||
bool followRedirect = [[command.arguments objectAtIndex:5] boolValue];
|
||||
NSString *responseType = [command.arguments objectAtIndex:6];
|
||||
NSNumber *reqId = [command.arguments objectAtIndex:7];
|
||||
NSTimeInterval connectTimeout = [[command.arguments objectAtIndex:4] doubleValue];
|
||||
NSTimeInterval readTimeout = [[command.arguments objectAtIndex:5] doubleValue];
|
||||
bool followRedirect = [[command.arguments objectAtIndex:6] boolValue];
|
||||
NSString *responseType = [command.arguments objectAtIndex:7];
|
||||
NSNumber *reqId = [command.arguments objectAtIndex:8];
|
||||
|
||||
[self setRequestSerializer: serializerName forManager: manager];
|
||||
[self setupAuthChallengeBlock: manager];
|
||||
[self setRequestHeaders: headers forManager: manager];
|
||||
[self setTimeout:timeoutInSeconds forManager:manager];
|
||||
[self setTimeout:readTimeout forManager:manager];
|
||||
[self setRedirect:followRedirect forManager:manager];
|
||||
[self setResponseSerializer:responseType forManager:manager];
|
||||
|
||||
@@ -351,15 +353,15 @@
|
||||
NSString *certMode = [command.arguments objectAtIndex:0];
|
||||
|
||||
if ([certMode isEqualToString: @"default"] || [certMode isEqualToString: @"legacy"]) {
|
||||
securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
|
||||
securityPolicy = [SM_AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
|
||||
securityPolicy.allowInvalidCertificates = NO;
|
||||
securityPolicy.validatesDomainName = YES;
|
||||
} else if ([certMode isEqualToString: @"nocheck"]) {
|
||||
securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
|
||||
securityPolicy = [SM_AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
|
||||
securityPolicy.allowInvalidCertificates = YES;
|
||||
securityPolicy.validatesDomainName = NO;
|
||||
} else if ([certMode isEqualToString: @"pinned"]) {
|
||||
securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
|
||||
securityPolicy = [SM_AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
|
||||
securityPolicy.allowInvalidCertificates = NO;
|
||||
securityPolicy.validatesDomainName = YES;
|
||||
}
|
||||
@@ -402,8 +404,18 @@
|
||||
} else {
|
||||
CFDictionaryRef identityDict = CFArrayGetValueAtIndex(items, 0);
|
||||
SecIdentityRef identity = (SecIdentityRef)CFDictionaryGetValue(identityDict, kSecImportItemIdentity);
|
||||
SecTrustRef trust = (SecTrustRef)CFDictionaryGetValue(identityDict, kSecImportItemTrust);
|
||||
|
||||
self->x509Credential = [NSURLCredential credentialWithIdentity:identity certificates: nil persistence:NSURLCredentialPersistenceForSession];
|
||||
int count = (int)SecTrustGetCertificateCount(trust);
|
||||
NSMutableArray* trustCertificates = nil;
|
||||
if (count > 1) {
|
||||
trustCertificates = [NSMutableArray arrayWithCapacity:SecTrustGetCertificateCount(trust)];
|
||||
for (int i=1;i<count; ++i) {
|
||||
[trustCertificates addObject:(id)SecTrustGetCertificateAtIndex(trust, i)];
|
||||
}
|
||||
}
|
||||
|
||||
self->x509Credential = [NSURLCredential credentialWithIdentity:identity certificates: trustCertificates persistence:NSURLCredentialPersistenceForSession];
|
||||
CFRelease(items);
|
||||
|
||||
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
|
||||
@@ -442,20 +454,20 @@
|
||||
}
|
||||
|
||||
- (void)uploadFiles:(CDVInvokedUrlCommand*)command {
|
||||
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
|
||||
SM_AFHTTPSessionManager *manager = [SM_AFHTTPSessionManager manager];
|
||||
|
||||
NSString *url = [command.arguments objectAtIndex:0];
|
||||
NSDictionary *headers = [command.arguments objectAtIndex:1];
|
||||
NSArray *filePaths = [command.arguments objectAtIndex: 2];
|
||||
NSArray *names = [command.arguments objectAtIndex: 3];
|
||||
NSTimeInterval timeoutInSeconds = [[command.arguments objectAtIndex:4] doubleValue];
|
||||
bool followRedirect = [[command.arguments objectAtIndex:5] boolValue];
|
||||
NSString *responseType = [command.arguments objectAtIndex:6];
|
||||
NSNumber *reqId = [command.arguments objectAtIndex:7];
|
||||
NSTimeInterval connectTimeout = [[command.arguments objectAtIndex:4] doubleValue];
|
||||
NSTimeInterval readTimeout = [[command.arguments objectAtIndex:5] doubleValue];
|
||||
bool followRedirect = [[command.arguments objectAtIndex:6] boolValue];
|
||||
NSString *responseType = [command.arguments objectAtIndex:7];
|
||||
NSNumber *reqId = [command.arguments objectAtIndex:8];
|
||||
|
||||
[self setRequestHeaders: headers forManager: manager];
|
||||
[self setupAuthChallengeBlock: manager];
|
||||
[self setTimeout:timeoutInSeconds forManager:manager];
|
||||
[self setTimeout:readTimeout forManager:manager];
|
||||
[self setRedirect:followRedirect forManager:manager];
|
||||
[self setResponseSerializer:responseType forManager:manager];
|
||||
|
||||
@@ -510,19 +522,20 @@
|
||||
}
|
||||
|
||||
- (void)downloadFile:(CDVInvokedUrlCommand*)command {
|
||||
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
|
||||
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
|
||||
SM_AFHTTPSessionManager *manager = [SM_AFHTTPSessionManager manager];
|
||||
manager.responseSerializer = [SM_AFHTTPResponseSerializer serializer];
|
||||
|
||||
NSString *url = [command.arguments objectAtIndex:0];
|
||||
NSDictionary *headers = [command.arguments objectAtIndex:1];
|
||||
NSString *filePath = [command.arguments objectAtIndex: 2];
|
||||
NSTimeInterval timeoutInSeconds = [[command.arguments objectAtIndex:3] doubleValue];
|
||||
bool followRedirect = [[command.arguments objectAtIndex:4] boolValue];
|
||||
NSNumber *reqId = [command.arguments objectAtIndex:5];
|
||||
NSTimeInterval connectTimeout = [[command.arguments objectAtIndex:3] doubleValue];
|
||||
NSTimeInterval readTimeout = [[command.arguments objectAtIndex:4] doubleValue];
|
||||
bool followRedirect = [[command.arguments objectAtIndex:5] boolValue];
|
||||
NSNumber *reqId = [command.arguments objectAtIndex:6];
|
||||
|
||||
[self setRequestHeaders: headers forManager: manager];
|
||||
[self setupAuthChallengeBlock: manager];
|
||||
[self setTimeout:timeoutInSeconds forManager:manager];
|
||||
[self setTimeout:readTimeout forManager:manager];
|
||||
[self setRedirect:followRedirect forManager:manager];
|
||||
|
||||
if ([filePath hasPrefix:@"file://"]) {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// AFHTTPSessionManager.h
|
||||
// SM_AFHTTPSessionManager.h
|
||||
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
@@ -31,14 +31,14 @@
|
||||
#import <CoreServices/CoreServices.h>
|
||||
#endif
|
||||
|
||||
#import "AFURLSessionManager.h"
|
||||
#import "SM_AFURLSessionManager.h"
|
||||
|
||||
/**
|
||||
`AFHTTPSessionManager` is a subclass of `AFURLSessionManager` with convenience methods for making HTTP requests. When a `baseURL` is provided, requests made with the `GET` / `POST` / et al. convenience methods can be made with relative paths.
|
||||
`SM_AFHTTPSessionManager` is a subclass of `SM_AFURLSessionManager` with convenience methods for making HTTP requests. When a `baseURL` is provided, requests made with the `GET` / `POST` / et al. convenience methods can be made with relative paths.
|
||||
|
||||
## Subclassing Notes
|
||||
|
||||
Developers targeting iOS 7 or Mac OS X 10.9 or later that deal extensively with a web service are encouraged to subclass `AFHTTPSessionManager`, providing a class method that returns a shared singleton object on which authentication and other configuration can be shared across the application.
|
||||
Developers targeting iOS 7 or Mac OS X 10.9 or later that deal extensively with a web service are encouraged to subclass `SM_AFHTTPSessionManager`, providing a class method that returns a shared singleton object on which authentication and other configuration can be shared across the application.
|
||||
|
||||
For developers targeting iOS 6 or Mac OS X 10.8 or earlier, `AFHTTPRequestOperationManager` may be used to similar effect.
|
||||
|
||||
@@ -48,9 +48,9 @@
|
||||
|
||||
## Serialization
|
||||
|
||||
Requests created by an HTTP client will contain default headers and encode parameters according to the `requestSerializer` property, which is an object conforming to `<AFURLRequestSerialization>`.
|
||||
Requests created by an HTTP client will contain default headers and encode parameters according to the `requestSerializer` property, which is an object conforming to `<SM_AFURLRequestSerialization>`.
|
||||
|
||||
Responses received from the server are automatically validated and serialized by the `responseSerializers` property, which is an object conforming to `<AFURLResponseSerialization>`
|
||||
Responses received from the server are automatically validated and serialized by the `responseSerializers` property, which is an object conforming to `<SM_AFURLResponseSerialization>`
|
||||
|
||||
## URL Construction Using Relative Paths
|
||||
|
||||
@@ -73,7 +73,7 @@
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@interface AFHTTPSessionManager : AFURLSessionManager <NSSecureCoding, NSCopying>
|
||||
@interface SM_AFHTTPSessionManager : SM_AFURLSessionManager <NSSecureCoding, NSCopying>
|
||||
|
||||
/**
|
||||
The URL used to construct requests from relative paths in methods like `requestWithMethod:URLString:parameters:`, and the `GET` / `POST` / et al. convenience methods.
|
||||
@@ -81,30 +81,30 @@ NS_ASSUME_NONNULL_BEGIN
|
||||
@property (readonly, nonatomic, strong, nullable) NSURL *baseURL;
|
||||
|
||||
/**
|
||||
Requests created with `requestWithMethod:URLString:parameters:` & `multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:` are constructed with a set of default headers using a parameter serialization specified by this property. By default, this is set to an instance of `AFHTTPRequestSerializer`, which serializes query string parameters for `GET`, `HEAD`, and `DELETE` requests, or otherwise URL-form-encodes HTTP message bodies.
|
||||
Requests created with `requestWithMethod:URLString:parameters:` & `multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:` are constructed with a set of default headers using a parameter serialization specified by this property. By default, this is set to an instance of `SM_AFHTTPRequestSerializer`, which serializes query string parameters for `GET`, `HEAD`, and `DELETE` requests, or otherwise URL-form-encodes HTTP message bodies.
|
||||
|
||||
@warning `requestSerializer` must not be `nil`.
|
||||
*/
|
||||
@property (nonatomic, strong) AFHTTPRequestSerializer <AFURLRequestSerialization> * requestSerializer;
|
||||
@property (nonatomic, strong) SM_AFHTTPRequestSerializer <SM_AFURLRequestSerialization> * requestSerializer;
|
||||
|
||||
/**
|
||||
Responses sent from the server in data tasks created with `dataTaskWithRequest:success:failure:` and run using the `GET` / `POST` / et al. convenience methods are automatically validated and serialized by the response serializer. By default, this property is set to an instance of `AFJSONResponseSerializer`.
|
||||
Responses sent from the server in data tasks created with `dataTaskWithRequest:success:failure:` and run using the `GET` / `POST` / et al. convenience methods are automatically validated and serialized by the response serializer. By default, this property is set to an instance of `SM_AFJSONResponseSerializer`.
|
||||
|
||||
@warning `responseSerializer` must not be `nil`.
|
||||
*/
|
||||
@property (nonatomic, strong) AFHTTPResponseSerializer <AFURLResponseSerialization> * responseSerializer;
|
||||
@property (nonatomic, strong) SM_AFHTTPResponseSerializer <SM_AFURLResponseSerialization> * responseSerializer;
|
||||
|
||||
///---------------------
|
||||
/// @name Initialization
|
||||
///---------------------
|
||||
|
||||
/**
|
||||
Creates and returns an `AFHTTPSessionManager` object.
|
||||
Creates and returns an `SM_AFHTTPSessionManager` object.
|
||||
*/
|
||||
+ (instancetype)manager;
|
||||
|
||||
/**
|
||||
Initializes an `AFHTTPSessionManager` object with the specified base URL.
|
||||
Initializes an `SM_AFHTTPSessionManager` object with the specified base URL.
|
||||
|
||||
@param url The base URL for the HTTP client.
|
||||
|
||||
@@ -113,7 +113,7 @@ NS_ASSUME_NONNULL_BEGIN
|
||||
- (instancetype)initWithBaseURL:(nullable NSURL *)url;
|
||||
|
||||
/**
|
||||
Initializes an `AFHTTPSessionManager` object with the specified base URL.
|
||||
Initializes an `SM_AFHTTPSessionManager` object with the specified base URL.
|
||||
|
||||
This is the designated initializer.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// AFHTTPSessionManager.m
|
||||
// SM_AFHTTPSessionManager.m
|
||||
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
@@ -19,10 +19,10 @@
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
#import "AFHTTPSessionManager.h"
|
||||
#import "SM_AFHTTPSessionManager.h"
|
||||
|
||||
#import "AFURLRequestSerialization.h"
|
||||
#import "AFURLResponseSerialization.h"
|
||||
#import "SM_AFURLRequestSerialization.h"
|
||||
#import "SM_AFURLResponseSerialization.h"
|
||||
|
||||
#import <Availability.h>
|
||||
#import <TargetConditionals.h>
|
||||
@@ -40,11 +40,11 @@
|
||||
#import <WatchKit/WatchKit.h>
|
||||
#endif
|
||||
|
||||
@interface AFHTTPSessionManager ()
|
||||
@interface SM_AFHTTPSessionManager ()
|
||||
@property (readwrite, nonatomic, strong) NSURL *baseURL;
|
||||
@end
|
||||
|
||||
@implementation AFHTTPSessionManager
|
||||
@implementation SM_AFHTTPSessionManager
|
||||
@dynamic responseSerializer;
|
||||
|
||||
+ (instancetype)manager {
|
||||
@@ -78,21 +78,21 @@
|
||||
|
||||
self.baseURL = url;
|
||||
|
||||
self.requestSerializer = [AFHTTPRequestSerializer serializer];
|
||||
self.responseSerializer = [AFJSONResponseSerializer serializer];
|
||||
self.requestSerializer = [SM_AFHTTPRequestSerializer serializer];
|
||||
self.responseSerializer = [SM_AFJSONResponseSerializer serializer];
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
#pragma mark -
|
||||
|
||||
- (void)setRequestSerializer:(AFHTTPRequestSerializer <AFURLRequestSerialization> *)requestSerializer {
|
||||
- (void)setRequestSerializer:(SM_AFHTTPRequestSerializer <SM_AFURLRequestSerialization> *)requestSerializer {
|
||||
NSParameterAssert(requestSerializer);
|
||||
|
||||
_requestSerializer = requestSerializer;
|
||||
}
|
||||
|
||||
- (void)setResponseSerializer:(AFHTTPResponseSerializer <AFURLResponseSerialization> *)responseSerializer {
|
||||
- (void)setResponseSerializer:(SM_AFHTTPResponseSerializer <SM_AFURLResponseSerialization> *)responseSerializer {
|
||||
NSParameterAssert(responseSerializer);
|
||||
|
||||
[super setResponseSerializer:responseSerializer];
|
||||
@@ -426,9 +426,9 @@
|
||||
return nil;
|
||||
}
|
||||
|
||||
self.requestSerializer = [decoder decodeObjectOfClass:[AFHTTPRequestSerializer class] forKey:NSStringFromSelector(@selector(requestSerializer))];
|
||||
self.responseSerializer = [decoder decodeObjectOfClass:[AFHTTPResponseSerializer class] forKey:NSStringFromSelector(@selector(responseSerializer))];
|
||||
AFSecurityPolicy *decodedPolicy = [decoder decodeObjectOfClass:[AFSecurityPolicy class] forKey:NSStringFromSelector(@selector(securityPolicy))];
|
||||
self.requestSerializer = [decoder decodeObjectOfClass:[SM_AFHTTPRequestSerializer class] forKey:NSStringFromSelector(@selector(requestSerializer))];
|
||||
self.responseSerializer = [decoder decodeObjectOfClass:[SM_AFHTTPResponseSerializer class] forKey:NSStringFromSelector(@selector(responseSerializer))];
|
||||
SM_AFSecurityPolicy *decodedPolicy = [decoder decodeObjectOfClass:[SM_AFSecurityPolicy class] forKey:NSStringFromSelector(@selector(securityPolicy))];
|
||||
if (decodedPolicy) {
|
||||
self.securityPolicy = decodedPolicy;
|
||||
}
|
||||
@@ -453,7 +453,7 @@
|
||||
#pragma mark - NSCopying
|
||||
|
||||
- (instancetype)copyWithZone:(NSZone *)zone {
|
||||
AFHTTPSessionManager *HTTPClient = [[[self class] allocWithZone:zone] initWithBaseURL:self.baseURL sessionConfiguration:self.session.configuration];
|
||||
SM_AFHTTPSessionManager *HTTPClient = [[[self class] allocWithZone:zone] initWithBaseURL:self.baseURL sessionConfiguration:self.session.configuration];
|
||||
|
||||
HTTPClient.requestSerializer = [self.requestSerializer copyWithZone:zone];
|
||||
HTTPClient.responseSerializer = [self.responseSerializer copyWithZone:zone];
|
||||
@@ -1,4 +1,4 @@
|
||||
// AFNetworkReachabilityManager.h
|
||||
// SM_AFNetworkReachabilityManager.h
|
||||
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
@@ -34,15 +34,15 @@ typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) {
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
/**
|
||||
`AFNetworkReachabilityManager` monitors the reachability of domains, and addresses for both WWAN and WiFi network interfaces.
|
||||
`SM_AFNetworkReachabilityManager` monitors the reachability of domains, and addresses for both WWAN and WiFi network interfaces.
|
||||
|
||||
Reachability can be used to determine background information about why a network operation failed, or to trigger a network operation retrying when a connection is established. It should not be used to prevent a user from initiating a network request, as it's possible that an initial request may be required to establish reachability.
|
||||
|
||||
See Apple's Reachability Sample Code ( https://developer.apple.com/library/ios/samplecode/reachability/ )
|
||||
|
||||
@warning Instances of `AFNetworkReachabilityManager` must be started with `-startMonitoring` before reachability status can be determined.
|
||||
@warning Instances of `SM_AFNetworkReachabilityManager` must be started with `-startMonitoring` before reachability status can be determined.
|
||||
*/
|
||||
@interface AFNetworkReachabilityManager : NSObject
|
||||
@interface SM_AFNetworkReachabilityManager : NSObject
|
||||
|
||||
/**
|
||||
The current network reachability status.
|
||||
@@ -150,7 +150,7 @@ NS_ASSUME_NONNULL_BEGIN
|
||||
/**
|
||||
## Network Reachability
|
||||
|
||||
The following constants are provided by `AFNetworkReachabilityManager` as possible network reachability statuses.
|
||||
The following constants are provided by `SM_AFNetworkReachabilityManager` as possible network reachability statuses.
|
||||
|
||||
enum {
|
||||
AFNetworkReachabilityStatusUnknown,
|
||||
@@ -175,8 +175,8 @@ NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
Strings that are used as keys in a `userInfo` dictionary in a network reachability status change notification.
|
||||
|
||||
`AFNetworkingReachabilityNotificationStatusItem`
|
||||
A key in the userInfo dictionary in a `AFNetworkingReachabilityDidChangeNotification` notification.
|
||||
`SM_AFNetworkingReachabilityNotificationStatusItem`
|
||||
A key in the userInfo dictionary in a `SM_AFNetworkingReachabilityDidChangeNotification` notification.
|
||||
The corresponding value is an `NSNumber` object representing the `AFNetworkReachabilityStatus` value for the current reachability status.
|
||||
*/
|
||||
|
||||
@@ -186,12 +186,12 @@ NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
/**
|
||||
Posted when network reachability changes.
|
||||
This notification assigns no notification object. The `userInfo` dictionary contains an `NSNumber` object under the `AFNetworkingReachabilityNotificationStatusItem` key, representing the `AFNetworkReachabilityStatus` value for the current network reachability.
|
||||
This notification assigns no notification object. The `userInfo` dictionary contains an `NSNumber` object under the `SM_AFNetworkingReachabilityNotificationStatusItem` key, representing the `AFNetworkReachabilityStatus` value for the current network reachability.
|
||||
|
||||
@warning In order for network reachability to be monitored, include the `SystemConfiguration` framework in the active target's "Link Binary With Library" build phase, and add `#import <SystemConfiguration/SystemConfiguration.h>` to the header prefix of the project (`Prefix.pch`).
|
||||
*/
|
||||
FOUNDATION_EXPORT NSString * const AFNetworkingReachabilityDidChangeNotification;
|
||||
FOUNDATION_EXPORT NSString * const AFNetworkingReachabilityNotificationStatusItem;
|
||||
FOUNDATION_EXPORT NSString * const SM_AFNetworkingReachabilityDidChangeNotification;
|
||||
FOUNDATION_EXPORT NSString * const SM_AFNetworkingReachabilityNotificationStatusItem;
|
||||
|
||||
///--------------------
|
||||
/// @name Functions
|
||||
@@ -200,7 +200,7 @@ FOUNDATION_EXPORT NSString * const AFNetworkingReachabilityNotificationStatusIte
|
||||
/**
|
||||
Returns a localized string representation of an `AFNetworkReachabilityStatus` value.
|
||||
*/
|
||||
FOUNDATION_EXPORT NSString * AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status);
|
||||
FOUNDATION_EXPORT NSString * SM_AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status);
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
#endif
|
||||
@@ -1,4 +1,4 @@
|
||||
// AFNetworkReachabilityManager.m
|
||||
// SM_AFNetworkReachabilityManager.m
|
||||
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
@@ -19,7 +19,7 @@
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
#import "AFNetworkReachabilityManager.h"
|
||||
#import "SM_AFNetworkReachabilityManager.h"
|
||||
#if !TARGET_OS_WATCH
|
||||
|
||||
#import <netinet/in.h>
|
||||
@@ -28,22 +28,22 @@
|
||||
#import <ifaddrs.h>
|
||||
#import <netdb.h>
|
||||
|
||||
NSString * const AFNetworkingReachabilityDidChangeNotification = @"com.alamofire.networking.reachability.change";
|
||||
NSString * const AFNetworkingReachabilityNotificationStatusItem = @"AFNetworkingReachabilityNotificationStatusItem";
|
||||
NSString * const SM_AFNetworkingReachabilityDidChangeNotification = @"com.alamofire.networking.reachability.change";
|
||||
NSString * const SM_AFNetworkingReachabilityNotificationStatusItem = @"SM_AFNetworkingReachabilityNotificationStatusItem";
|
||||
|
||||
typedef void (^AFNetworkReachabilityStatusBlock)(AFNetworkReachabilityStatus status);
|
||||
|
||||
NSString * AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status) {
|
||||
NSString * SM_AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status) {
|
||||
switch (status) {
|
||||
case AFNetworkReachabilityStatusNotReachable:
|
||||
return NSLocalizedStringFromTable(@"Not Reachable", @"AFNetworking", nil);
|
||||
return NSLocalizedStringFromTable(@"Not Reachable", @"SM_AFNetworking", nil);
|
||||
case AFNetworkReachabilityStatusReachableViaWWAN:
|
||||
return NSLocalizedStringFromTable(@"Reachable via WWAN", @"AFNetworking", nil);
|
||||
return NSLocalizedStringFromTable(@"Reachable via WWAN", @"SM_AFNetworking", nil);
|
||||
case AFNetworkReachabilityStatusReachableViaWiFi:
|
||||
return NSLocalizedStringFromTable(@"Reachable via WiFi", @"AFNetworking", nil);
|
||||
return NSLocalizedStringFromTable(@"Reachable via WiFi", @"SM_AFNetworking", nil);
|
||||
case AFNetworkReachabilityStatusUnknown:
|
||||
default:
|
||||
return NSLocalizedStringFromTable(@"Unknown", @"AFNetworking", nil);
|
||||
return NSLocalizedStringFromTable(@"Unknown", @"SM_AFNetworking", nil);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -85,8 +85,8 @@ static void AFPostReachabilityStatusChange(SCNetworkReachabilityFlags flags, AFN
|
||||
block(status);
|
||||
}
|
||||
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
|
||||
NSDictionary *userInfo = @{ AFNetworkingReachabilityNotificationStatusItem: @(status) };
|
||||
[notificationCenter postNotificationName:AFNetworkingReachabilityDidChangeNotification object:nil userInfo:userInfo];
|
||||
NSDictionary *userInfo = @{ SM_AFNetworkingReachabilityNotificationStatusItem: @(status) };
|
||||
[notificationCenter postNotificationName:SM_AFNetworkingReachabilityDidChangeNotification object:nil userInfo:userInfo];
|
||||
});
|
||||
}
|
||||
|
||||
@@ -105,16 +105,16 @@ static void AFNetworkReachabilityReleaseCallback(const void *info) {
|
||||
}
|
||||
}
|
||||
|
||||
@interface AFNetworkReachabilityManager ()
|
||||
@interface SM_AFNetworkReachabilityManager ()
|
||||
@property (readonly, nonatomic, assign) SCNetworkReachabilityRef networkReachability;
|
||||
@property (readwrite, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus;
|
||||
@property (readwrite, nonatomic, copy) AFNetworkReachabilityStatusBlock networkReachabilityStatusBlock;
|
||||
@end
|
||||
|
||||
@implementation AFNetworkReachabilityManager
|
||||
@implementation SM_AFNetworkReachabilityManager
|
||||
|
||||
+ (instancetype)sharedManager {
|
||||
static AFNetworkReachabilityManager *_sharedManager = nil;
|
||||
static SM_AFNetworkReachabilityManager *_sharedManager = nil;
|
||||
static dispatch_once_t onceToken;
|
||||
dispatch_once(&onceToken, ^{
|
||||
_sharedManager = [self manager];
|
||||
@@ -126,7 +126,7 @@ static void AFNetworkReachabilityReleaseCallback(const void *info) {
|
||||
+ (instancetype)managerForDomain:(NSString *)domain {
|
||||
SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [domain UTF8String]);
|
||||
|
||||
AFNetworkReachabilityManager *manager = [[self alloc] initWithReachability:reachability];
|
||||
SM_AFNetworkReachabilityManager *manager = [[self alloc] initWithReachability:reachability];
|
||||
|
||||
CFRelease(reachability);
|
||||
|
||||
@@ -135,7 +135,7 @@ static void AFNetworkReachabilityReleaseCallback(const void *info) {
|
||||
|
||||
+ (instancetype)managerForAddress:(const void *)address {
|
||||
SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr *)address);
|
||||
AFNetworkReachabilityManager *manager = [[self alloc] initWithReachability:reachability];
|
||||
SM_AFNetworkReachabilityManager *manager = [[self alloc] initWithReachability:reachability];
|
||||
|
||||
CFRelease(reachability);
|
||||
|
||||
@@ -240,7 +240,7 @@ static void AFNetworkReachabilityReleaseCallback(const void *info) {
|
||||
#pragma mark -
|
||||
|
||||
- (NSString *)localizedNetworkReachabilityStatusString {
|
||||
return AFStringFromNetworkReachabilityStatus(self.networkReachabilityStatus);
|
||||
return SM_AFStringFromNetworkReachabilityStatus(self.networkReachabilityStatus);
|
||||
}
|
||||
|
||||
#pragma mark -
|
||||
@@ -1,6 +1,6 @@
|
||||
// AFNetworking.h
|
||||
// SM_AFNetworking.h
|
||||
//
|
||||
// Copyright (c) 2013 AFNetworking (http://afnetworking.com/)
|
||||
// Copyright (c) 2013 SM_AFNetworking (http://afnetworking.com/)
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
@@ -27,15 +27,15 @@
|
||||
#ifndef _AFNETWORKING_
|
||||
#define _AFNETWORKING_
|
||||
|
||||
#import "AFURLRequestSerialization.h"
|
||||
#import "AFURLResponseSerialization.h"
|
||||
#import "AFSecurityPolicy.h"
|
||||
#import "SM_AFURLRequestSerialization.h"
|
||||
#import "SM_AFURLResponseSerialization.h"
|
||||
#import "SM_AFSecurityPolicy.h"
|
||||
|
||||
#if !TARGET_OS_WATCH
|
||||
#import "AFNetworkReachabilityManager.h"
|
||||
#import "SM_AFNetworkReachabilityManager.h"
|
||||
#endif
|
||||
|
||||
#import "AFURLSessionManager.h"
|
||||
#import "AFHTTPSessionManager.h"
|
||||
#import "SM_AFURLSessionManager.h"
|
||||
#import "SM_AFHTTPSessionManager.h"
|
||||
|
||||
#endif /* _AFNETWORKING_ */
|
||||
@@ -1,4 +1,4 @@
|
||||
// AFSecurityPolicy.h
|
||||
// SM_AFSecurityPolicy.h
|
||||
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
@@ -29,14 +29,14 @@ typedef NS_ENUM(NSUInteger, AFSSLPinningMode) {
|
||||
};
|
||||
|
||||
/**
|
||||
`AFSecurityPolicy` evaluates server trust against pinned X.509 certificates and public keys over secure connections.
|
||||
`SM_AFSecurityPolicy` evaluates server trust against pinned X.509 certificates and public keys over secure connections.
|
||||
|
||||
Adding pinned SSL certificates to your app helps prevent man-in-the-middle attacks and other vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged to route all communication over an HTTPS connection with SSL pinning configured and enabled.
|
||||
*/
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@interface AFSecurityPolicy : NSObject <NSSecureCoding, NSCopying>
|
||||
@interface SM_AFSecurityPolicy : NSObject <NSSecureCoding, NSCopying>
|
||||
|
||||
/**
|
||||
The criteria by which server trust should be evaluated against the pinned SSL certificates. Defaults to `AFSSLPinningModeNone`.
|
||||
@@ -46,7 +46,7 @@ NS_ASSUME_NONNULL_BEGIN
|
||||
/**
|
||||
The certificates used to evaluate server trust according to the SSL pinning mode.
|
||||
|
||||
By default, this property is set to any (`.cer`) certificates included in the target compiling AFNetworking. Note that if you are using AFNetworking as embedded framework, no certificates will be pinned by default. Use `certificatesInBundle` to load certificates from your target, and then create a new policy by calling `policyWithPinningMode:withPinnedCertificates`.
|
||||
By default, this property is set to any (`.cer`) certificates included in the target compiling SM_AFNetworking. Note that if you are using SM_AFNetworking as embedded framework, no certificates will be pinned by default. Use `certificatesInBundle` to load certificates from your target, and then create a new policy by calling `policyWithPinningMode:withPinnedCertificates`.
|
||||
|
||||
Note that if pinning is enabled, `evaluateServerTrust:forDomain:` will return true if any pinned certificate matches.
|
||||
*/
|
||||
@@ -67,7 +67,7 @@ NS_ASSUME_NONNULL_BEGIN
|
||||
///-----------------------------------------
|
||||
|
||||
/**
|
||||
Returns any certificates included in the bundle. If you are using AFNetworking as an embedded framework, you must use this method to find the certificates you have included in your app bundle, and use them when creating your security policy by calling `policyWithPinningMode:withPinnedCertificates`.
|
||||
Returns any certificates included in the bundle. If you are using SM_AFNetworking as an embedded framework, you must use this method to find the certificates you have included in your app bundle, and use them when creating your security policy by calling `policyWithPinningMode:withPinnedCertificates`.
|
||||
|
||||
@return The certificates included in the given bundle.
|
||||
*/
|
||||
@@ -1,4 +1,4 @@
|
||||
// AFSecurityPolicy.m
|
||||
// SM_AFSecurityPolicy.m
|
||||
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
@@ -19,7 +19,7 @@
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
#import "AFSecurityPolicy.h"
|
||||
#import "SM_AFSecurityPolicy.h"
|
||||
|
||||
#import <AssertMacros.h>
|
||||
|
||||
@@ -148,15 +148,25 @@ static NSArray * AFPublicKeyTrustChainForServerTrust(SecTrustRef serverTrust) {
|
||||
|
||||
#pragma mark -
|
||||
|
||||
@interface AFSecurityPolicy()
|
||||
@interface SM_AFSecurityPolicy()
|
||||
@property (readwrite, nonatomic, assign) AFSSLPinningMode SSLPinningMode;
|
||||
@property (readwrite, nonatomic, strong) NSSet *pinnedPublicKeys;
|
||||
@end
|
||||
|
||||
@implementation AFSecurityPolicy
|
||||
@implementation SM_AFSecurityPolicy
|
||||
|
||||
+(BOOL) isRunningOnCapacitor {
|
||||
return NSClassFromString(@"CAPPlugin") != nil;
|
||||
}
|
||||
|
||||
+ (NSSet *)certificatesInBundle:(NSBundle *)bundle {
|
||||
NSArray *paths = [bundle pathsForResourcesOfType:@"cer" inDirectory:@"www/certificates"];
|
||||
NSString* assetDir = @"www";
|
||||
if([self isRunningOnCapacitor]) {
|
||||
// we are running on capacitor and its assets dir is 'public'
|
||||
assetDir = @"public";
|
||||
}
|
||||
|
||||
NSArray *paths = [bundle pathsForResourcesOfType:@"cer" inDirectory: [NSString stringWithFormat:@"%@/certificates", assetDir]];
|
||||
NSMutableSet *certificates = [NSMutableSet setWithCapacity:[paths count]];
|
||||
|
||||
for (NSString *path in paths) {
|
||||
@@ -171,7 +181,7 @@ static NSArray * AFPublicKeyTrustChainForServerTrust(SecTrustRef serverTrust) {
|
||||
static NSSet *_defaultPinnedCertificates = nil;
|
||||
static dispatch_once_t onceToken;
|
||||
dispatch_once(&onceToken, ^{
|
||||
NSBundle *bundle = [NSBundle bundleForClass:[self class]];
|
||||
NSBundle *bundle = [self isRunningOnCapacitor] ? [NSBundle mainBundle] : [NSBundle bundleForClass:[self class]];
|
||||
_defaultPinnedCertificates = [self certificatesInBundle:bundle];
|
||||
});
|
||||
|
||||
@@ -179,7 +189,7 @@ static NSArray * AFPublicKeyTrustChainForServerTrust(SecTrustRef serverTrust) {
|
||||
}
|
||||
|
||||
+ (instancetype)defaultPolicy {
|
||||
AFSecurityPolicy *securityPolicy = [[self alloc] init];
|
||||
SM_AFSecurityPolicy *securityPolicy = [[self alloc] init];
|
||||
securityPolicy.SSLPinningMode = AFSSLPinningModeNone;
|
||||
|
||||
return securityPolicy;
|
||||
@@ -190,7 +200,7 @@ static NSArray * AFPublicKeyTrustChainForServerTrust(SecTrustRef serverTrust) {
|
||||
}
|
||||
|
||||
+ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode withPinnedCertificates:(NSSet *)pinnedCertificates {
|
||||
AFSecurityPolicy *securityPolicy = [[self alloc] init];
|
||||
SM_AFSecurityPolicy *securityPolicy = [[self alloc] init];
|
||||
securityPolicy.SSLPinningMode = pinningMode;
|
||||
|
||||
[securityPolicy setPinnedCertificates:pinnedCertificates];
|
||||
@@ -341,7 +351,7 @@ static NSArray * AFPublicKeyTrustChainForServerTrust(SecTrustRef serverTrust) {
|
||||
#pragma mark - NSCopying
|
||||
|
||||
- (instancetype)copyWithZone:(NSZone *)zone {
|
||||
AFSecurityPolicy *securityPolicy = [[[self class] allocWithZone:zone] init];
|
||||
SM_AFSecurityPolicy *securityPolicy = [[[self class] allocWithZone:zone] init];
|
||||
securityPolicy.SSLPinningMode = self.SSLPinningMode;
|
||||
securityPolicy.allowInvalidCertificates = self.allowInvalidCertificates;
|
||||
securityPolicy.validatesDomainName = self.validatesDomainName;
|
||||
@@ -1,4 +1,4 @@
|
||||
// AFURLRequestSerialization.h
|
||||
// SM_AFURLRequestSerialization.h
|
||||
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
@@ -44,7 +44,7 @@ NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@return The percent-escaped string.
|
||||
*/
|
||||
FOUNDATION_EXPORT NSString * AFPercentEscapedStringFromString(NSString *string);
|
||||
FOUNDATION_EXPORT NSString * SM_AFPercentEscapedStringFromString(NSString *string);
|
||||
|
||||
/**
|
||||
A helper method to generate encoded url query parameters for appending to the end of a URL.
|
||||
@@ -53,14 +53,14 @@ FOUNDATION_EXPORT NSString * AFPercentEscapedStringFromString(NSString *string);
|
||||
|
||||
@return A url encoded query string
|
||||
*/
|
||||
FOUNDATION_EXPORT NSString * AFQueryStringFromParameters(NSDictionary *parameters);
|
||||
FOUNDATION_EXPORT NSString * SM_AFQueryStringFromParameters(NSDictionary *parameters);
|
||||
|
||||
/**
|
||||
The `AFURLRequestSerialization` protocol is adopted by an object that encodes parameters for a specified HTTP requests. Request serializers may encode parameters as query strings, HTTP bodies, setting the appropriate HTTP header fields as necessary.
|
||||
The `SM_AFURLRequestSerialization` protocol is adopted by an object that encodes parameters for a specified HTTP requests. Request serializers may encode parameters as query strings, HTTP bodies, setting the appropriate HTTP header fields as necessary.
|
||||
|
||||
For example, a JSON request serializer may set the HTTP body of the request to a JSON representation, and set the `Content-Type` HTTP header field value to `application/json`.
|
||||
*/
|
||||
@protocol AFURLRequestSerialization <NSObject, NSSecureCoding, NSCopying>
|
||||
@protocol SM_AFURLRequestSerialization <NSObject, NSSecureCoding, NSCopying>
|
||||
|
||||
/**
|
||||
Returns a request with the specified parameters encoded into a copy of the original request.
|
||||
@@ -89,11 +89,11 @@ typedef NS_ENUM(NSUInteger, AFHTTPRequestQueryStringSerializationStyle) {
|
||||
@protocol AFMultipartFormData;
|
||||
|
||||
/**
|
||||
`AFHTTPRequestSerializer` conforms to the `AFURLRequestSerialization` & `AFURLResponseSerialization` protocols, offering a concrete base implementation of query string / URL form-encoded parameter serialization and default request headers, as well as response status code and content type validation.
|
||||
`SM_AFHTTPRequestSerializer` conforms to the `SM_AFURLRequestSerialization` & `SM_AFURLResponseSerialization` protocols, offering a concrete base implementation of query string / URL form-encoded parameter serialization and default request headers, as well as response status code and content type validation.
|
||||
|
||||
Any request or response serializer dealing with HTTP is encouraged to subclass `AFHTTPRequestSerializer` in order to ensure consistent default behavior.
|
||||
Any request or response serializer dealing with HTTP is encouraged to subclass `SM_AFHTTPRequestSerializer` in order to ensure consistent default behavior.
|
||||
*/
|
||||
@interface AFHTTPRequestSerializer : NSObject <AFURLRequestSerialization>
|
||||
@interface SM_AFHTTPRequestSerializer : NSObject <SM_AFURLRequestSerialization>
|
||||
|
||||
/**
|
||||
The string encoding used to serialize parameters. `NSUTF8StringEncoding` by default.
|
||||
@@ -265,7 +265,7 @@ forHTTPHeaderField:(NSString *)field;
|
||||
@param fileURL The file URL to write multipart form contents to.
|
||||
@param handler A handler block to execute.
|
||||
|
||||
@discussion There is a bug in `NSURLSessionTask` that causes requests to not send a `Content-Length` header when streaming contents from an HTTP body, which is notably problematic when interacting with the Amazon S3 webservice. As a workaround, this method takes a request constructed with `multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:error:`, or any other request with an `HTTPBodyStream`, writes the contents to the specified file and returns a copy of the original request with the `HTTPBodyStream` property set to `nil`. From here, the file can either be passed to `AFURLSessionManager -uploadTaskWithRequest:fromFile:progress:completionHandler:`, or have its contents read into an `NSData` that's assigned to the `HTTPBody` property of the request.
|
||||
@discussion There is a bug in `NSURLSessionTask` that causes requests to not send a `Content-Length` header when streaming contents from an HTTP body, which is notably problematic when interacting with the Amazon S3 webservice. As a workaround, this method takes a request constructed with `multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:error:`, or any other request with an `HTTPBodyStream`, writes the contents to the specified file and returns a copy of the original request with the `HTTPBodyStream` property set to `nil`. From here, the file can either be passed to `SM_AFURLSessionManager -uploadTaskWithRequest:fromFile:progress:completionHandler:`, or have its contents read into an `NSData` that's assigned to the `HTTPBody` property of the request.
|
||||
|
||||
@see https://github.com/AFNetworking/AFNetworking/issues/1398
|
||||
*/
|
||||
@@ -278,7 +278,7 @@ forHTTPHeaderField:(NSString *)field;
|
||||
#pragma mark -
|
||||
|
||||
/**
|
||||
The `AFMultipartFormData` protocol defines the methods supported by the parameter in the block argument of `AFHTTPRequestSerializer -multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:`.
|
||||
The `AFMultipartFormData` protocol defines the methods supported by the parameter in the block argument of `SM_AFHTTPRequestSerializer -multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:`.
|
||||
*/
|
||||
@protocol AFMultipartFormData
|
||||
|
||||
@@ -365,7 +365,7 @@ forHTTPHeaderField:(NSString *)field;
|
||||
/**
|
||||
Throttles request bandwidth by limiting the packet size and adding a delay for each chunk read from the upload stream.
|
||||
|
||||
When uploading over a 3G or EDGE connection, requests may fail with "request body stream exhausted". Setting a maximum packet size and delay according to the recommended values (`kAFUploadStream3GSuggestedPacketSize` and `kAFUploadStream3GSuggestedDelay`) lowers the risk of the input stream exceeding its allocated bandwidth. Unfortunately, there is no definite way to distinguish between a 3G, EDGE, or LTE connection over `NSURLConnection`. As such, it is not recommended that you throttle bandwidth based solely on network reachability. Instead, you should consider checking for the "request body stream exhausted" in a failure block, and then retrying the request with throttled bandwidth.
|
||||
When uploading over a 3G or EDGE connection, requests may fail with "request body stream exhausted". Setting a maximum packet size and delay according to the recommended values (`SM_kAFUploadStream3GSuggestedPacketSize` and `SM_kAFUploadStream3GSuggestedDelay`) lowers the risk of the input stream exceeding its allocated bandwidth. Unfortunately, there is no definite way to distinguish between a 3G, EDGE, or LTE connection over `NSURLConnection`. As such, it is not recommended that you throttle bandwidth based solely on network reachability. Instead, you should consider checking for the "request body stream exhausted" in a failure block, and then retrying the request with throttled bandwidth.
|
||||
|
||||
@param numberOfBytes Maximum packet size, in number of bytes. The default packet size for an input stream is 16kb.
|
||||
@param delay Duration of delay each time a packet is read. By default, no delay is set.
|
||||
@@ -378,9 +378,9 @@ forHTTPHeaderField:(NSString *)field;
|
||||
#pragma mark -
|
||||
|
||||
/**
|
||||
`AFJSONRequestSerializer` is a subclass of `AFHTTPRequestSerializer` that encodes parameters as JSON using `NSJSONSerialization`, setting the `Content-Type` of the encoded request to `application/json`.
|
||||
`SM_AFJSONRequestSerializer` is a subclass of `SM_AFHTTPRequestSerializer` that encodes parameters as JSON using `NSJSONSerialization`, setting the `Content-Type` of the encoded request to `application/json`.
|
||||
*/
|
||||
@interface AFJSONRequestSerializer : AFHTTPRequestSerializer
|
||||
@interface SM_AFJSONRequestSerializer : SM_AFHTTPRequestSerializer
|
||||
|
||||
/**
|
||||
Options for writing the request JSON data from Foundation objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONWritingOptions". `0` by default.
|
||||
@@ -399,9 +399,9 @@ forHTTPHeaderField:(NSString *)field;
|
||||
#pragma mark -
|
||||
|
||||
/**
|
||||
`AFPropertyListRequestSerializer` is a subclass of `AFHTTPRequestSerializer` that encodes parameters as JSON using `NSPropertyListSerializer`, setting the `Content-Type` of the encoded request to `application/x-plist`.
|
||||
`SM_AFPropertyListRequestSerializer` is a subclass of `SM_AFHTTPRequestSerializer` that encodes parameters as JSON using `NSPropertyListSerializer`, setting the `Content-Type` of the encoded request to `application/x-plist`.
|
||||
*/
|
||||
@interface AFPropertyListRequestSerializer : AFHTTPRequestSerializer
|
||||
@interface SM_AFPropertyListRequestSerializer : SM_AFHTTPRequestSerializer
|
||||
|
||||
/**
|
||||
The property list format. Possible values are described in "NSPropertyListFormat".
|
||||
@@ -437,28 +437,28 @@ forHTTPHeaderField:(NSString *)field;
|
||||
|
||||
The following error domain is predefined.
|
||||
|
||||
- `NSString * const AFURLRequestSerializationErrorDomain`
|
||||
- `NSString * const SM_AFURLRequestSerializationErrorDomain`
|
||||
|
||||
### Constants
|
||||
|
||||
`AFURLRequestSerializationErrorDomain`
|
||||
AFURLRequestSerializer errors. Error codes for `AFURLRequestSerializationErrorDomain` correspond to codes in `NSURLErrorDomain`.
|
||||
`SM_AFURLRequestSerializationErrorDomain`
|
||||
AFURLRequestSerializer errors. Error codes for `SM_AFURLRequestSerializationErrorDomain` correspond to codes in `NSURLErrorDomain`.
|
||||
*/
|
||||
FOUNDATION_EXPORT NSString * const AFURLRequestSerializationErrorDomain;
|
||||
FOUNDATION_EXPORT NSString * const SM_AFURLRequestSerializationErrorDomain;
|
||||
|
||||
/**
|
||||
## User info dictionary keys
|
||||
|
||||
These keys may exist in the user info dictionary, in addition to those defined for NSError.
|
||||
|
||||
- `NSString * const AFNetworkingOperationFailingURLRequestErrorKey`
|
||||
- `NSString * const SM_AFNetworkingOperationFailingURLRequestErrorKey`
|
||||
|
||||
### Constants
|
||||
|
||||
`AFNetworkingOperationFailingURLRequestErrorKey`
|
||||
The corresponding value is an `NSURLRequest` containing the request of the operation associated with an error. This key is only present in the `AFURLRequestSerializationErrorDomain`.
|
||||
`SM_AFNetworkingOperationFailingURLRequestErrorKey`
|
||||
The corresponding value is an `NSURLRequest` containing the request of the operation associated with an error. This key is only present in the `SM_AFURLRequestSerializationErrorDomain`.
|
||||
*/
|
||||
FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLRequestErrorKey;
|
||||
FOUNDATION_EXPORT NSString * const SM_AFNetworkingOperationFailingURLRequestErrorKey;
|
||||
|
||||
/**
|
||||
## Throttling Bandwidth for HTTP Request Input Streams
|
||||
@@ -467,13 +467,13 @@ FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLRequestErrorKe
|
||||
|
||||
### Constants
|
||||
|
||||
`kAFUploadStream3GSuggestedPacketSize`
|
||||
`SM_kAFUploadStream3GSuggestedPacketSize`
|
||||
Maximum packet size, in number of bytes. Equal to 16kb.
|
||||
|
||||
`kAFUploadStream3GSuggestedDelay`
|
||||
`SM_kAFUploadStream3GSuggestedDelay`
|
||||
Duration of delay each time a packet is read. Equal to 0.2 seconds.
|
||||
*/
|
||||
FOUNDATION_EXPORT NSUInteger const kAFUploadStream3GSuggestedPacketSize;
|
||||
FOUNDATION_EXPORT NSTimeInterval const kAFUploadStream3GSuggestedDelay;
|
||||
FOUNDATION_EXPORT NSUInteger const SM_kAFUploadStream3GSuggestedPacketSize;
|
||||
FOUNDATION_EXPORT NSTimeInterval const SM_kAFUploadStream3GSuggestedDelay;
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
@@ -1,4 +1,4 @@
|
||||
// AFURLRequestSerialization.m
|
||||
// SM_AFURLRequestSerialization.m
|
||||
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
@@ -19,7 +19,7 @@
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
#import "AFURLRequestSerialization.h"
|
||||
#import "SM_AFURLRequestSerialization.h"
|
||||
|
||||
#if TARGET_OS_IOS || TARGET_OS_WATCH || TARGET_OS_TV
|
||||
#import <MobileCoreServices/MobileCoreServices.h>
|
||||
@@ -27,8 +27,8 @@
|
||||
#import <CoreServices/CoreServices.h>
|
||||
#endif
|
||||
|
||||
NSString * const AFURLRequestSerializationErrorDomain = @"com.alamofire.error.serialization.request";
|
||||
NSString * const AFNetworkingOperationFailingURLRequestErrorKey = @"com.alamofire.serialization.request.error.response";
|
||||
NSString * const SM_AFURLRequestSerializationErrorDomain = @"com.alamofire.error.serialization.request";
|
||||
NSString * const SM_AFNetworkingOperationFailingURLRequestErrorKey = @"com.alamofire.serialization.request.error.response";
|
||||
|
||||
typedef NSString * (^AFQueryStringSerializationBlock)(NSURLRequest *request, id parameters, NSError *__autoreleasing *error);
|
||||
|
||||
@@ -44,7 +44,7 @@ typedef NSString * (^AFQueryStringSerializationBlock)(NSURLRequest *request, id
|
||||
- parameter string: The string to be percent-escaped.
|
||||
- returns: The percent-escaped string.
|
||||
*/
|
||||
NSString * AFPercentEscapedStringFromString(NSString *string) {
|
||||
NSString * SM_AFPercentEscapedStringFromString(NSString *string) {
|
||||
static NSString * const kAFCharactersGeneralDelimitersToEncode = @":#[]@"; // does not include "?" or "/" due to RFC 3986 - Section 3.4
|
||||
static NSString * const kAFCharactersSubDelimitersToEncode = @"!$&'()*+,;=";
|
||||
|
||||
@@ -78,7 +78,7 @@ NSString * AFPercentEscapedStringFromString(NSString *string) {
|
||||
|
||||
#pragma mark -
|
||||
|
||||
@interface AFQueryStringPair : NSObject
|
||||
@interface SM_AFQueryStringPair : NSObject
|
||||
@property (readwrite, nonatomic, strong) id field;
|
||||
@property (readwrite, nonatomic, strong) id value;
|
||||
|
||||
@@ -87,7 +87,7 @@ NSString * AFPercentEscapedStringFromString(NSString *string) {
|
||||
- (NSString *)URLEncodedStringValue;
|
||||
@end
|
||||
|
||||
@implementation AFQueryStringPair
|
||||
@implementation SM_AFQueryStringPair
|
||||
|
||||
- (instancetype)initWithField:(id)field value:(id)value {
|
||||
self = [super init];
|
||||
@@ -103,9 +103,9 @@ NSString * AFPercentEscapedStringFromString(NSString *string) {
|
||||
|
||||
- (NSString *)URLEncodedStringValue {
|
||||
if (!self.value || [self.value isEqual:[NSNull null]]) {
|
||||
return AFPercentEscapedStringFromString([self.field description]);
|
||||
return SM_AFPercentEscapedStringFromString([self.field description]);
|
||||
} else {
|
||||
return [NSString stringWithFormat:@"%@=%@", AFPercentEscapedStringFromString([self.field description]), AFPercentEscapedStringFromString([self.value description])];
|
||||
return [NSString stringWithFormat:@"%@=%@", SM_AFPercentEscapedStringFromString([self.field description]), SM_AFPercentEscapedStringFromString([self.value description])];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -113,23 +113,23 @@ NSString * AFPercentEscapedStringFromString(NSString *string) {
|
||||
|
||||
#pragma mark -
|
||||
|
||||
FOUNDATION_EXPORT NSArray * AFQueryStringPairsFromDictionary(NSDictionary *dictionary);
|
||||
FOUNDATION_EXPORT NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value);
|
||||
FOUNDATION_EXPORT NSArray * SM_AFQueryStringPairsFromDictionary(NSDictionary *dictionary);
|
||||
FOUNDATION_EXPORT NSArray * SM_AFQueryStringPairsFromKeyAndValue(NSString *key, id value);
|
||||
|
||||
NSString * AFQueryStringFromParameters(NSDictionary *parameters) {
|
||||
NSString * SM_AFQueryStringFromParameters(NSDictionary *parameters) {
|
||||
NSMutableArray *mutablePairs = [NSMutableArray array];
|
||||
for (AFQueryStringPair *pair in AFQueryStringPairsFromDictionary(parameters)) {
|
||||
for (SM_AFQueryStringPair *pair in SM_AFQueryStringPairsFromDictionary(parameters)) {
|
||||
[mutablePairs addObject:[pair URLEncodedStringValue]];
|
||||
}
|
||||
|
||||
return [mutablePairs componentsJoinedByString:@"&"];
|
||||
}
|
||||
|
||||
NSArray * AFQueryStringPairsFromDictionary(NSDictionary *dictionary) {
|
||||
return AFQueryStringPairsFromKeyAndValue(nil, dictionary);
|
||||
NSArray * SM_AFQueryStringPairsFromDictionary(NSDictionary *dictionary) {
|
||||
return SM_AFQueryStringPairsFromKeyAndValue(nil, dictionary);
|
||||
}
|
||||
|
||||
NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value) {
|
||||
NSArray * SM_AFQueryStringPairsFromKeyAndValue(NSString *key, id value) {
|
||||
NSMutableArray *mutableQueryStringComponents = [NSMutableArray array];
|
||||
|
||||
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"description" ascending:YES selector:@selector(compare:)];
|
||||
@@ -140,21 +140,21 @@ NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value) {
|
||||
for (id nestedKey in [dictionary.allKeys sortedArrayUsingDescriptors:@[ sortDescriptor ]]) {
|
||||
id nestedValue = dictionary[nestedKey];
|
||||
if (nestedValue) {
|
||||
[mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue((key ? [NSString stringWithFormat:@"%@[%@]", key, nestedKey] : nestedKey), nestedValue)];
|
||||
[mutableQueryStringComponents addObjectsFromArray:SM_AFQueryStringPairsFromKeyAndValue((key ? [NSString stringWithFormat:@"%@[%@]", key, nestedKey] : nestedKey), nestedValue)];
|
||||
}
|
||||
}
|
||||
} else if ([value isKindOfClass:[NSArray class]]) {
|
||||
NSArray *array = value;
|
||||
for (id nestedValue in array) {
|
||||
[mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue([NSString stringWithFormat:@"%@[]", key], nestedValue)];
|
||||
[mutableQueryStringComponents addObjectsFromArray:SM_AFQueryStringPairsFromKeyAndValue([NSString stringWithFormat:@"%@[]", key], nestedValue)];
|
||||
}
|
||||
} else if ([value isKindOfClass:[NSSet class]]) {
|
||||
NSSet *set = value;
|
||||
for (id obj in [set sortedArrayUsingDescriptors:@[ sortDescriptor ]]) {
|
||||
[mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue(key, obj)];
|
||||
[mutableQueryStringComponents addObjectsFromArray:SM_AFQueryStringPairsFromKeyAndValue(key, obj)];
|
||||
}
|
||||
} else {
|
||||
[mutableQueryStringComponents addObject:[[AFQueryStringPair alloc] initWithField:key value:value]];
|
||||
[mutableQueryStringComponents addObject:[[SM_AFQueryStringPair alloc] initWithField:key value:value]];
|
||||
}
|
||||
|
||||
return mutableQueryStringComponents;
|
||||
@@ -162,7 +162,7 @@ NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value) {
|
||||
|
||||
#pragma mark -
|
||||
|
||||
@interface AFStreamingMultipartFormData : NSObject <AFMultipartFormData>
|
||||
@interface SM_AFStreamingMultipartFormData : NSObject <AFMultipartFormData>
|
||||
- (instancetype)initWithURLRequest:(NSMutableURLRequest *)urlRequest
|
||||
stringEncoding:(NSStringEncoding)encoding;
|
||||
|
||||
@@ -171,26 +171,26 @@ NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value) {
|
||||
|
||||
#pragma mark -
|
||||
|
||||
static NSArray * AFHTTPRequestSerializerObservedKeyPaths() {
|
||||
static NSArray *_AFHTTPRequestSerializerObservedKeyPaths = nil;
|
||||
static NSArray * SM_AFHTTPRequestSerializerObservedKeyPaths() {
|
||||
static NSArray *_SM_AFHTTPRequestSerializerObservedKeyPaths = nil;
|
||||
static dispatch_once_t onceToken;
|
||||
dispatch_once(&onceToken, ^{
|
||||
_AFHTTPRequestSerializerObservedKeyPaths = @[NSStringFromSelector(@selector(allowsCellularAccess)), NSStringFromSelector(@selector(cachePolicy)), NSStringFromSelector(@selector(HTTPShouldHandleCookies)), NSStringFromSelector(@selector(HTTPShouldUsePipelining)), NSStringFromSelector(@selector(networkServiceType)), NSStringFromSelector(@selector(timeoutInterval))];
|
||||
_SM_AFHTTPRequestSerializerObservedKeyPaths = @[NSStringFromSelector(@selector(allowsCellularAccess)), NSStringFromSelector(@selector(cachePolicy)), NSStringFromSelector(@selector(HTTPShouldHandleCookies)), NSStringFromSelector(@selector(HTTPShouldUsePipelining)), NSStringFromSelector(@selector(networkServiceType)), NSStringFromSelector(@selector(timeoutInterval))];
|
||||
});
|
||||
|
||||
return _AFHTTPRequestSerializerObservedKeyPaths;
|
||||
return _SM_AFHTTPRequestSerializerObservedKeyPaths;
|
||||
}
|
||||
|
||||
static void *AFHTTPRequestSerializerObserverContext = &AFHTTPRequestSerializerObserverContext;
|
||||
static void *SM_AFHTTPRequestSerializerObserverContext = &SM_AFHTTPRequestSerializerObserverContext;
|
||||
|
||||
@interface AFHTTPRequestSerializer ()
|
||||
@interface SM_AFHTTPRequestSerializer ()
|
||||
@property (readwrite, nonatomic, strong) NSMutableSet *mutableObservedChangedKeyPaths;
|
||||
@property (readwrite, nonatomic, strong) NSMutableDictionary *mutableHTTPRequestHeaders;
|
||||
@property (readwrite, nonatomic, assign) AFHTTPRequestQueryStringSerializationStyle queryStringSerializationStyle;
|
||||
@property (readwrite, nonatomic, copy) AFQueryStringSerializationBlock queryStringSerialization;
|
||||
@end
|
||||
|
||||
@implementation AFHTTPRequestSerializer
|
||||
@implementation SM_AFHTTPRequestSerializer
|
||||
|
||||
+ (instancetype)serializer {
|
||||
return [[self alloc] init];
|
||||
@@ -239,9 +239,9 @@ static void *AFHTTPRequestSerializerObserverContext = &AFHTTPRequestSerializerOb
|
||||
self.HTTPMethodsEncodingParametersInURI = [NSSet setWithObjects:@"GET", @"HEAD", @"DELETE", nil];
|
||||
|
||||
self.mutableObservedChangedKeyPaths = [NSMutableSet set];
|
||||
for (NSString *keyPath in AFHTTPRequestSerializerObservedKeyPaths()) {
|
||||
for (NSString *keyPath in SM_AFHTTPRequestSerializerObservedKeyPaths()) {
|
||||
if ([self respondsToSelector:NSSelectorFromString(keyPath)]) {
|
||||
[self addObserver:self forKeyPath:keyPath options:NSKeyValueObservingOptionNew context:AFHTTPRequestSerializerObserverContext];
|
||||
[self addObserver:self forKeyPath:keyPath options:NSKeyValueObservingOptionNew context:SM_AFHTTPRequestSerializerObserverContext];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -249,9 +249,9 @@ static void *AFHTTPRequestSerializerObserverContext = &AFHTTPRequestSerializerOb
|
||||
}
|
||||
|
||||
- (void)dealloc {
|
||||
for (NSString *keyPath in AFHTTPRequestSerializerObservedKeyPaths()) {
|
||||
for (NSString *keyPath in SM_AFHTTPRequestSerializerObservedKeyPaths()) {
|
||||
if ([self respondsToSelector:NSSelectorFromString(keyPath)]) {
|
||||
[self removeObserver:self forKeyPath:keyPath context:AFHTTPRequestSerializerObserverContext];
|
||||
[self removeObserver:self forKeyPath:keyPath context:SM_AFHTTPRequestSerializerObserverContext];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -353,7 +353,7 @@ forHTTPHeaderField:(NSString *)field
|
||||
NSMutableURLRequest *mutableRequest = [[NSMutableURLRequest alloc] initWithURL:url];
|
||||
mutableRequest.HTTPMethod = method;
|
||||
|
||||
for (NSString *keyPath in AFHTTPRequestSerializerObservedKeyPaths()) {
|
||||
for (NSString *keyPath in SM_AFHTTPRequestSerializerObservedKeyPaths()) {
|
||||
if ([self.mutableObservedChangedKeyPaths containsObject:keyPath]) {
|
||||
[mutableRequest setValue:[self valueForKeyPath:keyPath] forKey:keyPath];
|
||||
}
|
||||
@@ -375,10 +375,10 @@ forHTTPHeaderField:(NSString *)field
|
||||
|
||||
NSMutableURLRequest *mutableRequest = [self requestWithMethod:method URLString:URLString parameters:nil error:error];
|
||||
|
||||
__block AFStreamingMultipartFormData *formData = [[AFStreamingMultipartFormData alloc] initWithURLRequest:mutableRequest stringEncoding:NSUTF8StringEncoding];
|
||||
__block SM_AFStreamingMultipartFormData *formData = [[SM_AFStreamingMultipartFormData alloc] initWithURLRequest:mutableRequest stringEncoding:NSUTF8StringEncoding];
|
||||
|
||||
if (parameters) {
|
||||
for (AFQueryStringPair *pair in AFQueryStringPairsFromDictionary(parameters)) {
|
||||
for (SM_AFQueryStringPair *pair in SM_AFQueryStringPairsFromDictionary(parameters)) {
|
||||
NSData *data = nil;
|
||||
if ([pair.value isKindOfClass:[NSData class]]) {
|
||||
data = pair.value;
|
||||
@@ -455,7 +455,7 @@ forHTTPHeaderField:(NSString *)field
|
||||
return mutableRequest;
|
||||
}
|
||||
|
||||
#pragma mark - AFURLRequestSerialization
|
||||
#pragma mark - SM_AFURLRequestSerialization
|
||||
|
||||
- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
|
||||
withParameters:(id)parameters
|
||||
@@ -487,7 +487,7 @@ forHTTPHeaderField:(NSString *)field
|
||||
} else {
|
||||
switch (self.queryStringSerializationStyle) {
|
||||
case AFHTTPRequestQueryStringDefaultStyle:
|
||||
query = AFQueryStringFromParameters(parameters);
|
||||
query = SM_AFQueryStringFromParameters(parameters);
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -514,7 +514,7 @@ forHTTPHeaderField:(NSString *)field
|
||||
#pragma mark - NSKeyValueObserving
|
||||
|
||||
+ (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key {
|
||||
if ([AFHTTPRequestSerializerObservedKeyPaths() containsObject:key]) {
|
||||
if ([SM_AFHTTPRequestSerializerObservedKeyPaths() containsObject:key]) {
|
||||
return NO;
|
||||
}
|
||||
|
||||
@@ -526,7 +526,7 @@ forHTTPHeaderField:(NSString *)field
|
||||
change:(NSDictionary *)change
|
||||
context:(void *)context
|
||||
{
|
||||
if (context == AFHTTPRequestSerializerObserverContext) {
|
||||
if (context == SM_AFHTTPRequestSerializerObserverContext) {
|
||||
if ([change[NSKeyValueChangeNewKey] isEqual:[NSNull null]]) {
|
||||
[self.mutableObservedChangedKeyPaths removeObject:keyPath];
|
||||
} else {
|
||||
@@ -561,7 +561,7 @@ forHTTPHeaderField:(NSString *)field
|
||||
#pragma mark - NSCopying
|
||||
|
||||
- (instancetype)copyWithZone:(NSZone *)zone {
|
||||
AFHTTPRequestSerializer *serializer = [[[self class] allocWithZone:zone] init];
|
||||
SM_AFHTTPRequestSerializer *serializer = [[[self class] allocWithZone:zone] init];
|
||||
serializer.mutableHTTPRequestHeaders = [self.mutableHTTPRequestHeaders mutableCopyWithZone:zone];
|
||||
serializer.queryStringSerializationStyle = self.queryStringSerializationStyle;
|
||||
serializer.queryStringSerialization = self.queryStringSerialization;
|
||||
@@ -601,10 +601,10 @@ static inline NSString * AFContentTypeForPathExtension(NSString *extension) {
|
||||
}
|
||||
}
|
||||
|
||||
NSUInteger const kAFUploadStream3GSuggestedPacketSize = 1024 * 16;
|
||||
NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2;
|
||||
NSUInteger const SM_kAFUploadStream3GSuggestedPacketSize = 1024 * 16;
|
||||
NSTimeInterval const SM_kAFUploadStream3GSuggestedDelay = 0.2;
|
||||
|
||||
@interface AFHTTPBodyPart : NSObject
|
||||
@interface SM_AFHTTPBodyPart : NSObject
|
||||
@property (nonatomic, assign) NSStringEncoding stringEncoding;
|
||||
@property (nonatomic, strong) NSDictionary *headers;
|
||||
@property (nonatomic, copy) NSString *boundary;
|
||||
@@ -622,7 +622,7 @@ NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2;
|
||||
maxLength:(NSUInteger)length;
|
||||
@end
|
||||
|
||||
@interface AFMultipartBodyStream : NSInputStream <NSStreamDelegate>
|
||||
@interface SM_AFMultipartBodyStream : NSInputStream <NSStreamDelegate>
|
||||
@property (nonatomic, assign) NSUInteger numberOfBytesInPacket;
|
||||
@property (nonatomic, assign) NSTimeInterval delay;
|
||||
@property (nonatomic, strong) NSInputStream *inputStream;
|
||||
@@ -631,19 +631,19 @@ NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2;
|
||||
|
||||
- (instancetype)initWithStringEncoding:(NSStringEncoding)encoding;
|
||||
- (void)setInitialAndFinalBoundaries;
|
||||
- (void)appendHTTPBodyPart:(AFHTTPBodyPart *)bodyPart;
|
||||
- (void)appendHTTPBodyPart:(SM_AFHTTPBodyPart *)bodyPart;
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
|
||||
@interface AFStreamingMultipartFormData ()
|
||||
@interface SM_AFStreamingMultipartFormData ()
|
||||
@property (readwrite, nonatomic, copy) NSMutableURLRequest *request;
|
||||
@property (readwrite, nonatomic, assign) NSStringEncoding stringEncoding;
|
||||
@property (readwrite, nonatomic, copy) NSString *boundary;
|
||||
@property (readwrite, nonatomic, strong) AFMultipartBodyStream *bodyStream;
|
||||
@property (readwrite, nonatomic, strong) SM_AFMultipartBodyStream *bodyStream;
|
||||
@end
|
||||
|
||||
@implementation AFStreamingMultipartFormData
|
||||
@implementation SM_AFStreamingMultipartFormData
|
||||
|
||||
- (instancetype)initWithURLRequest:(NSMutableURLRequest *)urlRequest
|
||||
stringEncoding:(NSStringEncoding)encoding
|
||||
@@ -656,7 +656,7 @@ NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2;
|
||||
self.request = urlRequest;
|
||||
self.stringEncoding = encoding;
|
||||
self.boundary = AFCreateMultipartFormBoundary();
|
||||
self.bodyStream = [[AFMultipartBodyStream alloc] initWithStringEncoding:encoding];
|
||||
self.bodyStream = [[SM_AFMultipartBodyStream alloc] initWithStringEncoding:encoding];
|
||||
|
||||
return self;
|
||||
}
|
||||
@@ -686,16 +686,16 @@ NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2;
|
||||
NSParameterAssert(mimeType);
|
||||
|
||||
if (![fileURL isFileURL]) {
|
||||
NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey: NSLocalizedStringFromTable(@"Expected URL to be a file URL", @"AFNetworking", nil)};
|
||||
NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey: NSLocalizedStringFromTable(@"Expected URL to be a file URL", @"SM_AFNetworking", nil)};
|
||||
if (error) {
|
||||
*error = [[NSError alloc] initWithDomain:AFURLRequestSerializationErrorDomain code:NSURLErrorBadURL userInfo:userInfo];
|
||||
*error = [[NSError alloc] initWithDomain:SM_AFURLRequestSerializationErrorDomain code:NSURLErrorBadURL userInfo:userInfo];
|
||||
}
|
||||
|
||||
return NO;
|
||||
} else if ([fileURL checkResourceIsReachableAndReturnError:error] == NO) {
|
||||
NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey: NSLocalizedStringFromTable(@"File URL not reachable.", @"AFNetworking", nil)};
|
||||
NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey: NSLocalizedStringFromTable(@"File URL not reachable.", @"SM_AFNetworking", nil)};
|
||||
if (error) {
|
||||
*error = [[NSError alloc] initWithDomain:AFURLRequestSerializationErrorDomain code:NSURLErrorBadURL userInfo:userInfo];
|
||||
*error = [[NSError alloc] initWithDomain:SM_AFURLRequestSerializationErrorDomain code:NSURLErrorBadURL userInfo:userInfo];
|
||||
}
|
||||
|
||||
return NO;
|
||||
@@ -710,7 +710,7 @@ NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2;
|
||||
[mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, fileName] forKey:@"Content-Disposition"];
|
||||
[mutableHeaders setValue:mimeType forKey:@"Content-Type"];
|
||||
|
||||
AFHTTPBodyPart *bodyPart = [[AFHTTPBodyPart alloc] init];
|
||||
SM_AFHTTPBodyPart *bodyPart = [[SM_AFHTTPBodyPart alloc] init];
|
||||
bodyPart.stringEncoding = self.stringEncoding;
|
||||
bodyPart.headers = mutableHeaders;
|
||||
bodyPart.boundary = self.boundary;
|
||||
@@ -735,7 +735,7 @@ NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2;
|
||||
[mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, fileName] forKey:@"Content-Disposition"];
|
||||
[mutableHeaders setValue:mimeType forKey:@"Content-Type"];
|
||||
|
||||
AFHTTPBodyPart *bodyPart = [[AFHTTPBodyPart alloc] init];
|
||||
SM_AFHTTPBodyPart *bodyPart = [[SM_AFHTTPBodyPart alloc] init];
|
||||
bodyPart.stringEncoding = self.stringEncoding;
|
||||
bodyPart.headers = mutableHeaders;
|
||||
bodyPart.boundary = self.boundary;
|
||||
@@ -778,7 +778,7 @@ NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2;
|
||||
{
|
||||
NSParameterAssert(body);
|
||||
|
||||
AFHTTPBodyPart *bodyPart = [[AFHTTPBodyPart alloc] init];
|
||||
SM_AFHTTPBodyPart *bodyPart = [[SM_AFHTTPBodyPart alloc] init];
|
||||
bodyPart.stringEncoding = self.stringEncoding;
|
||||
bodyPart.headers = headers;
|
||||
bodyPart.boundary = self.boundary;
|
||||
@@ -819,16 +819,16 @@ NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2;
|
||||
@property (readwrite, copy) NSError *streamError;
|
||||
@end
|
||||
|
||||
@interface AFMultipartBodyStream () <NSCopying>
|
||||
@interface SM_AFMultipartBodyStream () <NSCopying>
|
||||
@property (readwrite, nonatomic, assign) NSStringEncoding stringEncoding;
|
||||
@property (readwrite, nonatomic, strong) NSMutableArray *HTTPBodyParts;
|
||||
@property (readwrite, nonatomic, strong) NSEnumerator *HTTPBodyPartEnumerator;
|
||||
@property (readwrite, nonatomic, strong) AFHTTPBodyPart *currentHTTPBodyPart;
|
||||
@property (readwrite, nonatomic, strong) SM_AFHTTPBodyPart *currentHTTPBodyPart;
|
||||
@property (readwrite, nonatomic, strong) NSOutputStream *outputStream;
|
||||
@property (readwrite, nonatomic, strong) NSMutableData *buffer;
|
||||
@end
|
||||
|
||||
@implementation AFMultipartBodyStream
|
||||
@implementation SM_AFMultipartBodyStream
|
||||
#if (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000) || (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1100)
|
||||
@synthesize delegate;
|
||||
#endif
|
||||
@@ -850,7 +850,7 @@ NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2;
|
||||
|
||||
- (void)setInitialAndFinalBoundaries {
|
||||
if ([self.HTTPBodyParts count] > 0) {
|
||||
for (AFHTTPBodyPart *bodyPart in self.HTTPBodyParts) {
|
||||
for (SM_AFHTTPBodyPart *bodyPart in self.HTTPBodyParts) {
|
||||
bodyPart.hasInitialBoundary = NO;
|
||||
bodyPart.hasFinalBoundary = NO;
|
||||
}
|
||||
@@ -860,7 +860,7 @@ NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2;
|
||||
}
|
||||
}
|
||||
|
||||
- (void)appendHTTPBodyPart:(AFHTTPBodyPart *)bodyPart {
|
||||
- (void)appendHTTPBodyPart:(SM_AFHTTPBodyPart *)bodyPart {
|
||||
[self.HTTPBodyParts addObject:bodyPart];
|
||||
}
|
||||
|
||||
@@ -950,7 +950,7 @@ NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2;
|
||||
|
||||
- (unsigned long long)contentLength {
|
||||
unsigned long long length = 0;
|
||||
for (AFHTTPBodyPart *bodyPart in self.HTTPBodyParts) {
|
||||
for (SM_AFHTTPBodyPart *bodyPart in self.HTTPBodyParts) {
|
||||
length += [bodyPart contentLength];
|
||||
}
|
||||
|
||||
@@ -976,9 +976,9 @@ NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2;
|
||||
#pragma mark - NSCopying
|
||||
|
||||
- (instancetype)copyWithZone:(NSZone *)zone {
|
||||
AFMultipartBodyStream *bodyStreamCopy = [[[self class] allocWithZone:zone] initWithStringEncoding:self.stringEncoding];
|
||||
SM_AFMultipartBodyStream *bodyStreamCopy = [[[self class] allocWithZone:zone] initWithStringEncoding:self.stringEncoding];
|
||||
|
||||
for (AFHTTPBodyPart *bodyPart in self.HTTPBodyParts) {
|
||||
for (SM_AFHTTPBodyPart *bodyPart in self.HTTPBodyParts) {
|
||||
[bodyStreamCopy appendHTTPBodyPart:[bodyPart copy]];
|
||||
}
|
||||
|
||||
@@ -996,10 +996,10 @@ typedef enum {
|
||||
AFHeaderPhase = 2,
|
||||
AFBodyPhase = 3,
|
||||
AFFinalBoundaryPhase = 4,
|
||||
} AFHTTPBodyPartReadPhase;
|
||||
} SM_AFHTTPBodyPartReadPhase;
|
||||
|
||||
@interface AFHTTPBodyPart () <NSCopying> {
|
||||
AFHTTPBodyPartReadPhase _phase;
|
||||
@interface SM_AFHTTPBodyPart () <NSCopying> {
|
||||
SM_AFHTTPBodyPartReadPhase _phase;
|
||||
NSInputStream *_inputStream;
|
||||
unsigned long long _phaseReadOffset;
|
||||
}
|
||||
@@ -1010,7 +1010,7 @@ typedef enum {
|
||||
maxLength:(NSUInteger)length;
|
||||
@end
|
||||
|
||||
@implementation AFHTTPBodyPart
|
||||
@implementation SM_AFHTTPBodyPart
|
||||
|
||||
- (instancetype)init {
|
||||
self = [super init];
|
||||
@@ -1182,7 +1182,7 @@ typedef enum {
|
||||
#pragma mark - NSCopying
|
||||
|
||||
- (instancetype)copyWithZone:(NSZone *)zone {
|
||||
AFHTTPBodyPart *bodyPart = [[[self class] allocWithZone:zone] init];
|
||||
SM_AFHTTPBodyPart *bodyPart = [[[self class] allocWithZone:zone] init];
|
||||
|
||||
bodyPart.stringEncoding = self.stringEncoding;
|
||||
bodyPart.headers = self.headers;
|
||||
@@ -1197,7 +1197,7 @@ typedef enum {
|
||||
|
||||
#pragma mark -
|
||||
|
||||
@implementation AFJSONRequestSerializer
|
||||
@implementation SM_AFJSONRequestSerializer
|
||||
|
||||
+ (instancetype)serializer {
|
||||
return [self serializerWithWritingOptions:(NSJSONWritingOptions)0];
|
||||
@@ -1205,13 +1205,13 @@ typedef enum {
|
||||
|
||||
+ (instancetype)serializerWithWritingOptions:(NSJSONWritingOptions)writingOptions
|
||||
{
|
||||
AFJSONRequestSerializer *serializer = [[self alloc] init];
|
||||
SM_AFJSONRequestSerializer *serializer = [[self alloc] init];
|
||||
serializer.writingOptions = writingOptions;
|
||||
|
||||
return serializer;
|
||||
}
|
||||
|
||||
#pragma mark - AFURLRequestSerialization
|
||||
#pragma mark - SM_AFURLRequestSerialization
|
||||
|
||||
- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
|
||||
withParameters:(id)parameters
|
||||
@@ -1264,7 +1264,7 @@ typedef enum {
|
||||
#pragma mark - NSCopying
|
||||
|
||||
- (instancetype)copyWithZone:(NSZone *)zone {
|
||||
AFJSONRequestSerializer *serializer = [super copyWithZone:zone];
|
||||
SM_AFJSONRequestSerializer *serializer = [super copyWithZone:zone];
|
||||
serializer.writingOptions = self.writingOptions;
|
||||
|
||||
return serializer;
|
||||
@@ -1274,7 +1274,7 @@ typedef enum {
|
||||
|
||||
#pragma mark -
|
||||
|
||||
@implementation AFPropertyListRequestSerializer
|
||||
@implementation SM_AFPropertyListRequestSerializer
|
||||
|
||||
+ (instancetype)serializer {
|
||||
return [self serializerWithFormat:NSPropertyListXMLFormat_v1_0 writeOptions:0];
|
||||
@@ -1283,7 +1283,7 @@ typedef enum {
|
||||
+ (instancetype)serializerWithFormat:(NSPropertyListFormat)format
|
||||
writeOptions:(NSPropertyListWriteOptions)writeOptions
|
||||
{
|
||||
AFPropertyListRequestSerializer *serializer = [[self alloc] init];
|
||||
SM_AFPropertyListRequestSerializer *serializer = [[self alloc] init];
|
||||
serializer.format = format;
|
||||
serializer.writeOptions = writeOptions;
|
||||
|
||||
@@ -1345,7 +1345,7 @@ typedef enum {
|
||||
#pragma mark - NSCopying
|
||||
|
||||
- (instancetype)copyWithZone:(NSZone *)zone {
|
||||
AFPropertyListRequestSerializer *serializer = [super copyWithZone:zone];
|
||||
SM_AFPropertyListRequestSerializer *serializer = [super copyWithZone:zone];
|
||||
serializer.format = self.format;
|
||||
serializer.writeOptions = self.writeOptions;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// AFURLResponseSerialization.h
|
||||
// SM_AFURLResponseSerialization.h
|
||||
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
@@ -25,11 +25,11 @@
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
/**
|
||||
The `AFURLResponseSerialization` protocol is adopted by an object that decodes data into a more useful object representation, according to details in the server response. Response serializers may additionally perform validation on the incoming response and data.
|
||||
The `SM_AFURLResponseSerialization` protocol is adopted by an object that decodes data into a more useful object representation, according to details in the server response. Response serializers may additionally perform validation on the incoming response and data.
|
||||
|
||||
For example, a JSON response serializer may check for an acceptable status code (`2XX` range) and content type (`application/json`), decoding a valid JSON response into an object.
|
||||
*/
|
||||
@protocol AFURLResponseSerialization <NSObject, NSSecureCoding, NSCopying>
|
||||
@protocol SM_AFURLResponseSerialization <NSObject, NSSecureCoding, NSCopying>
|
||||
|
||||
/**
|
||||
The response object decoded from the data associated with a specified response.
|
||||
@@ -49,11 +49,11 @@ NS_ASSUME_NONNULL_BEGIN
|
||||
#pragma mark -
|
||||
|
||||
/**
|
||||
`AFHTTPResponseSerializer` conforms to the `AFURLRequestSerialization` & `AFURLResponseSerialization` protocols, offering a concrete base implementation of query string / URL form-encoded parameter serialization and default request headers, as well as response status code and content type validation.
|
||||
`SM_AFHTTPResponseSerializer` conforms to the `SM_AFURLRequestSerialization` & `SM_AFURLResponseSerialization` protocols, offering a concrete base implementation of query string / URL form-encoded parameter serialization and default request headers, as well as response status code and content type validation.
|
||||
|
||||
Any request or response serializer dealing with HTTP is encouraged to subclass `AFHTTPResponseSerializer` in order to ensure consistent default behavior.
|
||||
Any request or response serializer dealing with HTTP is encouraged to subclass `SM_AFHTTPResponseSerializer` in order to ensure consistent default behavior.
|
||||
*/
|
||||
@interface AFHTTPResponseSerializer : NSObject <AFURLResponseSerialization>
|
||||
@interface SM_AFHTTPResponseSerializer : NSObject <SM_AFURLResponseSerialization>
|
||||
|
||||
- (instancetype)init;
|
||||
|
||||
@@ -104,15 +104,15 @@ NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
|
||||
/**
|
||||
`AFJSONResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes JSON responses.
|
||||
`SM_AFJSONResponseSerializer` is a subclass of `SM_AFHTTPResponseSerializer` that validates and decodes JSON responses.
|
||||
|
||||
By default, `AFJSONResponseSerializer` accepts the following MIME types, which includes the official standard, `application/json`, as well as other commonly-used types:
|
||||
By default, `SM_AFJSONResponseSerializer` accepts the following MIME types, which includes the official standard, `application/json`, as well as other commonly-used types:
|
||||
|
||||
- `application/json`
|
||||
- `text/json`
|
||||
- `text/javascript`
|
||||
*/
|
||||
@interface AFJSONResponseSerializer : AFHTTPResponseSerializer
|
||||
@interface SM_AFJSONResponseSerializer : SM_AFHTTPResponseSerializer
|
||||
|
||||
- (instancetype)init;
|
||||
|
||||
@@ -138,14 +138,14 @@ NS_ASSUME_NONNULL_BEGIN
|
||||
#pragma mark -
|
||||
|
||||
/**
|
||||
`AFXMLParserResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLParser` objects.
|
||||
`SM_AFXMLParserResponseSerializer` is a subclass of `SM_AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLParser` objects.
|
||||
|
||||
By default, `AFXMLParserResponseSerializer` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types:
|
||||
By default, `SM_AFXMLParserResponseSerializer` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types:
|
||||
|
||||
- `application/xml`
|
||||
- `text/xml`
|
||||
*/
|
||||
@interface AFXMLParserResponseSerializer : AFHTTPResponseSerializer
|
||||
@interface SM_AFXMLParserResponseSerializer : SM_AFHTTPResponseSerializer
|
||||
|
||||
@end
|
||||
|
||||
@@ -154,14 +154,14 @@ NS_ASSUME_NONNULL_BEGIN
|
||||
#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED
|
||||
|
||||
/**
|
||||
`AFXMLDocumentResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLDocument` objects.
|
||||
`AFXMLDocumentResponseSerializer` is a subclass of `SM_AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLDocument` objects.
|
||||
|
||||
By default, `AFXMLDocumentResponseSerializer` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types:
|
||||
|
||||
- `application/xml`
|
||||
- `text/xml`
|
||||
*/
|
||||
@interface AFXMLDocumentResponseSerializer : AFHTTPResponseSerializer
|
||||
@interface AFXMLDocumentResponseSerializer : SM_AFHTTPResponseSerializer
|
||||
|
||||
- (instancetype)init;
|
||||
|
||||
@@ -184,13 +184,13 @@ NS_ASSUME_NONNULL_BEGIN
|
||||
#pragma mark -
|
||||
|
||||
/**
|
||||
`AFPropertyListResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLDocument` objects.
|
||||
`SM_AFPropertyListResponseSerializer` is a subclass of `SM_AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLDocument` objects.
|
||||
|
||||
By default, `AFPropertyListResponseSerializer` accepts the following MIME types:
|
||||
By default, `SM_AFPropertyListResponseSerializer` accepts the following MIME types:
|
||||
|
||||
- `application/x-plist`
|
||||
*/
|
||||
@interface AFPropertyListResponseSerializer : AFHTTPResponseSerializer
|
||||
@interface SM_AFPropertyListResponseSerializer : SM_AFHTTPResponseSerializer
|
||||
|
||||
- (instancetype)init;
|
||||
|
||||
@@ -218,9 +218,9 @@ NS_ASSUME_NONNULL_BEGIN
|
||||
#pragma mark -
|
||||
|
||||
/**
|
||||
`AFImageResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes image responses.
|
||||
`SM_AFImageResponseSerializer` is a subclass of `SM_AFHTTPResponseSerializer` that validates and decodes image responses.
|
||||
|
||||
By default, `AFImageResponseSerializer` accepts the following MIME types, which correspond to the image formats supported by UIImage or NSImage:
|
||||
By default, `SM_AFImageResponseSerializer` accepts the following MIME types, which correspond to the image formats supported by UIImage or NSImage:
|
||||
|
||||
- `image/tiff`
|
||||
- `image/jpeg`
|
||||
@@ -233,7 +233,7 @@ NS_ASSUME_NONNULL_BEGIN
|
||||
- `image/x-xbitmap`
|
||||
- `image/x-win-bitmap`
|
||||
*/
|
||||
@interface AFImageResponseSerializer : AFHTTPResponseSerializer
|
||||
@interface SM_AFImageResponseSerializer : SM_AFHTTPResponseSerializer
|
||||
|
||||
#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH
|
||||
/**
|
||||
@@ -252,21 +252,21 @@ NS_ASSUME_NONNULL_BEGIN
|
||||
#pragma mark -
|
||||
|
||||
/**
|
||||
`AFCompoundSerializer` is a subclass of `AFHTTPResponseSerializer` that delegates the response serialization to the first `AFHTTPResponseSerializer` object that returns an object for `responseObjectForResponse:data:error:`, falling back on the default behavior of `AFHTTPResponseSerializer`. This is useful for supporting multiple potential types and structures of server responses with a single serializer.
|
||||
`AFCompoundSerializer` is a subclass of `SM_AFHTTPResponseSerializer` that delegates the response serialization to the first `SM_AFHTTPResponseSerializer` object that returns an object for `responseObjectForResponse:data:error:`, falling back on the default behavior of `SM_AFHTTPResponseSerializer`. This is useful for supporting multiple potential types and structures of server responses with a single serializer.
|
||||
*/
|
||||
@interface AFCompoundResponseSerializer : AFHTTPResponseSerializer
|
||||
@interface SM_AFCompoundResponseSerializer : SM_AFHTTPResponseSerializer
|
||||
|
||||
/**
|
||||
The component response serializers.
|
||||
*/
|
||||
@property (readonly, nonatomic, copy) NSArray <id<AFURLResponseSerialization>> *responseSerializers;
|
||||
@property (readonly, nonatomic, copy) NSArray <id<SM_AFURLResponseSerialization>> *responseSerializers;
|
||||
|
||||
/**
|
||||
Creates and returns a compound serializer comprised of the specified response serializers.
|
||||
|
||||
@warning Each response serializer specified must be a subclass of `AFHTTPResponseSerializer`, and response to `-validateResponse:data:error:`.
|
||||
@warning Each response serializer specified must be a subclass of `SM_AFHTTPResponseSerializer`, and response to `-validateResponse:data:error:`.
|
||||
*/
|
||||
+ (instancetype)compoundSerializerWithResponseSerializers:(NSArray <id<AFURLResponseSerialization>> *)responseSerializers;
|
||||
+ (instancetype)compoundSerializerWithResponseSerializers:(NSArray <id<SM_AFURLResponseSerialization>> *)responseSerializers;
|
||||
|
||||
@end
|
||||
|
||||
@@ -279,40 +279,40 @@ NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
The following error domain is predefined.
|
||||
|
||||
- `NSString * const AFURLResponseSerializationErrorDomain`
|
||||
- `NSString * const SM_AFURLResponseSerializationErrorDomain`
|
||||
|
||||
### Constants
|
||||
|
||||
`AFURLResponseSerializationErrorDomain`
|
||||
AFURLResponseSerializer errors. Error codes for `AFURLResponseSerializationErrorDomain` correspond to codes in `NSURLErrorDomain`.
|
||||
`SM_AFURLResponseSerializationErrorDomain`
|
||||
AFURLResponseSerializer errors. Error codes for `SM_AFURLResponseSerializationErrorDomain` correspond to codes in `NSURLErrorDomain`.
|
||||
*/
|
||||
FOUNDATION_EXPORT NSString * const AFURLResponseSerializationErrorDomain;
|
||||
FOUNDATION_EXPORT NSString * const SM_AFURLResponseSerializationErrorDomain;
|
||||
|
||||
/**
|
||||
## User info dictionary keys
|
||||
|
||||
These keys may exist in the user info dictionary, in addition to those defined for NSError.
|
||||
|
||||
- `NSString * const AFNetworkingOperationFailingURLResponseErrorKey`
|
||||
- `NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey`
|
||||
- `NSString * const SM_AFNetworkingOperationFailingURLResponseErrorKey`
|
||||
- `NSString * const SM_AFNetworkingOperationFailingURLResponseDataErrorKey`
|
||||
|
||||
### Constants
|
||||
|
||||
`AFNetworkingOperationFailingURLResponseErrorKey`
|
||||
The corresponding value is an `NSURLResponse` containing the response of the operation associated with an error. This key is only present in the `AFURLResponseSerializationErrorDomain`.
|
||||
`SM_AFNetworkingOperationFailingURLResponseErrorKey`
|
||||
The corresponding value is an `NSURLResponse` containing the response of the operation associated with an error. This key is only present in the `SM_AFURLResponseSerializationErrorDomain`.
|
||||
|
||||
`AFNetworkingOperationFailingURLResponseDataErrorKey`
|
||||
The corresponding value is an `NSData` containing the original data of the operation associated with an error. This key is only present in the `AFURLResponseSerializationErrorDomain`.
|
||||
`SM_AFNetworkingOperationFailingURLResponseDataErrorKey`
|
||||
The corresponding value is an `NSData` containing the original data of the operation associated with an error. This key is only present in the `SM_AFURLResponseSerializationErrorDomain`.
|
||||
*/
|
||||
FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLResponseErrorKey;
|
||||
FOUNDATION_EXPORT NSString * const SM_AFNetworkingOperationFailingURLResponseErrorKey;
|
||||
|
||||
FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey;
|
||||
FOUNDATION_EXPORT NSString * const SM_AFNetworkingOperationFailingURLResponseDataErrorKey;
|
||||
|
||||
/**
|
||||
`AFNetworkingOperationFailingURLResponseBodyErrorKey`
|
||||
`SM_AFNetworkingOperationFailingURLResponseBodyErrorKey`
|
||||
The corresponding value is an `NSString` containing the decoded error message.
|
||||
*/
|
||||
|
||||
FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLResponseBodyErrorKey;
|
||||
FOUNDATION_EXPORT NSString * const SM_AFNetworkingOperationFailingURLResponseBodyErrorKey;
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
@@ -1,4 +1,4 @@
|
||||
// AFURLResponseSerialization.m
|
||||
// SM_AFURLResponseSerialization.m
|
||||
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
@@ -19,7 +19,7 @@
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
#import "AFURLResponseSerialization.h"
|
||||
#import "SM_AFURLResponseSerialization.h"
|
||||
|
||||
#import <TargetConditionals.h>
|
||||
|
||||
@@ -31,10 +31,10 @@
|
||||
#import <Cocoa/Cocoa.h>
|
||||
#endif
|
||||
|
||||
NSString * const AFURLResponseSerializationErrorDomain = @"com.alamofire.error.serialization.response";
|
||||
NSString * const AFNetworkingOperationFailingURLResponseErrorKey = @"com.alamofire.serialization.response.error.response";
|
||||
NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey = @"com.alamofire.serialization.response.error.data";
|
||||
NSString * const AFNetworkingOperationFailingURLResponseBodyErrorKey = @"com.alamofire.serialization.response.error.body";
|
||||
NSString * const SM_AFURLResponseSerializationErrorDomain = @"com.alamofire.error.serialization.response";
|
||||
NSString * const SM_AFNetworkingOperationFailingURLResponseErrorKey = @"com.alamofire.serialization.response.error.response";
|
||||
NSString * const SM_AFNetworkingOperationFailingURLResponseDataErrorKey = @"com.alamofire.serialization.response.error.data";
|
||||
NSString * const SM_AFNetworkingOperationFailingURLResponseBodyErrorKey = @"com.alamofire.serialization.response.error.body";
|
||||
|
||||
static NSError * AFErrorWithUnderlyingError(NSError *error, NSError *underlyingError) {
|
||||
if (!error) {
|
||||
@@ -86,7 +86,7 @@ static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingO
|
||||
return JSONObject;
|
||||
}
|
||||
|
||||
@implementation AFHTTPResponseSerializer
|
||||
@implementation SM_AFHTTPResponseSerializer
|
||||
|
||||
+ (instancetype)serializer {
|
||||
return [[self alloc] init];
|
||||
@@ -121,15 +121,15 @@ static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingO
|
||||
|
||||
if ([data length] > 0 && [response URL]) {
|
||||
NSMutableDictionary *mutableUserInfo = [@{
|
||||
NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Request failed: unacceptable content-type: %@", @"AFNetworking", nil), [response MIMEType]],
|
||||
NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Request failed: unacceptable content-type: %@", @"SM_AFNetworking", nil), [response MIMEType]],
|
||||
NSURLErrorFailingURLErrorKey:[response URL],
|
||||
AFNetworkingOperationFailingURLResponseErrorKey: response,
|
||||
SM_AFNetworkingOperationFailingURLResponseErrorKey: response,
|
||||
} mutableCopy];
|
||||
if (data) {
|
||||
mutableUserInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] = data;
|
||||
mutableUserInfo[SM_AFNetworkingOperationFailingURLResponseDataErrorKey] = data;
|
||||
}
|
||||
|
||||
validationError = AFErrorWithUnderlyingError([NSError errorWithDomain:AFURLResponseSerializationErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:mutableUserInfo], validationError);
|
||||
validationError = AFErrorWithUnderlyingError([NSError errorWithDomain:SM_AFURLResponseSerializationErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:mutableUserInfo], validationError);
|
||||
}
|
||||
|
||||
responseIsValid = NO;
|
||||
@@ -137,16 +137,16 @@ static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingO
|
||||
|
||||
if (self.acceptableStatusCodes && ![self.acceptableStatusCodes containsIndex:(NSUInteger)response.statusCode] && [response URL]) {
|
||||
NSMutableDictionary *mutableUserInfo = [@{
|
||||
NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Request failed: %@ (%ld)", @"AFNetworking", nil), [NSHTTPURLResponse localizedStringForStatusCode:response.statusCode], (long)response.statusCode],
|
||||
NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Request failed: %@ (%ld)", @"SM_AFNetworking", nil), [NSHTTPURLResponse localizedStringForStatusCode:response.statusCode], (long)response.statusCode],
|
||||
NSURLErrorFailingURLErrorKey:[response URL],
|
||||
AFNetworkingOperationFailingURLResponseErrorKey: response,
|
||||
SM_AFNetworkingOperationFailingURLResponseErrorKey: response,
|
||||
} mutableCopy];
|
||||
|
||||
if (data) {
|
||||
mutableUserInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] = data;
|
||||
mutableUserInfo[SM_AFNetworkingOperationFailingURLResponseDataErrorKey] = data;
|
||||
}
|
||||
|
||||
validationError = AFErrorWithUnderlyingError([NSError errorWithDomain:AFURLResponseSerializationErrorDomain code:NSURLErrorBadServerResponse userInfo:mutableUserInfo], validationError);
|
||||
validationError = AFErrorWithUnderlyingError([NSError errorWithDomain:SM_AFURLResponseSerializationErrorDomain code:NSURLErrorBadServerResponse userInfo:mutableUserInfo], validationError);
|
||||
|
||||
responseIsValid = NO;
|
||||
}
|
||||
@@ -159,7 +159,7 @@ static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingO
|
||||
return responseIsValid;
|
||||
}
|
||||
|
||||
#pragma mark - AFURLResponseSerialization
|
||||
#pragma mark - SM_AFURLResponseSerialization
|
||||
|
||||
- (id)responseObjectForResponse:(NSURLResponse *)response
|
||||
data:(NSData *)data
|
||||
@@ -196,7 +196,7 @@ static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingO
|
||||
#pragma mark - NSCopying
|
||||
|
||||
- (instancetype)copyWithZone:(NSZone *)zone {
|
||||
AFHTTPResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
|
||||
SM_AFHTTPResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
|
||||
serializer.acceptableStatusCodes = [self.acceptableStatusCodes copyWithZone:zone];
|
||||
serializer.acceptableContentTypes = [self.acceptableContentTypes copyWithZone:zone];
|
||||
|
||||
@@ -207,14 +207,14 @@ static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingO
|
||||
|
||||
#pragma mark -
|
||||
|
||||
@implementation AFJSONResponseSerializer
|
||||
@implementation SM_AFJSONResponseSerializer
|
||||
|
||||
+ (instancetype)serializer {
|
||||
return [self serializerWithReadingOptions:(NSJSONReadingOptions)0];
|
||||
}
|
||||
|
||||
+ (instancetype)serializerWithReadingOptions:(NSJSONReadingOptions)readingOptions {
|
||||
AFJSONResponseSerializer *serializer = [[self alloc] init];
|
||||
SM_AFJSONResponseSerializer *serializer = [[self alloc] init];
|
||||
serializer.readingOptions = readingOptions;
|
||||
|
||||
return serializer;
|
||||
@@ -231,14 +231,14 @@ static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingO
|
||||
return self;
|
||||
}
|
||||
|
||||
#pragma mark - AFURLResponseSerialization
|
||||
#pragma mark - SM_AFURLResponseSerialization
|
||||
|
||||
- (id)responseObjectForResponse:(NSURLResponse *)response
|
||||
data:(NSData *)data
|
||||
error:(NSError *__autoreleasing *)error
|
||||
{
|
||||
if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
|
||||
if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) {
|
||||
if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, SM_AFURLResponseSerializationErrorDomain)) {
|
||||
return nil;
|
||||
}
|
||||
}
|
||||
@@ -289,7 +289,7 @@ static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingO
|
||||
#pragma mark - NSCopying
|
||||
|
||||
- (instancetype)copyWithZone:(NSZone *)zone {
|
||||
AFJSONResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
|
||||
SM_AFJSONResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
|
||||
serializer.readingOptions = self.readingOptions;
|
||||
serializer.removesKeysWithNullValues = self.removesKeysWithNullValues;
|
||||
|
||||
@@ -300,10 +300,10 @@ static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingO
|
||||
|
||||
#pragma mark -
|
||||
|
||||
@implementation AFXMLParserResponseSerializer
|
||||
@implementation SM_AFXMLParserResponseSerializer
|
||||
|
||||
+ (instancetype)serializer {
|
||||
AFXMLParserResponseSerializer *serializer = [[self alloc] init];
|
||||
SM_AFXMLParserResponseSerializer *serializer = [[self alloc] init];
|
||||
|
||||
return serializer;
|
||||
}
|
||||
@@ -319,14 +319,14 @@ static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingO
|
||||
return self;
|
||||
}
|
||||
|
||||
#pragma mark - AFURLResponseSerialization
|
||||
#pragma mark - SM_AFURLResponseSerialization
|
||||
|
||||
- (id)responseObjectForResponse:(NSHTTPURLResponse *)response
|
||||
data:(NSData *)data
|
||||
error:(NSError *__autoreleasing *)error
|
||||
{
|
||||
if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
|
||||
if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) {
|
||||
if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, SM_AFURLResponseSerializationErrorDomain)) {
|
||||
return nil;
|
||||
}
|
||||
}
|
||||
@@ -364,14 +364,14 @@ static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingO
|
||||
return self;
|
||||
}
|
||||
|
||||
#pragma mark - AFURLResponseSerialization
|
||||
#pragma mark - SM_AFURLResponseSerialization
|
||||
|
||||
- (id)responseObjectForResponse:(NSURLResponse *)response
|
||||
data:(NSData *)data
|
||||
error:(NSError *__autoreleasing *)error
|
||||
{
|
||||
if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
|
||||
if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) {
|
||||
if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, SM_AFURLResponseSerializationErrorDomain)) {
|
||||
return nil;
|
||||
}
|
||||
}
|
||||
@@ -420,7 +420,7 @@ static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingO
|
||||
|
||||
#pragma mark -
|
||||
|
||||
@implementation AFPropertyListResponseSerializer
|
||||
@implementation SM_AFPropertyListResponseSerializer
|
||||
|
||||
+ (instancetype)serializer {
|
||||
return [self serializerWithFormat:NSPropertyListXMLFormat_v1_0 readOptions:0];
|
||||
@@ -429,7 +429,7 @@ static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingO
|
||||
+ (instancetype)serializerWithFormat:(NSPropertyListFormat)format
|
||||
readOptions:(NSPropertyListReadOptions)readOptions
|
||||
{
|
||||
AFPropertyListResponseSerializer *serializer = [[self alloc] init];
|
||||
SM_AFPropertyListResponseSerializer *serializer = [[self alloc] init];
|
||||
serializer.format = format;
|
||||
serializer.readOptions = readOptions;
|
||||
|
||||
@@ -447,14 +447,14 @@ static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingO
|
||||
return self;
|
||||
}
|
||||
|
||||
#pragma mark - AFURLResponseSerialization
|
||||
#pragma mark - SM_AFURLResponseSerialization
|
||||
|
||||
- (id)responseObjectForResponse:(NSURLResponse *)response
|
||||
data:(NSData *)data
|
||||
error:(NSError *__autoreleasing *)error
|
||||
{
|
||||
if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
|
||||
if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) {
|
||||
if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, SM_AFURLResponseSerializationErrorDomain)) {
|
||||
return nil;
|
||||
}
|
||||
}
|
||||
@@ -497,7 +497,7 @@ static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingO
|
||||
#pragma mark - NSCopying
|
||||
|
||||
- (instancetype)copyWithZone:(NSZone *)zone {
|
||||
AFPropertyListResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
|
||||
SM_AFPropertyListResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
|
||||
serializer.format = self.format;
|
||||
serializer.readOptions = self.readOptions;
|
||||
|
||||
@@ -512,13 +512,13 @@ static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingO
|
||||
#import <CoreGraphics/CoreGraphics.h>
|
||||
#import <UIKit/UIKit.h>
|
||||
|
||||
@interface UIImage (AFNetworkingSafeImageLoading)
|
||||
@interface UIImage (SM_AFNetworkingSafeImageLoading)
|
||||
+ (UIImage *)af_safeImageWithData:(NSData *)data;
|
||||
@end
|
||||
|
||||
static NSLock* imageLock = nil;
|
||||
|
||||
@implementation UIImage (AFNetworkingSafeImageLoading)
|
||||
@implementation UIImage (SM_AFNetworkingSafeImageLoading)
|
||||
|
||||
+ (UIImage *)af_safeImageWithData:(NSData *)data {
|
||||
UIImage* image = nil;
|
||||
@@ -638,7 +638,7 @@ static UIImage * AFInflatedImageFromResponseWithDataAtScale(NSHTTPURLResponse *r
|
||||
#endif
|
||||
|
||||
|
||||
@implementation AFImageResponseSerializer
|
||||
@implementation SM_AFImageResponseSerializer
|
||||
|
||||
- (instancetype)init {
|
||||
self = [super init];
|
||||
@@ -666,7 +666,7 @@ static UIImage * AFInflatedImageFromResponseWithDataAtScale(NSHTTPURLResponse *r
|
||||
error:(NSError *__autoreleasing *)error
|
||||
{
|
||||
if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
|
||||
if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) {
|
||||
if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, SM_AFURLResponseSerializationErrorDomain)) {
|
||||
return nil;
|
||||
}
|
||||
}
|
||||
@@ -723,7 +723,7 @@ static UIImage * AFInflatedImageFromResponseWithDataAtScale(NSHTTPURLResponse *r
|
||||
#pragma mark - NSCopying
|
||||
|
||||
- (instancetype)copyWithZone:(NSZone *)zone {
|
||||
AFImageResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
|
||||
SM_AFImageResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
|
||||
|
||||
#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH
|
||||
serializer.imageScale = self.imageScale;
|
||||
@@ -737,27 +737,27 @@ static UIImage * AFInflatedImageFromResponseWithDataAtScale(NSHTTPURLResponse *r
|
||||
|
||||
#pragma mark -
|
||||
|
||||
@interface AFCompoundResponseSerializer ()
|
||||
@interface SM_AFCompoundResponseSerializer ()
|
||||
@property (readwrite, nonatomic, copy) NSArray *responseSerializers;
|
||||
@end
|
||||
|
||||
@implementation AFCompoundResponseSerializer
|
||||
@implementation SM_AFCompoundResponseSerializer
|
||||
|
||||
+ (instancetype)compoundSerializerWithResponseSerializers:(NSArray *)responseSerializers {
|
||||
AFCompoundResponseSerializer *serializer = [[self alloc] init];
|
||||
SM_AFCompoundResponseSerializer *serializer = [[self alloc] init];
|
||||
serializer.responseSerializers = responseSerializers;
|
||||
|
||||
return serializer;
|
||||
}
|
||||
|
||||
#pragma mark - AFURLResponseSerialization
|
||||
#pragma mark - SM_AFURLResponseSerialization
|
||||
|
||||
- (id)responseObjectForResponse:(NSURLResponse *)response
|
||||
data:(NSData *)data
|
||||
error:(NSError *__autoreleasing *)error
|
||||
{
|
||||
for (id <AFURLResponseSerialization> serializer in self.responseSerializers) {
|
||||
if (![serializer isKindOfClass:[AFHTTPResponseSerializer class]]) {
|
||||
for (id <SM_AFURLResponseSerialization> serializer in self.responseSerializers) {
|
||||
if (![serializer isKindOfClass:[SM_AFHTTPResponseSerializer class]]) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -797,7 +797,7 @@ static UIImage * AFInflatedImageFromResponseWithDataAtScale(NSHTTPURLResponse *r
|
||||
#pragma mark - NSCopying
|
||||
|
||||
- (instancetype)copyWithZone:(NSZone *)zone {
|
||||
AFCompoundResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
|
||||
SM_AFCompoundResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
|
||||
serializer.responseSerializers = self.responseSerializers;
|
||||
|
||||
return serializer;
|
||||
@@ -1,4 +1,4 @@
|
||||
// AFURLSessionManager.h
|
||||
// SM_AFURLSessionManager.h
|
||||
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
@@ -22,23 +22,23 @@
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
#import "AFURLResponseSerialization.h"
|
||||
#import "AFURLRequestSerialization.h"
|
||||
#import "AFSecurityPolicy.h"
|
||||
#import "SM_AFURLResponseSerialization.h"
|
||||
#import "SM_AFURLRequestSerialization.h"
|
||||
#import "SM_AFSecurityPolicy.h"
|
||||
#if !TARGET_OS_WATCH
|
||||
#import "AFNetworkReachabilityManager.h"
|
||||
#import "SM_AFNetworkReachabilityManager.h"
|
||||
#endif
|
||||
|
||||
/**
|
||||
`AFURLSessionManager` creates and manages an `NSURLSession` object based on a specified `NSURLSessionConfiguration` object, which conforms to `<NSURLSessionTaskDelegate>`, `<NSURLSessionDataDelegate>`, `<NSURLSessionDownloadDelegate>`, and `<NSURLSessionDelegate>`.
|
||||
`SM_AFURLSessionManager` creates and manages an `NSURLSession` object based on a specified `NSURLSessionConfiguration` object, which conforms to `<NSURLSessionTaskDelegate>`, `<NSURLSessionDataDelegate>`, `<NSURLSessionDownloadDelegate>`, and `<NSURLSessionDelegate>`.
|
||||
|
||||
## Subclassing Notes
|
||||
|
||||
This is the base class for `AFHTTPSessionManager`, which adds functionality specific to making HTTP requests. If you are looking to extend `AFURLSessionManager` specifically for HTTP, consider subclassing `AFHTTPSessionManager` instead.
|
||||
This is the base class for `SM_AFHTTPSessionManager`, which adds functionality specific to making HTTP requests. If you are looking to extend `SM_AFURLSessionManager` specifically for HTTP, consider subclassing `SM_AFHTTPSessionManager` instead.
|
||||
|
||||
## NSURLSession & NSURLSessionTask Delegate Methods
|
||||
|
||||
`AFURLSessionManager` implements the following delegate methods:
|
||||
`SM_AFURLSessionManager` implements the following delegate methods:
|
||||
|
||||
### `NSURLSessionDelegate`
|
||||
|
||||
@@ -71,7 +71,7 @@
|
||||
|
||||
## Network Reachability Monitoring
|
||||
|
||||
Network reachability status and change monitoring is available through the `reachabilityManager` property. Applications may choose to monitor network reachability conditions in order to prevent or suspend any outbound requests. See `AFNetworkReachabilityManager` for more details.
|
||||
Network reachability status and change monitoring is available through the `reachabilityManager` property. Applications may choose to monitor network reachability conditions in order to prevent or suspend any outbound requests. See `SM_AFNetworkReachabilityManager` for more details.
|
||||
|
||||
## NSCoding Caveats
|
||||
|
||||
@@ -87,7 +87,7 @@
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@interface AFURLSessionManager : NSObject <NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate, NSSecureCoding, NSCopying>
|
||||
@interface SM_AFURLSessionManager : NSObject <NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate, NSSecureCoding, NSCopying>
|
||||
|
||||
/**
|
||||
The managed session.
|
||||
@@ -100,20 +100,20 @@ NS_ASSUME_NONNULL_BEGIN
|
||||
@property (readonly, nonatomic, strong) NSOperationQueue *operationQueue;
|
||||
|
||||
/**
|
||||
Responses sent from the server in data tasks created with `dataTaskWithRequest:success:failure:` and run using the `GET` / `POST` / et al. convenience methods are automatically validated and serialized by the response serializer. By default, this property is set to an instance of `AFJSONResponseSerializer`.
|
||||
Responses sent from the server in data tasks created with `dataTaskWithRequest:success:failure:` and run using the `GET` / `POST` / et al. convenience methods are automatically validated and serialized by the response serializer. By default, this property is set to an instance of `SM_AFJSONResponseSerializer`.
|
||||
|
||||
@warning `responseSerializer` must not be `nil`.
|
||||
*/
|
||||
@property (nonatomic, strong) id <AFURLResponseSerialization> responseSerializer;
|
||||
@property (nonatomic, strong) id <SM_AFURLResponseSerialization> responseSerializer;
|
||||
|
||||
///-------------------------------
|
||||
/// @name Managing Security Policy
|
||||
///-------------------------------
|
||||
|
||||
/**
|
||||
The security policy used by created session to evaluate server trust for secure connections. `AFURLSessionManager` uses the `defaultPolicy` unless otherwise specified.
|
||||
The security policy used by created session to evaluate server trust for secure connections. `SM_AFURLSessionManager` uses the `defaultPolicy` unless otherwise specified.
|
||||
*/
|
||||
@property (nonatomic, strong) AFSecurityPolicy *securityPolicy;
|
||||
@property (nonatomic, strong) SM_AFSecurityPolicy *securityPolicy;
|
||||
|
||||
#if !TARGET_OS_WATCH
|
||||
///--------------------------------------
|
||||
@@ -121,9 +121,9 @@ NS_ASSUME_NONNULL_BEGIN
|
||||
///--------------------------------------
|
||||
|
||||
/**
|
||||
The network reachability manager. `AFURLSessionManager` uses the `sharedManager` by default.
|
||||
The network reachability manager. `SM_AFURLSessionManager` uses the `sharedManager` by default.
|
||||
*/
|
||||
@property (readwrite, nonatomic, strong) AFNetworkReachabilityManager *reachabilityManager;
|
||||
@property (readwrite, nonatomic, strong) SM_AFNetworkReachabilityManager *reachabilityManager;
|
||||
#endif
|
||||
|
||||
///----------------------------
|
||||
@@ -423,7 +423,7 @@ NS_ASSUME_NONNULL_BEGIN
|
||||
/**
|
||||
Sets a block to be executed when a download task has completed a download, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didFinishDownloadingToURL:`.
|
||||
|
||||
@param block A block object to be executed when a download task has completed. The block returns the URL the download should be moved to, and takes three arguments: the session, the download task, and the temporary location of the downloaded file. If the file manager encounters an error while attempting to move the temporary file to the destination, an `AFURLSessionDownloadTaskDidFailToMoveFileNotification` will be posted, with the download task as its object, and the user info of the error.
|
||||
@param block A block object to be executed when a download task has completed. The block returns the URL the download should be moved to, and takes three arguments: the session, the download task, and the temporary location of the downloaded file. If the file manager encounters an error while attempting to move the temporary file to the destination, an `SM_AFURLSessionDownloadTaskDidFailToMoveFileNotification` will be posted, with the download task as its object, and the user info of the error.
|
||||
*/
|
||||
- (void)setDownloadTaskDidFinishDownloadingBlock:(nullable NSURL * _Nullable (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location))block;
|
||||
|
||||
@@ -450,51 +450,51 @@ NS_ASSUME_NONNULL_BEGIN
|
||||
/**
|
||||
Posted when a task resumes.
|
||||
*/
|
||||
FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidResumeNotification;
|
||||
FOUNDATION_EXPORT NSString * const SM_AFNetworkingTaskDidResumeNotification;
|
||||
|
||||
/**
|
||||
Posted when a task finishes executing. Includes a userInfo dictionary with additional information about the task.
|
||||
*/
|
||||
FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteNotification;
|
||||
FOUNDATION_EXPORT NSString * const SM_AFNetworkingTaskDidCompleteNotification;
|
||||
|
||||
/**
|
||||
Posted when a task suspends its execution.
|
||||
*/
|
||||
FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidSuspendNotification;
|
||||
FOUNDATION_EXPORT NSString * const SM_AFNetworkingTaskDidSuspendNotification;
|
||||
|
||||
/**
|
||||
Posted when a session is invalidated.
|
||||
*/
|
||||
FOUNDATION_EXPORT NSString * const AFURLSessionDidInvalidateNotification;
|
||||
FOUNDATION_EXPORT NSString * const SM_AFURLSessionDidInvalidateNotification;
|
||||
|
||||
/**
|
||||
Posted when a session download task encountered an error when moving the temporary download file to a specified destination.
|
||||
*/
|
||||
FOUNDATION_EXPORT NSString * const AFURLSessionDownloadTaskDidFailToMoveFileNotification;
|
||||
FOUNDATION_EXPORT NSString * const SM_AFURLSessionDownloadTaskDidFailToMoveFileNotification;
|
||||
|
||||
/**
|
||||
The raw response data of the task. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if response data exists for the task.
|
||||
The raw response data of the task. Included in the userInfo dictionary of the `SM_AFNetworkingTaskDidCompleteNotification` if response data exists for the task.
|
||||
*/
|
||||
FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteResponseDataKey;
|
||||
FOUNDATION_EXPORT NSString * const SM_AFNetworkingTaskDidCompleteResponseDataKey;
|
||||
|
||||
/**
|
||||
The serialized response object of the task. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if the response was serialized.
|
||||
The serialized response object of the task. Included in the userInfo dictionary of the `SM_AFNetworkingTaskDidCompleteNotification` if the response was serialized.
|
||||
*/
|
||||
FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteSerializedResponseKey;
|
||||
FOUNDATION_EXPORT NSString * const SM_AFNetworkingTaskDidCompleteSerializedResponseKey;
|
||||
|
||||
/**
|
||||
The response serializer used to serialize the response. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if the task has an associated response serializer.
|
||||
The response serializer used to serialize the response. Included in the userInfo dictionary of the `SM_AFNetworkingTaskDidCompleteNotification` if the task has an associated response serializer.
|
||||
*/
|
||||
FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteResponseSerializerKey;
|
||||
FOUNDATION_EXPORT NSString * const SM_AFNetworkingTaskDidCompleteResponseSerializerKey;
|
||||
|
||||
/**
|
||||
The file path associated with the download task. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if an the response data has been stored directly to disk.
|
||||
The file path associated with the download task. Included in the userInfo dictionary of the `SM_AFNetworkingTaskDidCompleteNotification` if an the response data has been stored directly to disk.
|
||||
*/
|
||||
FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteAssetPathKey;
|
||||
FOUNDATION_EXPORT NSString * const SM_AFNetworkingTaskDidCompleteAssetPathKey;
|
||||
|
||||
/**
|
||||
Any error associated with the task, or the serialization of the response. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if an error exists.
|
||||
Any error associated with the task, or the serialization of the response. Included in the userInfo dictionary of the `SM_AFNetworkingTaskDidCompleteNotification` if an error exists.
|
||||
*/
|
||||
FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteErrorKey;
|
||||
FOUNDATION_EXPORT NSString * const SM_AFNetworkingTaskDidCompleteErrorKey;
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
@@ -1,4 +1,4 @@
|
||||
// AFURLSessionManager.m
|
||||
// SM_AFURLSessionManager.m
|
||||
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
@@ -19,7 +19,7 @@
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
#import "AFURLSessionManager.h"
|
||||
#import "SM_AFURLSessionManager.h"
|
||||
#import <objc/runtime.h>
|
||||
|
||||
#ifndef NSFoundationVersionNumber_iOS_8_0
|
||||
@@ -69,19 +69,19 @@ static dispatch_group_t url_session_manager_completion_group() {
|
||||
return af_url_session_manager_completion_group;
|
||||
}
|
||||
|
||||
NSString * const AFNetworkingTaskDidResumeNotification = @"com.alamofire.networking.task.resume";
|
||||
NSString * const AFNetworkingTaskDidCompleteNotification = @"com.alamofire.networking.task.complete";
|
||||
NSString * const AFNetworkingTaskDidSuspendNotification = @"com.alamofire.networking.task.suspend";
|
||||
NSString * const AFURLSessionDidInvalidateNotification = @"com.alamofire.networking.session.invalidate";
|
||||
NSString * const AFURLSessionDownloadTaskDidFailToMoveFileNotification = @"com.alamofire.networking.session.download.file-manager-error";
|
||||
NSString * const SM_AFNetworkingTaskDidResumeNotification = @"com.alamofire.networking.task.resume";
|
||||
NSString * const SM_AFNetworkingTaskDidCompleteNotification = @"com.alamofire.networking.task.complete";
|
||||
NSString * const SM_AFNetworkingTaskDidSuspendNotification = @"com.alamofire.networking.task.suspend";
|
||||
NSString * const SM_AFURLSessionDidInvalidateNotification = @"com.alamofire.networking.session.invalidate";
|
||||
NSString * const SM_AFURLSessionDownloadTaskDidFailToMoveFileNotification = @"com.alamofire.networking.session.download.file-manager-error";
|
||||
|
||||
NSString * const AFNetworkingTaskDidCompleteSerializedResponseKey = @"com.alamofire.networking.task.complete.serializedresponse";
|
||||
NSString * const AFNetworkingTaskDidCompleteResponseSerializerKey = @"com.alamofire.networking.task.complete.responseserializer";
|
||||
NSString * const AFNetworkingTaskDidCompleteResponseDataKey = @"com.alamofire.networking.complete.finish.responsedata";
|
||||
NSString * const AFNetworkingTaskDidCompleteErrorKey = @"com.alamofire.networking.task.complete.error";
|
||||
NSString * const AFNetworkingTaskDidCompleteAssetPathKey = @"com.alamofire.networking.task.complete.assetpath";
|
||||
NSString * const SM_AFNetworkingTaskDidCompleteSerializedResponseKey = @"com.alamofire.networking.task.complete.serializedresponse";
|
||||
NSString * const SM_AFNetworkingTaskDidCompleteResponseSerializerKey = @"com.alamofire.networking.task.complete.responseserializer";
|
||||
NSString * const SM_AFNetworkingTaskDidCompleteResponseDataKey = @"com.alamofire.networking.complete.finish.responsedata";
|
||||
NSString * const SM_AFNetworkingTaskDidCompleteErrorKey = @"com.alamofire.networking.task.complete.error";
|
||||
NSString * const SM_AFNetworkingTaskDidCompleteAssetPathKey = @"com.alamofire.networking.task.complete.assetpath";
|
||||
|
||||
static NSString * const AFURLSessionManagerLockName = @"com.alamofire.networking.session.manager.lock";
|
||||
static NSString * const SM_AFURLSessionManagerLockName = @"com.alamofire.networking.session.manager.lock";
|
||||
|
||||
static NSUInteger const AFMaximumNumberOfAttemptsToRecreateBackgroundSessionUploadTask = 3;
|
||||
|
||||
@@ -111,8 +111,8 @@ typedef void (^AFURLSessionTaskCompletionHandler)(NSURLResponse *response, id re
|
||||
|
||||
#pragma mark -
|
||||
|
||||
@interface AFURLSessionManagerTaskDelegate : NSObject <NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate>
|
||||
@property (nonatomic, weak) AFURLSessionManager *manager;
|
||||
@interface SM_AFURLSessionManagerTaskDelegate : NSObject <NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate>
|
||||
@property (nonatomic, weak) SM_AFURLSessionManager *manager;
|
||||
@property (nonatomic, strong) NSMutableData *mutableData;
|
||||
@property (nonatomic, strong) NSProgress *uploadProgress;
|
||||
@property (nonatomic, strong) NSProgress *downloadProgress;
|
||||
@@ -123,7 +123,7 @@ typedef void (^AFURLSessionTaskCompletionHandler)(NSURLResponse *response, id re
|
||||
@property (nonatomic, copy) AFURLSessionTaskCompletionHandler completionHandler;
|
||||
@end
|
||||
|
||||
@implementation AFURLSessionManagerTaskDelegate
|
||||
@implementation SM_AFURLSessionManagerTaskDelegate
|
||||
|
||||
- (instancetype)init {
|
||||
self = [super init];
|
||||
@@ -249,12 +249,12 @@ typedef void (^AFURLSessionTaskCompletionHandler)(NSURLResponse *response, id re
|
||||
task:(NSURLSessionTask *)task
|
||||
didCompleteWithError:(NSError *)error
|
||||
{
|
||||
__strong AFURLSessionManager *manager = self.manager;
|
||||
__strong SM_AFURLSessionManager *manager = self.manager;
|
||||
|
||||
__block id responseObject = nil;
|
||||
|
||||
__block NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
|
||||
userInfo[AFNetworkingTaskDidCompleteResponseSerializerKey] = manager.responseSerializer;
|
||||
userInfo[SM_AFNetworkingTaskDidCompleteResponseSerializerKey] = manager.responseSerializer;
|
||||
|
||||
//Performance Improvement from #2672
|
||||
NSData *data = nil;
|
||||
@@ -265,13 +265,13 @@ didCompleteWithError:(NSError *)error
|
||||
}
|
||||
|
||||
if (self.downloadFileURL) {
|
||||
userInfo[AFNetworkingTaskDidCompleteAssetPathKey] = self.downloadFileURL;
|
||||
userInfo[SM_AFNetworkingTaskDidCompleteAssetPathKey] = self.downloadFileURL;
|
||||
} else if (data) {
|
||||
userInfo[AFNetworkingTaskDidCompleteResponseDataKey] = data;
|
||||
userInfo[SM_AFNetworkingTaskDidCompleteResponseDataKey] = data;
|
||||
}
|
||||
|
||||
if (error) {
|
||||
userInfo[AFNetworkingTaskDidCompleteErrorKey] = error;
|
||||
userInfo[SM_AFNetworkingTaskDidCompleteErrorKey] = error;
|
||||
|
||||
dispatch_group_async(manager.completionGroup ?: url_session_manager_completion_group(), manager.completionQueue ?: dispatch_get_main_queue(), ^{
|
||||
if (self.completionHandler) {
|
||||
@@ -279,7 +279,7 @@ didCompleteWithError:(NSError *)error
|
||||
}
|
||||
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidCompleteNotification object:task userInfo:userInfo];
|
||||
[[NSNotificationCenter defaultCenter] postNotificationName:SM_AFNetworkingTaskDidCompleteNotification object:task userInfo:userInfo];
|
||||
});
|
||||
});
|
||||
} else {
|
||||
@@ -292,11 +292,11 @@ didCompleteWithError:(NSError *)error
|
||||
}
|
||||
|
||||
if (responseObject) {
|
||||
userInfo[AFNetworkingTaskDidCompleteSerializedResponseKey] = responseObject;
|
||||
userInfo[SM_AFNetworkingTaskDidCompleteSerializedResponseKey] = responseObject;
|
||||
}
|
||||
|
||||
if (serializationError) {
|
||||
userInfo[AFNetworkingTaskDidCompleteErrorKey] = serializationError;
|
||||
userInfo[SM_AFNetworkingTaskDidCompleteErrorKey] = serializationError;
|
||||
}
|
||||
|
||||
dispatch_group_async(manager.completionGroup ?: url_session_manager_completion_group(), manager.completionQueue ?: dispatch_get_main_queue(), ^{
|
||||
@@ -305,7 +305,7 @@ didCompleteWithError:(NSError *)error
|
||||
}
|
||||
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidCompleteNotification object:task userInfo:userInfo];
|
||||
[[NSNotificationCenter defaultCenter] postNotificationName:SM_AFNetworkingTaskDidCompleteNotification object:task userInfo:userInfo];
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -336,7 +336,7 @@ didFinishDownloadingToURL:(NSURL *)location
|
||||
[[NSFileManager defaultManager] moveItemAtURL:location toURL:self.downloadFileURL error:&fileManagerError];
|
||||
|
||||
if (fileManagerError) {
|
||||
[[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDownloadTaskDidFailToMoveFileNotification object:downloadTask userInfo:fileManagerError.userInfo];
|
||||
[[NSNotificationCenter defaultCenter] postNotificationName:SM_AFURLSessionDownloadTaskDidFailToMoveFileNotification object:downloadTask userInfo:fileManagerError.userInfo];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -368,11 +368,11 @@ static inline BOOL af_addMethod(Class theClass, SEL selector, Method method) {
|
||||
static NSString * const AFNSURLSessionTaskDidResumeNotification = @"com.alamofire.networking.nsurlsessiontask.resume";
|
||||
static NSString * const AFNSURLSessionTaskDidSuspendNotification = @"com.alamofire.networking.nsurlsessiontask.suspend";
|
||||
|
||||
@interface _AFURLSessionTaskSwizzling : NSObject
|
||||
@interface _SM_AFURLSessionTaskSwizzling : NSObject
|
||||
|
||||
@end
|
||||
|
||||
@implementation _AFURLSessionTaskSwizzling
|
||||
@implementation _SM_AFURLSessionTaskSwizzling
|
||||
|
||||
+ (void)load {
|
||||
/**
|
||||
@@ -473,7 +473,7 @@ static NSString * const AFNSURLSessionTaskDidSuspendNotification = @"com.alamofi
|
||||
|
||||
#pragma mark -
|
||||
|
||||
@interface AFURLSessionManager ()
|
||||
@interface SM_AFURLSessionManager ()
|
||||
@property (readwrite, nonatomic, strong) NSURLSessionConfiguration *sessionConfiguration;
|
||||
@property (readwrite, nonatomic, strong) NSOperationQueue *operationQueue;
|
||||
@property (readwrite, nonatomic, strong) NSURLSession *session;
|
||||
@@ -497,7 +497,7 @@ static NSString * const AFNSURLSessionTaskDidSuspendNotification = @"com.alamofi
|
||||
@property (readwrite, nonatomic, copy) AFURLSessionDownloadTaskDidResumeBlock downloadTaskDidResume;
|
||||
@end
|
||||
|
||||
@implementation AFURLSessionManager
|
||||
@implementation SM_AFURLSessionManager
|
||||
|
||||
- (instancetype)init {
|
||||
return [self initWithSessionConfiguration:nil];
|
||||
@@ -511,6 +511,7 @@ static NSString * const AFNSURLSessionTaskDidSuspendNotification = @"com.alamofi
|
||||
|
||||
if (!configuration) {
|
||||
configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
|
||||
configuration.URLCache = nil;
|
||||
}
|
||||
|
||||
self.sessionConfiguration = configuration;
|
||||
@@ -520,18 +521,18 @@ static NSString * const AFNSURLSessionTaskDidSuspendNotification = @"com.alamofi
|
||||
|
||||
self.session = [NSURLSession sessionWithConfiguration:self.sessionConfiguration delegate:self delegateQueue:self.operationQueue];
|
||||
|
||||
self.responseSerializer = [AFJSONResponseSerializer serializer];
|
||||
self.responseSerializer = [SM_AFJSONResponseSerializer serializer];
|
||||
|
||||
self.securityPolicy = [AFSecurityPolicy defaultPolicy];
|
||||
self.securityPolicy = [SM_AFSecurityPolicy defaultPolicy];
|
||||
|
||||
#if !TARGET_OS_WATCH
|
||||
self.reachabilityManager = [AFNetworkReachabilityManager sharedManager];
|
||||
self.reachabilityManager = [SM_AFNetworkReachabilityManager sharedManager];
|
||||
#endif
|
||||
|
||||
self.mutableTaskDelegatesKeyedByTaskIdentifier = [[NSMutableDictionary alloc] init];
|
||||
|
||||
self.lock = [[NSLock alloc] init];
|
||||
self.lock.name = AFURLSessionManagerLockName;
|
||||
self.lock.name = SM_AFURLSessionManagerLockName;
|
||||
|
||||
[self.session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
|
||||
for (NSURLSessionDataTask *task in dataTasks) {
|
||||
@@ -565,7 +566,7 @@ static NSString * const AFNSURLSessionTaskDidSuspendNotification = @"com.alamofi
|
||||
if ([task respondsToSelector:@selector(taskDescription)]) {
|
||||
if ([task.taskDescription isEqualToString:self.taskDescriptionForSessionTasks]) {
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidResumeNotification object:task];
|
||||
[[NSNotificationCenter defaultCenter] postNotificationName:SM_AFNetworkingTaskDidResumeNotification object:task];
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -576,7 +577,7 @@ static NSString * const AFNSURLSessionTaskDidSuspendNotification = @"com.alamofi
|
||||
if ([task respondsToSelector:@selector(taskDescription)]) {
|
||||
if ([task.taskDescription isEqualToString:self.taskDescriptionForSessionTasks]) {
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidSuspendNotification object:task];
|
||||
[[NSNotificationCenter defaultCenter] postNotificationName:SM_AFNetworkingTaskDidSuspendNotification object:task];
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -584,10 +585,10 @@ static NSString * const AFNSURLSessionTaskDidSuspendNotification = @"com.alamofi
|
||||
|
||||
#pragma mark -
|
||||
|
||||
- (AFURLSessionManagerTaskDelegate *)delegateForTask:(NSURLSessionTask *)task {
|
||||
- (SM_AFURLSessionManagerTaskDelegate *)delegateForTask:(NSURLSessionTask *)task {
|
||||
NSParameterAssert(task);
|
||||
|
||||
AFURLSessionManagerTaskDelegate *delegate = nil;
|
||||
SM_AFURLSessionManagerTaskDelegate *delegate = nil;
|
||||
[self.lock lock];
|
||||
delegate = self.mutableTaskDelegatesKeyedByTaskIdentifier[@(task.taskIdentifier)];
|
||||
[self.lock unlock];
|
||||
@@ -595,7 +596,7 @@ static NSString * const AFNSURLSessionTaskDidSuspendNotification = @"com.alamofi
|
||||
return delegate;
|
||||
}
|
||||
|
||||
- (void)setDelegate:(AFURLSessionManagerTaskDelegate *)delegate
|
||||
- (void)setDelegate:(SM_AFURLSessionManagerTaskDelegate *)delegate
|
||||
forTask:(NSURLSessionTask *)task
|
||||
{
|
||||
NSParameterAssert(task);
|
||||
@@ -613,7 +614,7 @@ static NSString * const AFNSURLSessionTaskDidSuspendNotification = @"com.alamofi
|
||||
downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgressBlock
|
||||
completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler
|
||||
{
|
||||
AFURLSessionManagerTaskDelegate *delegate = [[AFURLSessionManagerTaskDelegate alloc] init];
|
||||
SM_AFURLSessionManagerTaskDelegate *delegate = [[SM_AFURLSessionManagerTaskDelegate alloc] init];
|
||||
delegate.manager = self;
|
||||
delegate.completionHandler = completionHandler;
|
||||
|
||||
@@ -628,7 +629,7 @@ static NSString * const AFNSURLSessionTaskDidSuspendNotification = @"com.alamofi
|
||||
progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock
|
||||
completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler
|
||||
{
|
||||
AFURLSessionManagerTaskDelegate *delegate = [[AFURLSessionManagerTaskDelegate alloc] init];
|
||||
SM_AFURLSessionManagerTaskDelegate *delegate = [[SM_AFURLSessionManagerTaskDelegate alloc] init];
|
||||
delegate.manager = self;
|
||||
delegate.completionHandler = completionHandler;
|
||||
|
||||
@@ -644,7 +645,7 @@ static NSString * const AFNSURLSessionTaskDidSuspendNotification = @"com.alamofi
|
||||
destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
|
||||
completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler
|
||||
{
|
||||
AFURLSessionManagerTaskDelegate *delegate = [[AFURLSessionManagerTaskDelegate alloc] init];
|
||||
SM_AFURLSessionManagerTaskDelegate *delegate = [[SM_AFURLSessionManagerTaskDelegate alloc] init];
|
||||
delegate.manager = self;
|
||||
delegate.completionHandler = completionHandler;
|
||||
|
||||
@@ -664,7 +665,7 @@ static NSString * const AFNSURLSessionTaskDidSuspendNotification = @"com.alamofi
|
||||
- (void)removeDelegateForTask:(NSURLSessionTask *)task {
|
||||
NSParameterAssert(task);
|
||||
|
||||
AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:task];
|
||||
SM_AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:task];
|
||||
[self.lock lock];
|
||||
[delegate cleanUpProgressForTask:task];
|
||||
[self removeNotificationObserverForTask:task];
|
||||
@@ -726,7 +727,7 @@ static NSString * const AFNSURLSessionTaskDidSuspendNotification = @"com.alamofi
|
||||
|
||||
#pragma mark -
|
||||
|
||||
- (void)setResponseSerializer:(id <AFURLResponseSerialization>)responseSerializer {
|
||||
- (void)setResponseSerializer:(id <SM_AFURLResponseSerialization>)responseSerializer {
|
||||
NSParameterAssert(responseSerializer);
|
||||
|
||||
_responseSerializer = responseSerializer;
|
||||
@@ -956,7 +957,7 @@ didBecomeInvalidWithError:(NSError *)error
|
||||
self.sessionDidBecomeInvalid(session, error);
|
||||
}
|
||||
|
||||
[[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDidInvalidateNotification object:session];
|
||||
[[NSNotificationCenter defaultCenter] postNotificationName:SM_AFURLSessionDidInvalidateNotification object:session];
|
||||
}
|
||||
|
||||
- (void)URLSession:(NSURLSession *)session
|
||||
@@ -1078,7 +1079,7 @@ totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend
|
||||
task:(NSURLSessionTask *)task
|
||||
didCompleteWithError:(NSError *)error
|
||||
{
|
||||
AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:task];
|
||||
SM_AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:task];
|
||||
|
||||
// delegate may be nil when completing a task in the background
|
||||
if (delegate) {
|
||||
@@ -1114,7 +1115,7 @@ didReceiveResponse:(NSURLResponse *)response
|
||||
dataTask:(NSURLSessionDataTask *)dataTask
|
||||
didBecomeDownloadTask:(NSURLSessionDownloadTask *)downloadTask
|
||||
{
|
||||
AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:dataTask];
|
||||
SM_AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:dataTask];
|
||||
if (delegate) {
|
||||
[self removeDelegateForTask:dataTask];
|
||||
[self setDelegate:delegate forTask:downloadTask];
|
||||
@@ -1130,7 +1131,7 @@ didBecomeDownloadTask:(NSURLSessionDownloadTask *)downloadTask
|
||||
didReceiveData:(NSData *)data
|
||||
{
|
||||
|
||||
AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:dataTask];
|
||||
SM_AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:dataTask];
|
||||
[delegate URLSession:session dataTask:dataTask didReceiveData:data];
|
||||
|
||||
if (self.dataTaskDidReceiveData) {
|
||||
@@ -1168,7 +1169,7 @@ didBecomeDownloadTask:(NSURLSessionDownloadTask *)downloadTask
|
||||
downloadTask:(NSURLSessionDownloadTask *)downloadTask
|
||||
didFinishDownloadingToURL:(NSURL *)location
|
||||
{
|
||||
AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:downloadTask];
|
||||
SM_AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:downloadTask];
|
||||
if (self.downloadTaskDidFinishDownloading) {
|
||||
NSURL *fileURL = self.downloadTaskDidFinishDownloading(session, downloadTask, location);
|
||||
if (fileURL) {
|
||||
@@ -1176,7 +1177,7 @@ didFinishDownloadingToURL:(NSURL *)location
|
||||
NSError *error = nil;
|
||||
[[NSFileManager defaultManager] moveItemAtURL:location toURL:fileURL error:&error];
|
||||
if (error) {
|
||||
[[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDownloadTaskDidFailToMoveFileNotification object:downloadTask userInfo:error.userInfo];
|
||||
[[NSNotificationCenter defaultCenter] postNotificationName:SM_AFURLSessionDownloadTaskDidFailToMoveFileNotification object:downloadTask userInfo:error.userInfo];
|
||||
}
|
||||
|
||||
return;
|
||||
@@ -1,7 +1,7 @@
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "AFURLRequestSerialization.h"
|
||||
#import "SM_AFURLRequestSerialization.h"
|
||||
|
||||
@interface TextRequestSerializer : AFHTTPRequestSerializer
|
||||
@interface TextRequestSerializer : SM_AFHTTPRequestSerializer
|
||||
|
||||
+ (instancetype)serializer;
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
return serializer;
|
||||
}
|
||||
|
||||
#pragma mark - AFURLRequestSerialization
|
||||
#pragma mark - SM_AFURLRequestSerialization
|
||||
|
||||
- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
|
||||
withParameters:(id)parameters
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "AFURLResponseSerialization.h"
|
||||
#import "SM_AFURLResponseSerialization.h"
|
||||
|
||||
@interface TextResponseSerializer : AFHTTPResponseSerializer
|
||||
@interface TextResponseSerializer : SM_AFHTTPResponseSerializer
|
||||
|
||||
+ (instancetype)serializer;
|
||||
|
||||
|
||||
@@ -94,26 +94,26 @@ static BOOL AFErrorOrUnderlyingErrorHasCodeInDomain(NSError *error, NSInteger co
|
||||
if (data && !*decoded) {
|
||||
NSMutableDictionary *mutableUserInfo = [@{
|
||||
NSURLErrorFailingURLErrorKey:[response URL],
|
||||
AFNetworkingOperationFailingURLResponseErrorKey: response,
|
||||
AFNetworkingOperationFailingURLResponseDataErrorKey: data,
|
||||
AFNetworkingOperationFailingURLResponseBodyErrorKey: @"Could not decode response data due to invalid or unknown charset encoding",
|
||||
SM_AFNetworkingOperationFailingURLResponseErrorKey: response,
|
||||
SM_AFNetworkingOperationFailingURLResponseDataErrorKey: data,
|
||||
SM_AFNetworkingOperationFailingURLResponseBodyErrorKey: @"Could not decode response data due to invalid or unknown charset encoding",
|
||||
} mutableCopy];
|
||||
|
||||
validationError = AFErrorWithUnderlyingError([NSError errorWithDomain:AFURLResponseSerializationErrorDomain code:NSURLErrorBadServerResponse userInfo:mutableUserInfo], validationError);
|
||||
validationError = AFErrorWithUnderlyingError([NSError errorWithDomain:SM_AFURLResponseSerializationErrorDomain code:NSURLErrorBadServerResponse userInfo:mutableUserInfo], validationError);
|
||||
responseIsValid = NO;
|
||||
} else if (self.acceptableStatusCodes && ![self.acceptableStatusCodes containsIndex:(NSUInteger)response.statusCode] && [response URL]) {
|
||||
NSMutableDictionary *mutableUserInfo = [@{
|
||||
NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Request failed: %@ (%ld)", @"AFNetworking", nil), [NSHTTPURLResponse localizedStringForStatusCode:response.statusCode], (long)response.statusCode],
|
||||
NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Request failed: %@ (%ld)", @"SM_AFNetworking", nil), [NSHTTPURLResponse localizedStringForStatusCode:response.statusCode], (long)response.statusCode],
|
||||
NSURLErrorFailingURLErrorKey: [response URL],
|
||||
AFNetworkingOperationFailingURLResponseErrorKey: response,
|
||||
SM_AFNetworkingOperationFailingURLResponseErrorKey: response,
|
||||
} mutableCopy];
|
||||
|
||||
if (data) {
|
||||
mutableUserInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] = data;
|
||||
mutableUserInfo[AFNetworkingOperationFailingURLResponseBodyErrorKey] = *decoded;
|
||||
mutableUserInfo[SM_AFNetworkingOperationFailingURLResponseDataErrorKey] = data;
|
||||
mutableUserInfo[SM_AFNetworkingOperationFailingURLResponseBodyErrorKey] = *decoded;
|
||||
}
|
||||
|
||||
validationError = AFErrorWithUnderlyingError([NSError errorWithDomain:AFURLResponseSerializationErrorDomain code:NSURLErrorBadServerResponse userInfo:mutableUserInfo], validationError);
|
||||
validationError = AFErrorWithUnderlyingError([NSError errorWithDomain:SM_AFURLResponseSerializationErrorDomain code:NSURLErrorBadServerResponse userInfo:mutableUserInfo], validationError);
|
||||
responseIsValid = NO;
|
||||
}
|
||||
}
|
||||
@@ -125,7 +125,7 @@ static BOOL AFErrorOrUnderlyingErrorHasCodeInDomain(NSError *error, NSInteger co
|
||||
return responseIsValid;
|
||||
}
|
||||
|
||||
#pragma mark - AFURLResponseSerialization
|
||||
#pragma mark - SM_AFURLResponseSerialization
|
||||
|
||||
- (id)responseObjectForResponse:(NSURLResponse *)response
|
||||
data:(NSData *)data
|
||||
@@ -134,7 +134,7 @@ static BOOL AFErrorOrUnderlyingErrorHasCodeInDomain(NSError *error, NSInteger co
|
||||
NSString* decoded = nil;
|
||||
|
||||
if (![self validateResponse:(NSHTTPURLResponse *)response data:data decoded:&decoded error:error]) {
|
||||
if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) {
|
||||
if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, SM_AFURLResponseSerializationErrorDomain)) {
|
||||
return nil;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
"displayName": "HttpDemo",
|
||||
"version": "1.0.0",
|
||||
"description": "A sample Apache Cordova application that demonstrates advanced HTTP plugin.",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"build": "scripts/build.sh",
|
||||
"test": "npm run build && scripts/test.sh"
|
||||
@@ -11,12 +10,11 @@
|
||||
"author": "Sefa Ilkimen",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"cordova": "10.0.0",
|
||||
"cordova-android": "9.0.0",
|
||||
"cordova-browser": "6.0.0",
|
||||
"cordova-ios": "6.2.0",
|
||||
"cordova-plugin-device": "2.0.3",
|
||||
"cordova-plugin-wkwebview-file-xhr": "3.0.0"
|
||||
"cordova": "12.0.0",
|
||||
"cordova-android": "12.0.1",
|
||||
"cordova-browser": "7.0.0",
|
||||
"cordova-ios": "7.1.1",
|
||||
"cordova-plugin-device": "2.0.3"
|
||||
},
|
||||
"cordova": {
|
||||
"platforms": [
|
||||
@@ -25,11 +23,7 @@
|
||||
"browser"
|
||||
],
|
||||
"plugins": {
|
||||
"cordova-plugin-device": {},
|
||||
"cordova-plugin-wkwebview-file-xhr": {}
|
||||
"cordova-plugin-device": {}
|
||||
}
|
||||
},
|
||||
"devDependencies": {
|
||||
"cordova-plugin-device": "2.0.3"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
/* global hooks, tests */
|
||||
|
||||
const app = {
|
||||
testIndex: -1,
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
/* global cordova, resolveLocalFileSystemURL, should */
|
||||
|
||||
const hooks = {
|
||||
onBeforeEachTest: function (resolve, reject) {
|
||||
cordova.plugin.http.clearCookies();
|
||||
@@ -9,9 +11,7 @@ const hooks = {
|
||||
}
|
||||
|
||||
helpers.setDefaultServerTrustMode(function () {
|
||||
// @TODO: not ready yet
|
||||
// helpers.setNoneClientAuthMode(resolve, reject);
|
||||
resolve();
|
||||
helpers.setNoneClientAuthMode(resolve, reject);
|
||||
}, reject);
|
||||
});
|
||||
}
|
||||
@@ -23,12 +23,16 @@ const helpers = {
|
||||
setPinnedServerTrustMode: function (resolve, reject) { cordova.plugin.http.setServerTrustMode('pinned', resolve, reject); },
|
||||
setNoneClientAuthMode: function (resolve, reject) { cordova.plugin.http.setClientAuthMode('none', resolve, reject); },
|
||||
setBufferClientAuthMode: function (resolve, reject) {
|
||||
helpers.getWithXhr(function (pkcs) {
|
||||
cordova.plugin.http.setClientAuthMode('buffer', {
|
||||
rawPkcs: pkcs,
|
||||
pkcsPassword: 'badssl.com'
|
||||
}, resolve, reject);
|
||||
}, './certificates/badssl-client-cert.pkcs', 'arraybuffer');
|
||||
var path = cordova.file.applicationDirectory + 'www/certificates/badssl-client-cert.pkcs';
|
||||
|
||||
resolveLocalFileSystemURL(path, function(entry) {
|
||||
helpers.readFileEntry(entry, 'buffer', function(pkcs) {
|
||||
cordova.plugin.http.setClientAuthMode('buffer', {
|
||||
rawPkcs: pkcs,
|
||||
pkcsPassword: 'badssl.com'
|
||||
}, resolve, reject);
|
||||
}, reject);
|
||||
}, reject);
|
||||
},
|
||||
setJsonSerializer: function (resolve) { resolve(cordova.plugin.http.setDataSerializer('json')); },
|
||||
setUtf8StringSerializer: function (resolve) { resolve(cordova.plugin.http.setDataSerializer('utf8')); },
|
||||
@@ -37,20 +41,22 @@ const helpers = {
|
||||
setRawSerializer: function (resolve) { resolve(cordova.plugin.http.setDataSerializer('raw')); },
|
||||
disableFollowingRedirect: function (resolve) { resolve(cordova.plugin.http.setFollowRedirect(false)); },
|
||||
enableFollowingRedirect: function (resolve) { resolve(cordova.plugin.http.setFollowRedirect(true)); },
|
||||
getWithXhr: function (done, url, type) {
|
||||
var xhr = new XMLHttpRequest();
|
||||
readFileEntry: function(fileEntry, contentType, onSuccess, onFail) {
|
||||
var reader = new FileReader();
|
||||
|
||||
xhr.addEventListener('load', function () {
|
||||
if (!type || type === 'text') {
|
||||
done(this.responseText);
|
||||
reader.onerror = onFail;
|
||||
|
||||
reader.onloadend = function() {
|
||||
onSuccess(reader.result);
|
||||
};
|
||||
|
||||
fileEntry.file(function(file) {
|
||||
if (contentType === 'buffer') {
|
||||
reader.readAsArrayBuffer(file);
|
||||
} else {
|
||||
done(this.response);
|
||||
reader.readAsText(file);
|
||||
}
|
||||
});
|
||||
|
||||
xhr.responseType = type;
|
||||
xhr.open('GET', url);
|
||||
xhr.send();
|
||||
}, onFail);
|
||||
},
|
||||
writeToFile: function (done, fileName, content) {
|
||||
window.resolveLocalFileSystemURL(cordova.file.cacheDirectory, function (directoryEntry) {
|
||||
@@ -85,12 +91,15 @@ const helpers = {
|
||||
result.type.should.be.equal(expected);
|
||||
},
|
||||
isAbortSupported: function () {
|
||||
if (window.cordova && window.cordova.platformId === 'android') {
|
||||
var version = device.version; // NOTE will throw error if cordova is present without cordova-plugin-device
|
||||
var major = parseInt(/^(\d+)(\.|$)/.exec(version)[1], 10);
|
||||
return isFinite(major) && major >= 6;
|
||||
}
|
||||
return true;
|
||||
// abort is not working reliably; will be documented in known issues
|
||||
return false;
|
||||
|
||||
// if (window.cordova && window.cordova.platformId === 'android') {
|
||||
// var version = device.version; // NOTE will throw error if cordova is present without cordova-plugin-device
|
||||
// var major = parseInt(/^(\d+)(\.|$)/.exec(version)[1], 10);
|
||||
// return isFinite(major) && major >= 6;
|
||||
// }
|
||||
// return true;
|
||||
},
|
||||
getAbortDelay: function () { return 0; },
|
||||
getDemoArrayBuffer: function(size) {
|
||||
@@ -110,7 +119,6 @@ const helpers = {
|
||||
};
|
||||
|
||||
const messageFactory = {
|
||||
handshakeFailed: function() { return 'TLS connection could not be established: javax.net.ssl.SSLHandshakeException: Handshake failed' },
|
||||
sslTrustAnchor: function () { return 'TLS connection could not be established: javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.' },
|
||||
invalidCertificate: function (domain) { return 'The certificate for this server is invalid. You might be connecting to a server that is pretending to be “' + domain + '” which could put your confidential information at risk.' }
|
||||
}
|
||||
@@ -223,7 +231,7 @@ const tests = [
|
||||
},
|
||||
{
|
||||
description: 'should send JSON object correctly (POST)',
|
||||
expected: 'resolved: {"status": 200, "data": "{\\"json\\":\\"test\\": \\"testString\\"}\" ...',
|
||||
expected: 'resolved: {"status": 200, "data": "{\\"json\\":\\"test\\": \\"testString\\"}" ...',
|
||||
before: helpers.setJsonSerializer,
|
||||
func: function (resolve, reject) { cordova.plugin.http.post('http://httpbin.org/anything', { test: 'testString' }, {}, resolve, reject); },
|
||||
validationFunc: function (driver, result) {
|
||||
@@ -233,7 +241,7 @@ const tests = [
|
||||
},
|
||||
{
|
||||
description: 'should send JSON object correctly (PUT)',
|
||||
expected: 'resolved: {"status": 200, "data": "{\\"json\\":\\"test\\": \\"testString\\"}\" ...',
|
||||
expected: 'resolved: {"status": 200, "data": "{\\"json\\":\\"test\\": \\"testString\\"}" ...',
|
||||
before: helpers.setJsonSerializer,
|
||||
func: function (resolve, reject) { cordova.plugin.http.put('http://httpbin.org/anything', { test: 'testString' }, {}, resolve, reject); },
|
||||
validationFunc: function (driver, result) {
|
||||
@@ -243,7 +251,7 @@ const tests = [
|
||||
},
|
||||
{
|
||||
description: 'should send JSON object correctly (PATCH)',
|
||||
expected: 'resolved: {"status": 200, "data": "{\\"json\\":\\"test\\": \\"testString\\"}\" ...',
|
||||
expected: 'resolved: {"status": 200, "data": "{\\"json\\":\\"test\\": \\"testString\\"}" ...',
|
||||
before: helpers.setJsonSerializer,
|
||||
func: function (resolve, reject) { cordova.plugin.http.patch('http://httpbin.org/anything', { test: 'testString' }, {}, resolve, reject); },
|
||||
validationFunc: function (driver, result) {
|
||||
@@ -253,7 +261,7 @@ const tests = [
|
||||
},
|
||||
{
|
||||
description: 'should send JSON array correctly (POST) #26',
|
||||
expected: 'resolved: {"status": 200, "data": "[ 1, 2, 3 ]\" ...',
|
||||
expected: 'resolved: {"status": 200, "data": "[ 1, 2, 3 ]" ...',
|
||||
before: helpers.setJsonSerializer,
|
||||
func: function (resolve, reject) { cordova.plugin.http.post('http://httpbin.org/anything', [1, 2, 3], {}, resolve, reject); },
|
||||
validationFunc: function (driver, result) {
|
||||
@@ -263,7 +271,7 @@ const tests = [
|
||||
},
|
||||
{
|
||||
description: 'should send JSON array correctly (PUT) #26',
|
||||
expected: 'resolved: {"status": 200, "data": "[ 1, 2, 3 ]\" ...',
|
||||
expected: 'resolved: {"status": 200, "data": "[ 1, 2, 3 ]" ...',
|
||||
before: helpers.setJsonSerializer,
|
||||
func: function (resolve, reject) { cordova.plugin.http.put('http://httpbin.org/anything', [1, 2, 3], {}, resolve, reject); },
|
||||
validationFunc: function (driver, result) {
|
||||
@@ -273,7 +281,7 @@ const tests = [
|
||||
},
|
||||
{
|
||||
description: 'should send JSON array correctly (PATCH) #26',
|
||||
expected: 'resolved: {"status": 200, "data": "[ 1, 2, 3 ]\" ...',
|
||||
expected: 'resolved: {"status": 200, "data": "[ 1, 2, 3 ]" ...',
|
||||
before: helpers.setJsonSerializer,
|
||||
func: function (resolve, reject) { cordova.plugin.http.patch('http://httpbin.org/anything', [1, 2, 3], {}, resolve, reject); },
|
||||
validationFunc: function (driver, result) {
|
||||
@@ -284,7 +292,7 @@ const tests = [
|
||||
},
|
||||
{
|
||||
description: 'should send url encoded data correctly (POST) #41',
|
||||
expected: 'resolved: {"status": 200, "data": "{\\"form\\":\\"test\\": \\"testString\\"}\" ...',
|
||||
expected: 'resolved: {"status": 200, "data": "{\\"form\\":\\"test\\": \\"testString\\"}" ...',
|
||||
before: helpers.setUrlEncodedSerializer,
|
||||
func: function (resolve, reject) { cordova.plugin.http.post('http://httpbin.org/anything', { test: 'testString' }, {}, resolve, reject); },
|
||||
validationFunc: function (driver, result) {
|
||||
@@ -294,7 +302,7 @@ const tests = [
|
||||
},
|
||||
{
|
||||
description: 'should send url encoded data correctly (PUT)',
|
||||
expected: 'resolved: {"status": 200, "data": "{\\"form\\":\\"test\\": \\"testString\\"}\" ...',
|
||||
expected: 'resolved: {"status": 200, "data": "{\\"form\\":\\"test\\": \\"testString\\"}" ...',
|
||||
before: helpers.setUrlEncodedSerializer,
|
||||
func: function (resolve, reject) { cordova.plugin.http.put('http://httpbin.org/anything', { test: 'testString' }, {}, resolve, reject); },
|
||||
validationFunc: function (driver, result) {
|
||||
@@ -304,7 +312,7 @@ const tests = [
|
||||
},
|
||||
{
|
||||
description: 'should send url encoded data correctly (PATCH)',
|
||||
expected: 'resolved: {"status": 200, "data": "{\\"form\\":\\"test\\": \\"testString\\"}\" ...',
|
||||
expected: 'resolved: {"status": 200, "data": "{\\"form\\":\\"test\\": \\"testString\\"}" ...',
|
||||
before: helpers.setUrlEncodedSerializer,
|
||||
func: function (resolve, reject) { cordova.plugin.http.patch('http://httpbin.org/anything', { test: 'testString' }, {}, resolve, reject); },
|
||||
validationFunc: function (driver, result) {
|
||||
@@ -314,18 +322,21 @@ const tests = [
|
||||
},
|
||||
{
|
||||
description: 'should resolve correct URL after redirect (GET) #33',
|
||||
expected: 'resolved: {"status": 200, url: "http://httpbin.org/anything", ...',
|
||||
func: function (resolve, reject) { cordova.plugin.http.get('http://httpbingo.org/redirect-to?url=http://httpbin.org/anything', {}, {}, resolve, reject); },
|
||||
expected: 'resolved: {"status": 200, url: "http://httpbingo.org/anything", ...',
|
||||
func: function (resolve, reject) { cordova.plugin.http.get('http://httpbingo.org/redirect-to?url=http://httpbingo.org/anything', {}, {}, resolve, reject); },
|
||||
validationFunc: function (driver, result) {
|
||||
result.type.should.be.equal('resolved');
|
||||
result.data.url.should.be.equal('http://httpbin.org/anything');
|
||||
result.data.url.should.be.equal('http://httpbingo.org/anything');
|
||||
}
|
||||
},
|
||||
{
|
||||
description: 'should not follow 302 redirect when following redirects is disabled',
|
||||
expected: 'rejected: {"status": 302, ...',
|
||||
before: function (resolve, reject) { cordova.plugin.http.setFollowRedirect(false); resolve(); },
|
||||
func: function (resolve, reject) { cordova.plugin.http.get('http://httpbingo.org/redirect-to?url=http://httpbin.org/anything', {}, {}, resolve, reject); },
|
||||
before: function (resolve) {
|
||||
cordova.plugin.http.setFollowRedirect(false);
|
||||
resolve();
|
||||
},
|
||||
func: function (resolve, reject) { cordova.plugin.http.get('http://httpbingo.org/redirect-to?url=http://httpbingo.org/anything', {}, {}, resolve, reject); },
|
||||
validationFunc: function (driver, result) {
|
||||
result.type.should.be.equal('rejected');
|
||||
result.data.status.should.be.equal(302);
|
||||
@@ -339,7 +350,7 @@ const tests = [
|
||||
var targetPath = cordova.file.cacheDirectory + 'test.xml';
|
||||
|
||||
cordova.plugin.http.downloadFile(sourceUrl, {}, {}, targetPath, function (entry) {
|
||||
helpers.getWithXhr(function (content) {
|
||||
helpers.readFileEntry(entry, 'text', function (content) {
|
||||
resolve({
|
||||
sourceUrl: sourceUrl,
|
||||
targetPath: targetPath,
|
||||
@@ -347,7 +358,7 @@ const tests = [
|
||||
name: entry.name,
|
||||
content: content
|
||||
});
|
||||
}, targetPath);
|
||||
}, reject);
|
||||
}, reject);
|
||||
},
|
||||
validationFunc: function (driver, result) {
|
||||
@@ -421,7 +432,7 @@ const tests = [
|
||||
},
|
||||
{
|
||||
description: 'should encode HTTP array params correctly (GET) #45',
|
||||
expected: 'resolved: {"status": 200, "data": "{\\"url\\":\\"http://httpbin.org/get?myArray[]=val1&myArray[]=val2&myArray[]=val3\\"}\" ...',
|
||||
expected: 'resolved: {"status": 200, "data": "{\\"url\\":\\"http://httpbin.org/get?myArray[]=val1&myArray[]=val2&myArray[]=val3\\"}" ...',
|
||||
func: function (resolve, reject) {
|
||||
cordova.plugin.http.get('http://httpbin.org/get', { myArray: ['val1', 'val2', 'val3'], myString: 'testString' }, {}, resolve, reject);
|
||||
},
|
||||
@@ -449,8 +460,9 @@ const tests = [
|
||||
{
|
||||
description: 'should throw an error while setting non-string value as global header #54',
|
||||
expected: 'throwed: "advanced-http: header values must be strings"',
|
||||
func: function (resolve, reject) {
|
||||
func: function (resolve) {
|
||||
cordova.plugin.http.setHeader('myTestHeader', 2);
|
||||
resolve();
|
||||
},
|
||||
validationFunc: function (driver, result) {
|
||||
result.type.should.be.equal('throwed');
|
||||
@@ -489,7 +501,7 @@ const tests = [
|
||||
},
|
||||
{
|
||||
description: 'should not send programmatically set cookies after running "clearCookies" (GET) #59',
|
||||
expected: 'resolved: {"status": 200, "data": "{\"headers\": {\"Cookie\": \"\"...',
|
||||
expected: 'resolved: {"status": 200, "data": "{"headers": {"Cookie": ""...',
|
||||
func: function (resolve, reject) {
|
||||
cordova.plugin.http.setCookie('http://httpbin.org/get', 'myCookie=myValue');
|
||||
cordova.plugin.http.setCookie('http://httpbin.org/get', 'mySecondCookie=mySecondValue');
|
||||
@@ -517,7 +529,7 @@ const tests = [
|
||||
cordova.plugin.http.setCookie('http://httpbin.org/get', 'mySecondCookie=mySecondValue');
|
||||
|
||||
cordova.plugin.http.downloadFile(sourceUrl, {}, {}, targetPath, function (entry) {
|
||||
helpers.getWithXhr(function (content) {
|
||||
helpers.readFileEntry(entry, 'text', function (content) {
|
||||
resolve({
|
||||
sourceUrl: sourceUrl,
|
||||
targetPath: targetPath,
|
||||
@@ -525,7 +537,7 @@ const tests = [
|
||||
name: entry.name,
|
||||
content: content
|
||||
});
|
||||
}, targetPath);
|
||||
}, reject);
|
||||
}, reject);
|
||||
},
|
||||
validationFunc: function (driver, result) {
|
||||
@@ -605,7 +617,9 @@ const tests = [
|
||||
},
|
||||
validationFunc: function (driver, result, targetInfo) {
|
||||
result.type.should.be.equal('rejected');
|
||||
result.data.should.be.eql({ status: -2, error: targetInfo.isAndroid ? messageFactory.sslTrustAnchor() : messageFactory.invalidCertificate('sha512.badssl.com') });
|
||||
result.data.status.should.be.equal(-2);
|
||||
result.data.error.should.include(targetInfo.isAndroid ? 'javax.net.ssl.SSLHandshakeException' : 'The certificate for this server is invalid');
|
||||
// result.data.should.be.eql({ status: -2, error: targetInfo.isAndroid ? messageFactory.s^slTrustAnchor() : messageFactory.invalidCertificate('sha512.badssl.com') });
|
||||
}
|
||||
},
|
||||
{
|
||||
@@ -694,7 +708,7 @@ const tests = [
|
||||
var targetPath = cordova.file.cacheDirectory + 'test.xml';
|
||||
|
||||
cordova.plugin.http.downloadFile(sourceUrl, {}, {}, targetPath, function (entry) {
|
||||
helpers.getWithXhr(function (content) {
|
||||
helpers.readFileEntry(entry, 'text', function (content) {
|
||||
resolve({
|
||||
sourceUrl: sourceUrl,
|
||||
targetPath: targetPath,
|
||||
@@ -702,7 +716,7 @@ const tests = [
|
||||
name: entry.name,
|
||||
content: content
|
||||
});
|
||||
}, targetPath);
|
||||
}, reject);
|
||||
}, reject);
|
||||
},
|
||||
validationFunc: function (driver, result) {
|
||||
@@ -848,14 +862,18 @@ const tests = [
|
||||
before: helpers.setMultipartSerializer,
|
||||
func: function (resolve, reject) {
|
||||
var ponyfills = cordova.plugin.http.ponyfills;
|
||||
helpers.getWithXhr(function (blob) {
|
||||
var formData = new ponyfills.FormData();
|
||||
formData.append('CordovaLogo', blob);
|
||||
var path = cordova.file.applicationDirectory + 'www/res/cordova_logo.png';
|
||||
|
||||
var url = 'https://httpbin.org/anything';
|
||||
var options = { method: 'post', data: formData };
|
||||
cordova.plugin.http.sendRequest(url, options, resolve, reject);
|
||||
}, './res/cordova_logo.png', 'blob');
|
||||
resolveLocalFileSystemURL(path, function(entry) {
|
||||
helpers.readFileEntry(entry, 'buffer', function(buffer) {
|
||||
var formData = new ponyfills.FormData();
|
||||
formData.append('CordovaLogo', new Blob([buffer], { type: 'image/png' }));
|
||||
|
||||
var url = 'https://httpbin.org/anything';
|
||||
var options = { method: 'post', data: formData };
|
||||
cordova.plugin.http.sendRequest(url, options, resolve, reject);
|
||||
}, reject);
|
||||
}, reject);
|
||||
},
|
||||
validationFunc: function (driver, result) {
|
||||
helpers.checkResult(result, 'resolved');
|
||||
@@ -874,9 +892,13 @@ const tests = [
|
||||
expected: 'resolved: {"status":200,"data:application/octet-stream;base64,iVBORw0KGgoAAAANSUhEUg ...',
|
||||
before: helpers.setRawSerializer,
|
||||
func: function (resolve, reject) {
|
||||
helpers.getWithXhr(function (buffer) {
|
||||
cordova.plugin.http.post('http://httpbin.org/anything', buffer, {}, resolve, reject);
|
||||
}, './res/cordova_logo.png', 'arraybuffer');
|
||||
var path = cordova.file.applicationDirectory + 'www/res/cordova_logo.png';
|
||||
|
||||
resolveLocalFileSystemURL(path, function(entry) {
|
||||
helpers.readFileEntry(entry, 'buffer', function(buffer) {
|
||||
cordova.plugin.http.post('http://httpbin.org/anything', buffer, {}, resolve, reject);
|
||||
}, reject);
|
||||
}, reject);
|
||||
},
|
||||
validationFunc: function (driver, result) {
|
||||
helpers.checkResult(result, 'resolved');
|
||||
@@ -995,7 +1017,7 @@ const tests = [
|
||||
},
|
||||
{
|
||||
description: 'should not send any cookies after running "clearCookies" (GET) #248',
|
||||
expected: 'resolved: {"status": 200, "data": "{\"cookies\":{}} ...',
|
||||
expected: 'resolved: {"status": 200, "data": "{"cookies":{}} ...',
|
||||
before: helpers.disableFollowingRedirect,
|
||||
func: function (resolve, reject) {
|
||||
cordova.plugin.http.get('https://httpbin.org/cookies/set?myCookieKey=myCookieValue', {}, {}, function () {
|
||||
@@ -1072,7 +1094,7 @@ const tests = [
|
||||
var targetPath = cordova.file.cacheDirectory + 'test.xml';
|
||||
|
||||
var reqId = cordova.plugin.http.downloadFile(sourceUrl, {}, {}, targetPath, function (entry) {
|
||||
helpers.getWithXhr(function (content) {
|
||||
helpers.readFileEntry(entry, 'text', function(content) {
|
||||
resolve({
|
||||
sourceUrl: sourceUrl,
|
||||
targetPath: targetPath,
|
||||
@@ -1080,7 +1102,7 @@ const tests = [
|
||||
name: entry.name,
|
||||
content: content
|
||||
});
|
||||
}, targetPath);
|
||||
}, reject);
|
||||
}, reject);
|
||||
|
||||
setTimeout(function () {
|
||||
@@ -1160,7 +1182,8 @@ const tests = [
|
||||
},
|
||||
validationFunc: function (driver, result) {
|
||||
result.type.should.be.equal('rejected');
|
||||
result.data.should.be.eql({ status: -2, error: messageFactory.handshakeFailed() });
|
||||
result.data.status.should.be.equal(-2);
|
||||
result.data.error.should.include('UNSUPPORTED_PROTOCOL');
|
||||
}
|
||||
},
|
||||
];
|
||||
|
||||
@@ -60,20 +60,22 @@ const configs = {
|
||||
|
||||
// testing on BrowserStack
|
||||
browserstackIosDevice: {
|
||||
'appium-version': '1.22.0',
|
||||
device: 'iPhone 12',
|
||||
os_version: '14',
|
||||
project: 'HTTP Test App',
|
||||
autoWebview: true,
|
||||
app: 'HttpTestAppAndroid',
|
||||
'browserstack.networkLogs': true
|
||||
app: 'HttpTestAppIos',
|
||||
'browserstack.networkLogs': false
|
||||
},
|
||||
browserstackAndroidDevice: {
|
||||
device: 'Google Nexus 6',
|
||||
os_version: '6.0',
|
||||
'appium-version': '1.22.0',
|
||||
device: 'Samsung Galaxy S22 Ultra',
|
||||
os_version: '12.0',
|
||||
project: 'HTTP Test App',
|
||||
autoWebview: true,
|
||||
app: 'HttpTestAppAndroid',
|
||||
'browserstack.networkLogs': true
|
||||
'browserstack.networkLogs': false
|
||||
}
|
||||
};
|
||||
|
||||
@@ -84,7 +86,7 @@ function getCaps(environment, os, runtime) {
|
||||
caps.name = `cordova-plugin-advanced-http (${os})`;
|
||||
|
||||
return caps;
|
||||
};
|
||||
}
|
||||
|
||||
function capitalize(text) {
|
||||
return text.charAt(0).toUpperCase() + text.slice(1).toLowerCase();
|
||||
|
||||
@@ -98,7 +98,7 @@ async function validateTestIndex(driver, testIndex) {
|
||||
|
||||
async function validateTestTitle(driver, testTitle) {
|
||||
const description = await driver.elementById('descriptionLbl').text();
|
||||
const title = description.match(/\d+:\ (.*)/)[1];
|
||||
const title = description.match(/\d+: (.*)/)[1];
|
||||
|
||||
title.should.be.equal(testTitle, 'Test description is not matching!');
|
||||
}
|
||||
@@ -106,6 +106,7 @@ async function validateTestTitle(driver, testTitle) {
|
||||
async function waitToBeFinished(driver, timeout) {
|
||||
const timeoutTimestamp = Date.now() + timeout;
|
||||
|
||||
// eslint-disable-next-line no-constant-condition
|
||||
while (true) {
|
||||
if (await driver.elementById('statusInput').getValue() === 'finished') {
|
||||
return true;
|
||||
|
||||
@@ -148,12 +148,32 @@ describe('Advanced HTTP public interface', function () {
|
||||
it('configures global timeout value correctly with given valid value', () => {
|
||||
http.setRequestTimeout(10);
|
||||
http.getRequestTimeout().should.equal(10);
|
||||
http.getConnectTimeout().should.equal(10);
|
||||
http.getReadTimeout().should.equal(10);
|
||||
});
|
||||
|
||||
it('throws an Error when you try to configure global timeout with a string', () => {
|
||||
(() => { http.setRequestTimeout('myString'); }).should.throw(messages.INVALID_TIMEOUT_VALUE);
|
||||
});
|
||||
|
||||
it('configures connect timeout value correctly with given valid value', () => {
|
||||
http.setConnectTimeout(10);
|
||||
http.getConnectTimeout().should.equal(10);
|
||||
})
|
||||
|
||||
it('throws an Error when you try to configure connect timeout with a string', () => {
|
||||
(() => { http.setConnectTimeout('myString'); }).should.throw(messages.INVALID_TIMEOUT_VALUE);
|
||||
})
|
||||
|
||||
it('configures read timeout value correctly with given valid value', () => {
|
||||
http.setReadTimeout(10);
|
||||
http.getReadTimeout().should.equal(10);
|
||||
})
|
||||
|
||||
it('throws an Error when you try to configure connect timeout with a string', () => {
|
||||
(() => { http.setReadTimeout('myString'); }).should.throw(messages.INVALID_TIMEOUT_VALUE);
|
||||
})
|
||||
|
||||
it('sets global option for following redirects correctly', () => {
|
||||
http.setFollowRedirect(false);
|
||||
http.getFollowRedirect().should.equal(false);
|
||||
@@ -381,6 +401,8 @@ describe('Common helpers', function () {
|
||||
serializer: 'urlencoded',
|
||||
followRedirect: true,
|
||||
timeout: 60.0,
|
||||
connectTimeout: 30.0,
|
||||
readTimeout: 30.0
|
||||
}
|
||||
|
||||
it('adds missing "followRedirect" option correctly', () => {
|
||||
@@ -514,7 +536,7 @@ describe('Common helpers', function () {
|
||||
null,
|
||||
(response) => {
|
||||
response.status.should.be.equal(errorCodes.POST_PROCESSING_FAILED);
|
||||
response.error.should.include('Unexpected token N in JSON at position 0');
|
||||
response.error.should.include('Unexpected token');
|
||||
}
|
||||
);
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ const BlobMock = require('./Blob.mock');
|
||||
module.exports = class FileMock extends BlobMock {
|
||||
constructor(blob, fileName) {
|
||||
super(blob, { type: blob.type });
|
||||
this._fileName = fileName !== undefined ? fileName : 'blob';
|
||||
this._fileName = fileName !== undefined ? fileName : 'blob';
|
||||
this.__lastModifiedDate = new Date();
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,8 @@ var globalConfigs = {
|
||||
serializer: 'urlencoded',
|
||||
followRedirect: true,
|
||||
timeout: 60.0,
|
||||
connectTimeout: 60.0,
|
||||
readTimeout: 60.0
|
||||
};
|
||||
|
||||
module.exports = globalConfigs;
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
/* global FileSystem */
|
||||
|
||||
module.exports = function init(global, jsUtil, cookieHandler, messages, base64, errorCodes, dependencyValidator, ponyfills) {
|
||||
var validSerializers = ['urlencoded', 'json', 'utf8', 'raw', 'multipart'];
|
||||
var validCertModes = ['default', 'nocheck', 'pinned', 'legacy'];
|
||||
@@ -66,7 +68,7 @@ module.exports = function init(global, jsUtil, cookieHandler, messages, base64,
|
||||
for (var i = 0; i < globalKeys.length; i++) {
|
||||
key = globalKeys[i];
|
||||
|
||||
if (!localHeaders.hasOwnProperty(key)) {
|
||||
if (!Object.prototype.hasOwnProperty.call(localHeaders, key)) {
|
||||
localHeaders[key] = globalHeaders[key];
|
||||
}
|
||||
}
|
||||
@@ -343,7 +345,10 @@ module.exports = function init(global, jsUtil, cookieHandler, messages, base64,
|
||||
|
||||
function injectFileEntryHandler(cb) {
|
||||
return function (response) {
|
||||
cb(createFileEntry(response.file));
|
||||
var fileEntry = createFileEntry(response.file);
|
||||
response.file = fileEntry;
|
||||
response.data = fileEntry;
|
||||
cb(fileEntry, response);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -358,7 +363,7 @@ module.exports = function init(global, jsUtil, cookieHandler, messages, base64,
|
||||
}
|
||||
|
||||
function getMatchingHostHeaders(url, headersList) {
|
||||
var matches = url.match(/^https?\:\/\/([^\/?#]+)(?:[\/?#]|$)/i);
|
||||
var matches = url.match(/^https?:\/\/([^/?#]+)(?:[/?#]|$)/i);
|
||||
var domain = matches && matches[1];
|
||||
|
||||
return headersList[domain] || null;
|
||||
@@ -505,7 +510,9 @@ module.exports = function init(global, jsUtil, cookieHandler, messages, base64,
|
||||
params: checkParamsObject(options.params || {}),
|
||||
responseType: checkResponseType(options.responseType || validResponseTypes[0]),
|
||||
serializer: checkSerializer(options.serializer || globals.serializer),
|
||||
timeout: checkTimeoutValue(options.timeout || globals.timeout),
|
||||
connectTimeout: checkTimeoutValue(options.connectTimeout || globals.connectTimeout),
|
||||
readTimeout: checkTimeoutValue(options.readTimeout || globals.readTimeout),
|
||||
timeout: checkTimeoutValue(options.timeout || globals.timeout)
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
@@ -164,13 +164,15 @@ module.exports = function init(ToughCookie, _) {
|
||||
WebStorageCookieStore.prototype._readStore = function () {
|
||||
var json = this._storage.getItem(this._storeKey);
|
||||
|
||||
if (json !== null) {
|
||||
try {
|
||||
return JSON.parse(json);
|
||||
} catch (e) { }
|
||||
if (json === null) {
|
||||
return {};
|
||||
}
|
||||
|
||||
return {};
|
||||
try {
|
||||
return JSON.parse(json);
|
||||
} catch (e) {
|
||||
return {};
|
||||
}
|
||||
};
|
||||
|
||||
WebStorageCookieStore.prototype._writeStore = function (store) {
|
||||
|
||||
@@ -14,6 +14,12 @@ module.exports = function init(exec, cookieHandler, urlUtil, helpers, globalConf
|
||||
setRequestTimeout: setRequestTimeout,
|
||||
getFollowRedirect: getFollowRedirect,
|
||||
setFollowRedirect: setFollowRedirect,
|
||||
// @Android Only
|
||||
getConnectTimeout: getConnectTimeout,
|
||||
// @Android Only
|
||||
setConnectTimeout: setConnectTimeout,
|
||||
getReadTimeout: getReadTimeout,
|
||||
setReadTimeout: setReadTimeout,
|
||||
setServerTrustMode: setServerTrustMode,
|
||||
setClientAuthMode: setClientAuthMode,
|
||||
sendRequest: sendRequest,
|
||||
@@ -97,6 +103,24 @@ module.exports = function init(exec, cookieHandler, urlUtil, helpers, globalConf
|
||||
|
||||
function setRequestTimeout(timeout) {
|
||||
globalConfigs.timeout = helpers.checkTimeoutValue(timeout);
|
||||
globalConfigs.connectTimeout = helpers.checkTimeoutValue(timeout);
|
||||
globalConfigs.readTimeout = helpers.checkTimeoutValue(timeout);
|
||||
}
|
||||
|
||||
function getConnectTimeout() {
|
||||
return globalConfigs.connectTimeout;
|
||||
}
|
||||
|
||||
function setConnectTimeout(timeout) {
|
||||
globalConfigs.connectTimeout = helpers.checkTimeoutValue(timeout);
|
||||
}
|
||||
|
||||
function getReadTimeout() {
|
||||
return globalConfigs.readTimeout;
|
||||
}
|
||||
|
||||
function setReadTimeout(timeout) {
|
||||
globalConfigs.readTimeout = helpers.checkTimeoutValue(timeout);
|
||||
}
|
||||
|
||||
function getFollowRedirect() {
|
||||
@@ -151,20 +175,20 @@ module.exports = function init(exec, cookieHandler, urlUtil, helpers, globalConf
|
||||
case 'put':
|
||||
case 'patch':
|
||||
helpers.processData(options.data, options.serializer, function (data) {
|
||||
exec(onSuccess, onFail, 'CordovaHttpPlugin', options.method, [url, data, options.serializer, headers, options.timeout, options.followRedirect, options.responseType, reqId]);
|
||||
exec(onSuccess, onFail, 'CordovaHttpPlugin', options.method, [url, data, options.serializer, headers, options.connectTimeout, options.readTimeout, options.followRedirect, options.responseType, reqId]);
|
||||
});
|
||||
break;
|
||||
case 'upload':
|
||||
var fileOptions = helpers.checkUploadFileOptions(options.filePath, options.name);
|
||||
exec(onSuccess, onFail, 'CordovaHttpPlugin', 'uploadFiles', [url, headers, fileOptions.filePaths, fileOptions.names, options.timeout, options.followRedirect, options.responseType, reqId]);
|
||||
exec(onSuccess, onFail, 'CordovaHttpPlugin', 'uploadFiles', [url, headers, fileOptions.filePaths, fileOptions.names, options.connectTimeout, options.readTimeout, options.followRedirect, options.responseType, reqId]);
|
||||
break;
|
||||
case 'download':
|
||||
var filePath = helpers.checkDownloadFilePath(options.filePath);
|
||||
var onDownloadSuccess = helpers.injectCookieHandler(url, helpers.injectFileEntryHandler(success));
|
||||
exec(onDownloadSuccess, onFail, 'CordovaHttpPlugin', 'downloadFile', [url, headers, filePath, options.timeout, options.followRedirect, reqId]);
|
||||
exec(onDownloadSuccess, onFail, 'CordovaHttpPlugin', 'downloadFile', [url, headers, filePath, options.connectTimeout, options.readTimeout, options.followRedirect, reqId]);
|
||||
break;
|
||||
default:
|
||||
exec(onSuccess, onFail, 'CordovaHttpPlugin', options.method, [url, headers, options.timeout, options.followRedirect, options.responseType, reqId]);
|
||||
exec(onSuccess, onFail, 'CordovaHttpPlugin', options.method, [url, headers, options.connectTimeout, options.readTimeout, options.followRedirect, options.responseType, reqId]);
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -173,7 +197,7 @@ module.exports = function init(exec, cookieHandler, urlUtil, helpers, globalConf
|
||||
|
||||
function post(url, data, headers, success, failure) {
|
||||
return publicInterface.sendRequest(url, { method: 'post', data: data, headers: headers }, success, failure);
|
||||
};
|
||||
}
|
||||
|
||||
function put(url, data, headers, success, failure) {
|
||||
return publicInterface.sendRequest(url, { method: 'put', data: data, headers: headers }, success, failure);
|
||||
@@ -185,7 +209,7 @@ module.exports = function init(exec, cookieHandler, urlUtil, helpers, globalConf
|
||||
|
||||
function get(url, params, headers, success, failure) {
|
||||
return publicInterface.sendRequest(url, { method: 'get', params: params, headers: headers }, success, failure);
|
||||
};
|
||||
}
|
||||
|
||||
function del(url, params, headers, success, failure) {
|
||||
return publicInterface.sendRequest(url, { method: 'delete', params: params, headers: headers }, success, failure);
|
||||
@@ -197,7 +221,7 @@ module.exports = function init(exec, cookieHandler, urlUtil, helpers, globalConf
|
||||
|
||||
function options(url, params, headers, success, failure) {
|
||||
return publicInterface.sendRequest(url, { method: 'options', params: params, headers: headers }, success, failure);
|
||||
};
|
||||
}
|
||||
|
||||
function uploadFile(url, params, headers, filePath, name, success, failure) {
|
||||
return publicInterface.sendRequest(url, { method: 'upload', params: params, headers: headers, filePath: filePath, name: name }, success, failure);
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -6,7 +6,7 @@ module.exports = function init(jsUtil) {
|
||||
}
|
||||
|
||||
function parseUrl(url) {
|
||||
var match = url.match(/^(https?\:)\/\/(([^:\/?#]*)(?:\:([0-9]+))?)([\/]{0,1}[^?#]*)(\?[^#]*|)(#.*|)$/);
|
||||
var match = url.match(/^(https?:)\/\/(([^:/?#]*)(?::([0-9]+))?)([/]{0,1}[^?#]*)(\?[^#]*|)(#.*|)$/);
|
||||
|
||||
return match && {
|
||||
protocol: match[1],
|
||||
@@ -42,7 +42,7 @@ module.exports = function init(jsUtil) {
|
||||
var parts = [];
|
||||
|
||||
for (var key in object) {
|
||||
if (!object.hasOwnProperty(key)) {
|
||||
if (!Object.prototype.hasOwnProperty.call(object, key)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user