Compare commits

..

38 Commits

Author SHA1 Message Date
Tobias Becht
4ef17d1af5 fix: handle 'missing' options 2023-02-09 11:48:37 +01:00
Tobias Becht
767f638635 feat: upload file without formdata 2023-02-08 17:25:57 +01:00
Sefa Ilkimen
6fc8a7e06d chore: improve travis build for android 2022-12-29 04:59:16 +01:00
Sefa Ilkimen
00dc85cdac chore: update android build tools for Travis CI build 2022-12-29 04:34:34 +01:00
Sefa Ilkimen
c86874a01a test: fix broken tests due to changes at httpbingo.org 2022-12-29 03:14:10 +01:00
Sefa Ilkimen
86fc3892a4 chore: update GitHub Actions badge 2022-12-29 01:19:40 +01:00
Sefa Ilkimen
b1ad996585 Merge pull request #480 from shaneAPT/master
Update READ.md setCookie with removal message
2022-10-19 11:24:17 +02:00
Shane Tully
1218a57e5f update READ.md setCookie 2022-09-22 21:48:40 +01:00
Sefa Ilkimen
320ed35022 Merge pull request #469 from silkimen/dependabot/npm_and_yarn/async-2.6.4
chore(deps): bump async from 2.6.3 to 2.6.4
2022-09-16 04:42:41 +02:00
dependabot[bot]
845f90d43f chore(deps): bump async from 2.6.3 to 2.6.4
Bumps [async](https://github.com/caolan/async) from 2.6.3 to 2.6.4.
- [Release notes](https://github.com/caolan/async/releases)
- [Changelog](https://github.com/caolan/async/blob/v2.6.4/CHANGELOG.md)
- [Commits](https://github.com/caolan/async/compare/v2.6.3...v2.6.4)

---
updated-dependencies:
- dependency-name: async
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-04-29 02:30:39 +00:00
Sefa Ilkimen
f6c3ea7f66 release v3.3.1 2022-03-31 01:22:23 +02:00
Sefa Ilkimen
d52eb08982 docu: update changelog 2022-03-31 01:16:49 +02:00
Sefa Ilkimen
57c87db5a1 fix: broken network connection check on Android 2022-03-31 01:02:09 +02:00
Sefa Ilkimen
8ea1f3aed6 Merge pull request #427 from moshe5745/master
Add "No connection" error response with status code -6
2022-03-31 00:37:46 +02:00
Sefa Ilkimen
e41684cc79 Merge pull request #459 from spoonconsulting/remove_dup_symbol_base
AFNetworking: Remove Duplicate Symbol Base
2022-03-31 00:11:40 +02:00
Sefa Ilkimen
d393d3ca78 Merge pull request #429 from inited/master
Added support for intermediate certificates on iOS
2022-03-30 23:56:22 +02:00
Sefa Ilkimen
479c644b1d Merge pull request #444 from alexander-gruenewald/patch-1
[Browser] Fixing error propagation in setHeaders
2022-03-30 23:36:36 +02:00
Sefa Ilkimen
bfa446c7fd Merge pull request #461 from dtarnawsky/master
Resolves #441 disable url cache
2022-03-30 23:33:42 +02:00
Sefa Ilkimen
c92f07775b chore: update all dependencies 2022-03-30 23:14:37 +02:00
Sefa Ilkimen
9870dde50a release v3.3.0 2022-03-30 17:37:14 +02:00
Sefa Ilkimen
ed08534cf3 chore: fix broken CI build / test 2022-03-30 16:19:46 +02:00
Sefa Ilkimen
ea15617fae docu: update changelog 2022-03-29 14:39:54 +02:00
Sefa Ilkimen
87c915f7c0 Merge pull request #451 from h4ck-rOOt/download-response-ext
feat: response object on file download
2022-03-29 14:04:05 +02:00
Damian Tarnawsky
1f4ccd37b4 Resolves #441 disable url cache 2022-03-11 06:30:34 -08:00
zafirskthelifehacker
343c536a3b New Line 2022-03-10 10:26:50 +04:00
zafirskthelifehacker
38da25bb75 Reset Package-Lock and Revert Version 2022-03-10 10:26:08 +04:00
zafirskthelifehacker
42175e27ad Remove Spoon Consulting Ltd 2022-03-10 10:16:21 +04:00
Tobias Becht
43b65fa887 docs: extend downloadFile example code 2022-02-01 16:48:10 +01:00
Tobias Becht
48445786b6 chore: review feedback, response object 2022-02-01 16:44:08 +01:00
Tobias Becht
08ec3203e9 feat: response object on file download 2022-02-01 14:56:33 +01:00
Alexander Grünewald
9684c03685 Update cordova-http-plugin.js 2022-01-03 08:00:04 +01:00
YushraJewon
8f3cfb11d0 forking reason in readme 2021-12-17 14:38:46 +04:00
d48512c8df package name 2021-12-16 23:18:11 +04:00
ee2d727c2b rename symbol 2021-12-16 23:09:55 +04:00
0ae3756a74 remove duplicate symbol of afnetworking 2021-12-16 18:49:57 +04:00
Alexander Grünewald
935e7d6ba3 [Browser] Fixing error propagation in setHeaders
If the headers contain certain special characters (€, “, ≠, ∑, †, Ω etc..), calling the setHeaders method will throw an "Value is not a valid ByteString" error which unfortunately is neither propagated to the caller of the http-plugin, nor is the xhr request cancelled in this case.

By wrapping the setHeader-call into a try/catch, and fail the xhr request in case of an error, we make sure the caller of the http-plugin will receive a proper error and the xhr request gets canceled.
2021-11-30 17:04:50 +01:00
Jaroslav Pavlicek
6a9a22f81e Added support for intermediate certificates on iOS 2021-09-14 11:42:01 +02:00
moshe_ch
36d7e1813c Add "No connection" error response with status code -6 2021-08-26 01:04:22 +03:00
31 changed files with 4514 additions and 4903 deletions

View File

@@ -3,63 +3,70 @@ name: Cordova HTTP Plugin CI
on: [push]
env:
nodejs: '10.x'
nodejs: "16.x"
BROWSERSTACK_USERNAME: ${{ secrets.BROWSERSTACK_USERNAME }}
BROWSERSTACK_ACCESS_KEY: ${{ secrets.BROWSERSTACK_ACCESS_KEY }}
jobs:
test-www-interface:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Install Node.js ${{ env.nodejs }}
uses: actions/setup-node@v1
with:
node-version: ${{ env.nodejs }}
- name: Install node modules
run: npm ci
- name: Run WWW interface tests
run: npm run testjs
- uses: actions/checkout@v1
- name: Install Node.js ${{ env.nodejs }}
uses: actions/setup-node@v1
with:
node-version: ${{ env.nodejs }}
- name: Install node modules
run: npm ci
- name: Run WWW interface tests
run: npm run test:js
build-ios:
runs-on: macOS-latest
steps:
- uses: actions/checkout@v1
- name: Install Node.js ${{ env.nodejs }}
uses: actions/setup-node@v1
with:
node-version: ${{ env.nodejs }}
- name: Install node modules
run: npm ci
- name: Update test cert for httpbin.org
run: npm run updatecert
- name: Build test app
run: scripts/build-test-app.sh --ios --emulator
- uses: actions/checkout@v1
- name: Install Node.js ${{ env.nodejs }}
uses: actions/setup-node@v1
with:
node-version: ${{ env.nodejs }}
- name: Install node modules
run: npm ci
- name: Update test cert for httpbin.org
run: npm run update:cert
# need to find a solution for signing iOS App so we can build for device target instead simulator
- name: Build test app
run: scripts/build-test-app.sh --ios --emulator
- name: Upload artifact to BrowserStack
if: env.BROWSERSTACK_USERNAME != ''
run: scripts/upload-browserstack.sh --ios
# need to have an App for device target
# - name: Run e2e tests
# if: env.BROWSERSTACK_USERNAME != ''
# run: scripts/test-app.sh --ios --device
build-android:
runs-on: ubuntu-latest
env:
BROWSERSTACK_USERNAME: ${{ secrets.BROWSERSTACK_USERNAME }}
BROWSERSTACK_ACCESS_KEY: ${{ secrets.BROWSERSTACK_ACCESS_KEY }}
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 ${{ env.nodejs }}
uses: actions/setup-node@v1
with:
node-version: ${{ env.nodejs }}
- name: Install node modules
run: npm ci
- name: Install JDK 1.8
uses: actions/setup-java@v1
with:
java-version: 1.8
- name: Update test cert for httpbin.org
run: npm run update:cert
- name: Add workaround for missing DX files in build-tools 32 (https://stackoverflow.com/a/68430992)
run: ln -s $ANDROID_HOME/build-tools/32.0.0/d8 $ANDROID_HOME/build-tools/32.0.0/dx && ln -s $ANDROID_HOME/build-tools/32.0.0/lib/d8.jar $ANDROID_HOME/build-tools/32.0.0/lib/dx.jar
- name: Build test app
run: scripts/build-test-app.sh --android --device
- name: Upload artifact to BrowserStack
if: env.BROWSERSTACK_USERNAME != ''
run: scripts/upload-browserstack.sh --android
- name: Run e2e tests
if: env.BROWSERSTACK_USERNAME != ''
run: scripts/test-app.sh --android --device

View File

@@ -7,52 +7,49 @@ addons:
matrix:
include:
- name: "iOS Build & Test"
language: objective-c
sudo: false
os: osx
osx_image: xcode12.5
- name: "iOS Build & Test"
language: objective-c
os: osx
osx_image: xcode12.5
before_install:
- export LANG=en_US.UTF-8 &&
nvm use 14
before_install:
- export LANG=en_US.UTF-8 &&
nvm use 14
install:
- npm install
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;
script:
- npm run test:js &&
npm run update:cert &&
scripts/build-test-app.sh --ios --emulator &&
scripts/upload-saucelabs.sh --ios &&
scripts/test-app.sh --ios --emulator;
- name: "Android Build & Test"
language: android
sudo : required
- name: "Android Build & Test"
language: android
android:
components:
- tools
- platform-tools
- build-tools-28.0.3
- android-28
- extra-android-support
- extra-android-m2repository
- extra-google-m2repository
before_cache:
- rm -f $HOME/.gradle/caches/modules-2/modules-2.lock
- rm -rf $HOME/.gradle/caches/*/plugin-resolution/
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
cache:
directories:
- $HOME/.gradle/caches/
- $HOME/.gradle/wrapper/
install:
- npm install
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 "tools" "build-tools;30.0.3" "platforms;android-30" "extras;android;m2repository" "extras;google;m2repository"
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;
install:
- npm install
script:
- npm run test:js &&
npm run update:cert &&
scripts/build-test-app.sh --android --emulator &&
scripts/upload-saucelabs.sh --android &&
scripts/test-app.sh --android --emulator;

View File

@@ -1,5 +1,17 @@
# 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

View File

@@ -5,7 +5,7 @@ Cordova Advanced HTTP
[![downloads/month](https://img.shields.io/npm/dm/cordova-plugin-advanced-http.svg)](https://www.npmjs.com/package/cordova-plugin-advanced-http)
[![Travis Build Status](https://img.shields.io/travis/com/silkimen/cordova-plugin-advanced-http/master?label=Travis%20CI)](https://app.travis-ci.com/silkimen/cordova-plugin-advanced-http)
[![GitHub Build Status](https://img.shields.io/github/workflow/status/silkimen/cordova-plugin-advanced-http/Cordova%20HTTP%20Plugin%20CI/master?label=GitHub%20Actions)](https://github.com/silkimen/cordova-plugin-advanced-http/actions)
[![GitHub Build Status](https://img.shields.io/github/actions/workflow/status/silkimen/cordova-plugin-advanced-http/.github/workflows/ci.yml?branch=master)](https://github.com/silkimen/cordova-plugin-advanced-http/actions)
Cordova / Phonegap plugin for communicating with HTTP servers. Supports iOS, Android and [Browser](#browserSupport).
@@ -163,7 +163,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);
@@ -414,21 +414,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>
@@ -445,12 +456,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){
@@ -512,7 +526,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:
@@ -523,8 +537,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

7316
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,17 +1,17 @@
{
"name": "cordova-plugin-advanced-http",
"version": "3.2.2",
"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",
"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 +58,12 @@
},
"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",
"cordova": "11.0.0",
"mocha": "9.2.2",
"umd-tough-cookie": "3.0.0",
"wd": "1.14.0",
"xml2js": "0.4.23"
}
}

View File

@@ -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.2">
<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
@@ -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"/>

View File

@@ -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;
}
@@ -149,12 +163,17 @@ public class CordovaHttpPlugin extends CordovaPlugin implements Observer {
int readTimeout = args.getInt(5) * 1000;
boolean followRedirect = args.getBoolean(6);
String responseType = args.getString(7);
Integer reqId = args.getInt(8);
JSONObject transmitOptions = args.getJSONObject(8);
Integer reqId = args.getInt(9);
// new file transmission options
String transmitFileType = transmitOptions.getString("transmitFileAs");
boolean submitRaw = transmitFileType.equalsIgnoreCase("BINARY");
CordovaObservableCallbackContext observableCallbackContext = new CordovaObservableCallbackContext(callbackContext, reqId);
CordovaHttpUpload upload = new CordovaHttpUpload(url, headers, filePaths, uploadNames, connectTimeout, readTimeout, followRedirect,
responseType, this.tlsConfiguration, this.cordova.getActivity().getApplicationContext(), observableCallbackContext);
responseType, this.tlsConfiguration, submitRaw, this.cordova.getActivity().getApplicationContext(), observableCallbackContext);
startRequest(reqId, observableCallbackContext, upload);
@@ -249,4 +268,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();
}
}

View File

@@ -25,18 +25,40 @@ class CordovaHttpUpload extends CordovaHttpBase {
private JSONArray uploadNames;
private Context applicationContext;
private boolean submitRaw = false;
public CordovaHttpUpload(String url, JSONObject headers, JSONArray filePaths, JSONArray uploadNames, int connectTimeout, int readTimeout,
boolean followRedirects, String responseType, TLSConfiguration tlsConfiguration,
boolean followRedirects, String responseType, TLSConfiguration tlsConfiguration, boolean submitRaw,
Context applicationContext, CordovaObservableCallbackContext callbackContext) {
super("POST", url, headers, connectTimeout, readTimeout, followRedirects, responseType, tlsConfiguration, callbackContext);
this.filePaths = filePaths;
this.uploadNames = uploadNames;
this.applicationContext = applicationContext;
this.submitRaw = submitRaw;
}
@Override
protected void sendBody(HttpRequest request) throws Exception {
if (this.submitRaw) {
if (this.filePaths.length() != 1) {
throw new IllegalArgumentException("Can only transmit a single file. Multiple files are not supported in this mode.");
}
String filePath = this.filePaths.getString(0);
Uri fileURI = Uri.parse(filePath);
if (ContentResolver.SCHEME_FILE.equals((fileURI.getScheme()))) {
File file = new File(new URI(filePath));
request.send(file);
} else if (ContentResolver.SCHEME_CONTENT.equals(fileURI.getScheme())) {
InputStream inputStream = this.applicationContext.getContentResolver().openInputStream(fileURI);
request.send(inputStream);
}
return;
}
for (int i = 0; i < this.filePaths.length(); ++i) {
String uploadName = this.uploadNames.getString(i);
String filePath = this.filePaths.getString(i);

View File

@@ -237,7 +237,16 @@ function sendRequest(method, withData, opts, success, failure) {
// we can't set connect timeout and read timeout separately on browser platform
xhr.timeout = readTimeout * 1000;
setHeaders(xhr, headers);
try {
setHeaders(xhr, headers);
} catch(error) {
return onFail({
status: -1,
error: error,
url: url,
headers: headers
});
}
xhr.onerror = function () {
return onFail(createXhrFailureObject(xhr));

View File

@@ -1,7 +1,7 @@
#import <Foundation/Foundation.h>
#import "SM_AFURLRequestSerialization.h"
@interface BinaryRequestSerializer : AFHTTPRequestSerializer
@interface BinaryRequestSerializer : SM_AFHTTPRequestSerializer
+ (instancetype)serializer;

View File

@@ -1,7 +1,7 @@
#import <Foundation/Foundation.h>
#import "SM_AFURLResponseSerialization.h"
@interface BinaryResponseSerializer : AFHTTPResponseSerializer
@interface BinaryResponseSerializer : SM_AFHTTPResponseSerializer
+ (instancetype)serializer;

View File

@@ -42,13 +42,13 @@
- (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];
}
}
@@ -404,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];
@@ -450,50 +460,30 @@
NSDictionary *headers = [command.arguments objectAtIndex:1];
NSArray *filePaths = [command.arguments objectAtIndex: 2];
NSArray *names = [command.arguments objectAtIndex: 3];
NSTimeInterval connectTimeout = [[command.arguments objectAtIndex:4] doubleValue];
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 setTimeout:readTimeout forManager:manager];
[self setRedirect:followRedirect forManager:manager];
[self setResponseSerializer:responseType forManager:manager];
NSDictionary *transmitOptions = [command.arguments objectAtIndex:8];
NSNumber *reqId = [command.arguments objectAtIndex:9];
NSString *transmitFileType = [transmitOptions objectForKey:@"transmitFileAs"];
CordovaHttpPlugin* __weak weakSelf = self;
[[SDNetworkActivityIndicator sharedActivityIndicator] startActivity];
@try {
NSURLSessionDataTask *task = [manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
NSError *error;
for (int i = 0; i < [filePaths count]; i++) {
NSString *filePath = (NSString *) [filePaths objectAtIndex:i];
NSString *uploadName = (NSString *) [names objectAtIndex:i];
NSURL *fileURL = [NSURL URLWithString: filePath];
[formData appendPartWithFileURL:fileURL name:uploadName error:&error];
}
if (error) {
[weakSelf removeRequest:reqId];
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
[dictionary setObject:[NSNumber numberWithInt:500] forKey:@"status"];
[dictionary setObject:@"Could not add file to post body." forKey:@"error"];
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:dictionary];
[weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
[[SDNetworkActivityIndicator sharedActivityIndicator] stopActivity];
return;
}
} progress:nil success:^(NSURLSessionTask *task, id responseObject) {
[weakSelf removeRequest:reqId];
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
[self handleSuccess:dictionary withResponse:(NSHTTPURLResponse*)task.response andData:responseObject];
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:dictionary];
[weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
[[SDNetworkActivityIndicator sharedActivityIndicator] stopActivity];
} failure:^(NSURLSessionTask *task, NSError *error) {
@try
{
NSURLSessionDataTask* task;
void (^setupManager)(void) = ^() {
[self setRequestHeaders: headers forManager: manager];
[self setTimeout:readTimeout forManager:manager];
[self setRedirect:followRedirect forManager:manager];
[self setResponseSerializer:responseType forManager:manager];
};
void (^onFailure)(NSURLSessionTask *, NSError *) = ^(NSURLSessionTask *task, NSError *error) {
[weakSelf removeRequest:reqId];
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
@@ -502,10 +492,95 @@
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:dictionary];
[weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
[[SDNetworkActivityIndicator sharedActivityIndicator] stopActivity];
}];
[manager invalidateSessionCancelingTasks:YES];
};
void (^onSuccess)(NSURLSessionTask *, id) = ^(NSURLSessionTask *task, id responseObject) {
[weakSelf removeRequest:reqId];
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
[self handleSuccess:dictionary withResponse:(NSHTTPURLResponse*)task.response andData:responseObject];
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:dictionary];
[weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
[[SDNetworkActivityIndicator sharedActivityIndicator] stopActivity];
[manager invalidateSessionCancelingTasks:YES];
};
bool submitRaw = [transmitFileType isEqualToString:@"BINARY"];
// RAW
if (submitRaw)
{
if ([filePaths count] == 1)
{
// setup the request serializer to submit the raw file content
manager.requestSerializer = [BinaryRequestSerializer serializer];
setupManager();
NSURL *fileURL = [NSURL URLWithString:[filePaths objectAtIndex:0]];
NSError *error;
NSData *fileData = [NSData dataWithContentsOfURL:fileURL options:0 error:&error];
if (error)
{
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
[self handleError:dictionary withResponse:nil error:error];
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:dictionary];
[weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
[[SDNetworkActivityIndicator sharedActivityIndicator] stopActivity];
[manager invalidateSessionCancelingTasks:YES];
return;
}
task = [manager uploadTaskWithHTTPMethod:@"POST" URLString:url parameters:fileData progress:nil success:onSuccess failure:onFailure];
}
else
{
[NSException raise:@"ArgumentException" format:@"Can only transmit a single file. Multiple files are not supported in this mode."];
}
}
else // FALLBACK: Multipart / FormData
{
setupManager();
task = [manager
POST:url
parameters:nil
constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
NSError *error;
for (int i = 0; i < [filePaths count]; i++)
{
NSString *filePath = (NSString *) [filePaths objectAtIndex:i];
NSString *uploadName = (NSString *) [names objectAtIndex:i];
NSURL *fileURL = [NSURL URLWithString: filePath];
[formData appendPartWithFileURL:fileURL name:uploadName error:&error];
}
if (error)
{
[weakSelf removeRequest:reqId];
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
[dictionary setObject:[NSNumber numberWithInt:500] forKey:@"status"];
[dictionary setObject:@"Could not add file to post body." forKey:@"error"];
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:dictionary];
[weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
[[SDNetworkActivityIndicator sharedActivityIndicator] stopActivity];
return;
}
}
progress:nil
success:onSuccess
failure:onFailure
];
}
[self addRequest:reqId forTask:task];
}
@catch (NSException *exception) {
@catch (NSException *exception)
{
[[SDNetworkActivityIndicator sharedActivityIndicator] stopActivity];
[self handleException:exception withCommand:command];
}
@@ -513,7 +588,7 @@
- (void)downloadFile:(CDVInvokedUrlCommand*)command {
SM_AFHTTPSessionManager *manager = [SM_AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.responseSerializer = [SM_AFHTTPResponseSerializer serializer];
NSString *url = [command.arguments objectAtIndex:0];
NSDictionary *headers = [command.arguments objectAtIndex:1];

View File

@@ -81,18 +81,18 @@ 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 <SM_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 <SM_AFURLResponseSerialization> * responseSerializer;
@property (nonatomic, strong) SM_AFHTTPResponseSerializer <SM_AFURLResponseSerialization> * responseSerializer;
///---------------------
/// @name Initialization

View File

@@ -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 <SM_AFURLRequestSerialization> *)requestSerializer {
- (void)setRequestSerializer:(SM_AFHTTPRequestSerializer <SM_AFURLRequestSerialization> *)requestSerializer {
NSParameterAssert(requestSerializer);
_requestSerializer = requestSerializer;
}
- (void)setResponseSerializer:(AFHTTPResponseSerializer <SM_AFURLResponseSerialization> *)responseSerializer {
- (void)setResponseSerializer:(SM_AFHTTPResponseSerializer <SM_AFURLResponseSerialization> *)responseSerializer {
NSParameterAssert(responseSerializer);
[super setResponseSerializer:responseSerializer];
@@ -426,8 +426,8 @@
return nil;
}
self.requestSerializer = [decoder decodeObjectOfClass:[AFHTTPRequestSerializer class] forKey:NSStringFromSelector(@selector(requestSerializer))];
self.responseSerializer = [decoder decodeObjectOfClass:[AFHTTPResponseSerializer class] forKey:NSStringFromSelector(@selector(responseSerializer))];
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;

View File

@@ -200,7 +200,7 @@ FOUNDATION_EXPORT NSString * const SM_AFNetworkingReachabilityNotificationStatus
/**
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

View File

@@ -33,7 +33,7 @@ NSString * const SM_AFNetworkingReachabilityNotificationStatusItem = @"SM_AFNetw
typedef void (^AFNetworkReachabilityStatusBlock)(AFNetworkReachabilityStatus status);
NSString * AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status) {
NSString * SM_AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status) {
switch (status) {
case AFNetworkReachabilityStatusNotReachable:
return NSLocalizedStringFromTable(@"Not Reachable", @"SM_AFNetworking", nil);
@@ -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 -

View File

@@ -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,7 +53,7 @@ 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 `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.
@@ -89,11 +89,11 @@ typedef NS_ENUM(NSUInteger, AFHTTPRequestQueryStringSerializationStyle) {
@protocol AFMultipartFormData;
/**
`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.
`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 <SM_AFURLRequestSerialization>
@interface SM_AFHTTPRequestSerializer : NSObject <SM_AFURLRequestSerialization>
/**
The string encoding used to serialize parameters. `NSUTF8StringEncoding` by default.
@@ -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".
@@ -467,13 +467,13 @@ FOUNDATION_EXPORT NSString * const SM_AFNetworkingOperationFailingURLRequestErro
### 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

View File

@@ -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;
@@ -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;
}
@@ -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,7 +1205,7 @@ typedef enum {
+ (instancetype)serializerWithWritingOptions:(NSJSONWritingOptions)writingOptions
{
AFJSONRequestSerializer *serializer = [[self alloc] init];
SM_AFJSONRequestSerializer *serializer = [[self alloc] init];
serializer.writingOptions = writingOptions;
return serializer;
@@ -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;

View File

@@ -49,11 +49,11 @@ NS_ASSUME_NONNULL_BEGIN
#pragma mark -
/**
`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.
`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 <SM_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,9 +252,9 @@ 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.
@@ -264,7 +264,7 @@ NS_ASSUME_NONNULL_BEGIN
/**
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<SM_AFURLResponseSerialization>> *)responseSerializers;

View File

@@ -86,7 +86,7 @@ static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingO
return JSONObject;
}
@implementation AFHTTPResponseSerializer
@implementation SM_AFHTTPResponseSerializer
+ (instancetype)serializer {
return [[self alloc] init];
@@ -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;
@@ -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;
}
@@ -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;
@@ -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;
@@ -638,7 +638,7 @@ static UIImage * AFInflatedImageFromResponseWithDataAtScale(NSHTTPURLResponse *r
#endif
@implementation AFImageResponseSerializer
@implementation SM_AFImageResponseSerializer
- (instancetype)init {
self = [super init];
@@ -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,14 +737,14 @@ 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;
@@ -757,7 +757,7 @@ static UIImage * AFInflatedImageFromResponseWithDataAtScale(NSHTTPURLResponse *r
error:(NSError *__autoreleasing *)error
{
for (id <SM_AFURLResponseSerialization> serializer in self.responseSerializers) {
if (![serializer isKindOfClass:[AFHTTPResponseSerializer class]]) {
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;

View File

@@ -100,7 +100,7 @@ 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`.
*/
@@ -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;
@@ -465,12 +465,12 @@ 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 `SM_AFNetworkingTaskDidCompleteNotification` if response data exists for the task.

View File

@@ -72,8 +72,8 @@ static dispatch_group_t url_session_manager_completion_group() {
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 AFURLSessionDidInvalidateNotification = @"com.alamofire.networking.session.invalidate";
NSString * const AFURLSessionDownloadTaskDidFailToMoveFileNotification = @"com.alamofire.networking.session.download.file-manager-error";
NSString * const SM_AFURLSessionDidInvalidateNotification = @"com.alamofire.networking.session.invalidate";
NSString * const SM_AFURLSessionDownloadTaskDidFailToMoveFileNotification = @"com.alamofire.networking.session.download.file-manager-error";
NSString * const SM_AFNetworkingTaskDidCompleteSerializedResponseKey = @"com.alamofire.networking.task.complete.serializedresponse";
NSString * const SM_AFNetworkingTaskDidCompleteResponseSerializerKey = @"com.alamofire.networking.task.complete.responseserializer";
@@ -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 {
/**
@@ -511,6 +511,7 @@ static NSString * const AFNSURLSessionTaskDidSuspendNotification = @"com.alamofi
if (!configuration) {
configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
configuration.URLCache = nil;
}
self.sessionConfiguration = configuration;
@@ -520,7 +521,7 @@ 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 = [SM_AFSecurityPolicy defaultPolicy];
@@ -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
@@ -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;

View File

@@ -1,7 +1,7 @@
#import <Foundation/Foundation.h>
#import "SM_AFURLRequestSerialization.h"
@interface TextRequestSerializer : AFHTTPRequestSerializer
@interface TextRequestSerializer : SM_AFHTTPRequestSerializer
+ (instancetype)serializer;

View File

@@ -1,7 +1,7 @@
#import <Foundation/Foundation.h>
#import "SM_AFURLResponseSerialization.h"
@interface TextResponseSerializer : AFHTTPResponseSerializer
@interface TextResponseSerializer : SM_AFHTTPResponseSerializer
+ (instancetype)serializer;

View File

@@ -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": "11.0.0",
"cordova-android": "10.1.1",
"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-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"
}
}

View File

@@ -9,9 +9,7 @@ const hooks = {
}
helpers.setDefaultServerTrustMode(function () {
// @TODO: not ready yet
// helpers.setNoneClientAuthMode(resolve, reject);
resolve();
helpers.setNoneClientAuthMode(resolve, reject);
}, reject);
});
}
@@ -23,12 +21,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 +39,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) {
@@ -317,18 +321,18 @@ 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); },
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);
@@ -342,7 +346,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,
@@ -350,7 +354,7 @@ const tests = [
name: entry.name,
content: content
});
}, targetPath);
}, reject);
}, reject);
},
validationFunc: function (driver, result) {
@@ -520,7 +524,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,
@@ -528,7 +532,7 @@ const tests = [
name: entry.name,
content: content
});
}, targetPath);
}, reject);
}, reject);
},
validationFunc: function (driver, result) {
@@ -697,7 +701,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,
@@ -705,7 +709,7 @@ const tests = [
name: entry.name,
content: content
});
}, targetPath);
}, reject);
}, reject);
},
validationFunc: function (driver, result) {
@@ -851,14 +855,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');
@@ -877,9 +885,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');
@@ -1075,7 +1087,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,
@@ -1083,7 +1095,7 @@ const tests = [
name: entry.name,
content: content
});
}, targetPath);
}, reject);
}, reject);
setTimeout(function () {

View File

@@ -64,7 +64,7 @@ const configs = {
os_version: '14',
project: 'HTTP Test App',
autoWebview: true,
app: 'HttpTestAppAndroid',
app: 'HttpTestAppIos',
'browserstack.networkLogs': false
},
browserstackAndroidDevice: {

View File

@@ -343,7 +343,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);
}
}
@@ -495,7 +498,7 @@ module.exports = function init(global, jsUtil, cookieHandler, messages, base64,
function handleMissingOptions(options, globals) {
options = options || {};
return {
return Object.assign({}, options, {
data: jsUtil.getTypeOf(options.data) === 'Undefined' ? null : options.data,
filePath: options.filePath,
followRedirect: checkFollowRedirectValue(options.followRedirect || globals.followRedirect),
@@ -508,6 +511,6 @@ module.exports = function init(global, jsUtil, cookieHandler, messages, base64,
connectTimeout: checkTimeoutValue(options.connectTimeout || globals.connectTimeout),
readTimeout: checkTimeoutValue(options.readTimeout || globals.readTimeout),
timeout: checkTimeoutValue(options.timeout || globals.timeout)
};
});
}
};

View File

@@ -180,7 +180,13 @@ module.exports = function init(exec, cookieHandler, urlUtil, helpers, globalConf
break;
case 'upload':
var fileOptions = helpers.checkUploadFileOptions(options.filePath, options.name);
exec(onSuccess, onFail, 'CordovaHttpPlugin', 'uploadFiles', [url, headers, fileOptions.filePaths, fileOptions.names, options.connectTimeout, options.readTimeout, options.followRedirect, options.responseType, reqId]);
// support uploading files as octet-stream / encoded string instead of form-data
var transmitOptions = {};
transmitOptions.transmitFileAs = options.transmitFileAs || 'FORMDATA';
// transmitOptions.transmitMethod = options.transmitMethod || 'POST';
exec(onSuccess, onFail, 'CordovaHttpPlugin', 'uploadFiles', [url, headers, fileOptions.filePaths, fileOptions.names, options.connectTimeout, options.readTimeout, options.followRedirect, options.responseType, transmitOptions, reqId]);
break;
case 'download':
var filePath = helpers.checkDownloadFilePath(options.filePath);

File diff suppressed because one or more lines are too long