• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

silkimen/cordova-plugin-advanced-http: Cordova / Phonegap plugin for communicati ...

原作者: [db:作者] 来自: 网络 收藏 邀请

开源软件名称:

silkimen/cordova-plugin-advanced-http

开源软件地址:

https://github.com/silkimen/cordova-plugin-advanced-http

开源编程语言:

JavaScript 47.2%

开源软件介绍:

Cordova Advanced HTTP

npm version MIT Licence downloads/month

Travis Build Status GitHub Build Status

Cordova / Phonegap plugin for communicating with HTTP servers. Supports iOS, Android and Browser.

This is a fork of Wymsee's Cordova-HTTP plugin.

Advantages over Javascript requests

  • SSL / TLS Pinning
  • CORS restrictions do not apply
  • X.509 client certificate based authentication
  • Handling of HTTP code 401 - read more at Issue CB-2415

Updates

Please check CHANGELOG.md for details about updating to a new version.

Installation

The plugin conforms to the Cordova plugin specification, it can be installed using the Cordova / Phonegap command line interface.

phonegap plugin add cordova-plugin-advanced-http

cordova plugin add cordova-plugin-advanced-http

Plugin Preferences

AndroidBlacklistSecureSocketProtocols: define a blacklist of secure socket protocols for Android. This preference allows you to disable protocols which are considered unsafe. You need to provide a comma-separated list of protocols (check Android SSLSocket#protocols docu for protocol names).

e.g. blacklist SSLv3 and TLSv1:

<preference name="AndroidBlacklistSecureSocketProtocols" value="SSLv3,TLSv1" />

Currently known issues

  • aborting sent requests is not working reliably

Usage

Plain Cordova

This plugin registers a global object located at cordova.plugin.http.

With Ionic-native wrapper

Check the Ionic docs for how to use this plugin with Ionic-native.

Synchronous Functions

getBasicAuthHeader

This returns an object representing a basic HTTP Authorization header of the form {'Authorization': 'Basic base64encodedusernameandpassword'}

var header = cordova.plugin.http.getBasicAuthHeader('user', 'password');

useBasicAuth

This sets up all future requests to use Basic HTTP authentication with the given username and password.

cordova.plugin.http.useBasicAuth('user', 'password');

setHeader

Set a header for all future requests to a specified host. Takes a hostname, a header and a value (must be a string value or null).

cordova.plugin.http.setHeader('Hostname', 'Header', 'Value');

You can also define headers used for all hosts by using wildcard character "*" or providing only two params.

cordova.plugin.http.setHeader('*', 'Header', 'Value');
cordova.plugin.http.setHeader('Header', 'Value');

The hostname also includes the port number. If you define a header for www.example.com it will not match following URL http://www.example.com:8080.

// will match http://www.example.com/...
cordova.plugin.http.setHeader('www.example.com', 'Header', 'Value');

// will match http://www.example.com:8080/...
cordova.plugin.http.setHeader('www.example.com:8080', 'Header', 'Value');

setDataSerializer

Set the data serializer which will be used for all future PATCH, POST and PUT requests. Takes a string representing the name of the serializer.

cordova.plugin.http.setDataSerializer('urlencoded');

You can choose one of these:

  • urlencoded: send data as url encoded content in body
    • default content type "application/x-www-form-urlencoded"
    • data must be an dictionary style Object
  • json: send data as JSON encoded content in body
    • default content type "application/json"
    • data must be an Array or an dictionary style Object
  • utf8: send data as plain UTF8 encoded string in body
    • default content type "plain/text"
    • data must be a String
  • multipart: send FormData objects as multipart content in body
    • default content type "multipart/form-data"
    • data must be an FormData instance
  • raw: send data as is, without any processing
    • default content type "application/octet-stream"
    • data must be an Uint8Array or an ArrayBuffer

This defaults to urlencoded. You can also override the default content type headers by specifying your own headers (see setHeader).

⚠️ urlencoded does not support serializing deep structures whereas json does.

⚠️ multipart depends on several Web API standards which need to be supported in your web view. Check out https://github.com/silkimen/cordova-plugin-advanced-http/wiki/Web-APIs-required-for-Multipart-requests for more info.

setRequestTimeout

Set how long to wait for a request to respond, in seconds. For Android, this will set both connectTimeout and readTimeout. For iOS, this will set timeout interval. For browser platform, this will set timeout.

cordova.plugin.http.setRequestTimeout(5.0);

setConnectTimeout (Android Only)

Set connect timeout for Android

cordova.plugin.http.setRequestTimeout(5.0);

setReadTimeout (Android Only)

Set read timeout for Android

cordova.plugin.http.setReadTimeout(5.0);

setFollowRedirect

Configure if it should follow redirects automatically. This defaults to true.

cordova.plugin.http.setFollowRedirect(true);

getCookieString

Returns saved cookies (as string) matching given URL.

cordova.plugin.http.getCookieString(url);

setCookie

Add a custom cookie. Takes a URL, a cookie string and an options object. See ToughCookie documentation for allowed options.

cordova.plugin.http.setCookie(url, cookie, options);

clearCookies

Clear the cookie store.

cordova.plugin.http.clearCookies();

Asynchronous Functions

These functions all take success and error callbacks as their last 2 arguments.

setServerTrustMode

Set server trust mode, being one of the following values:

  • default: default SSL trustship and hostname verification handling using system's CA certs
  • legacy: use legacy default behavior (< 2.0.3), excluding user installed CA certs (only for Android)
  • nocheck: disable SSL certificate checking and hostname verification, trusting all certs (meant to be used only for testing purposes)
  • pinned: trust only provided certificates

To use SSL pinning you must include at least one .cer SSL certificate in your app project. You can pin to your server certificate or to one of the issuing CA certificates. Include your certificate in the www/certificates folder. All .cer files found there will be loaded automatically.

⚠️ Your certificate must be DER encoded! If you only have a PEM encoded certificate read this stackoverflow answer. You want to convert it to a DER encoded certificate with a .cer extension.

// enable SSL pinning
cordova.plugin.http.setServerTrustMode('pinned', function() {
  console.log('success!');
}, function() {
  console.log('error :(');
});

// use system's default CA certs
cordova.plugin.http.setServerTrustMode('default', function() {
  console.log('success!');
}, function() {
  console.log('error :(');
});

// disable SSL cert checking, only meant for testing purposes, do NOT use in production!
cordova.plugin.http.setServerTrustMode('nocheck', function() {
  console.log('success!');
}, function() {
  console.log('error :(');
});

setClientAuthMode

Configure X.509 client certificate authentication. Takes mode and options. mode being one of following values:

  • none: disable client certificate authentication
  • systemstore (only on Android): use client certificate installed in the Android system store; user will be presented with a list of all installed certificates
  • buffer: use given client certificate; you will need to provide an options object:
    • rawPkcs: ArrayBuffer containing raw PKCS12 container with client certificate and private key
    • pkcsPassword: password of the PKCS container
  // enable client auth using PKCS12 container given in ArrayBuffer `myPkcs12ArrayBuffer`
  cordova.plugin.http.setClientAuthMode('buffer', {
    rawPkcs: myPkcs12ArrayBuffer,
    pkcsPassword: 'mySecretPassword'
  }, success, fail);

  // enable client auth using certificate in system store (only on Android)
  cordova.plugin.http.setClientAuthMode('systemstore', {}, success, fail);

  // disable client auth
  cordova.plugin.http.setClientAuthMode('none', {}, success, fail);

removeCookies

Remove all cookies associated with a given URL.

cordova.plugin.http.removeCookies(url, callback);

sendRequest

Execute a HTTP request. Takes a URL and an options object. This is the internally used implementation of the following shorthand functions (post, get, put, patch, delete, head, uploadFile and downloadFile). You can use this function, if you want to override global settings for each single request. Check the documentation of the respective shorthand function for details on what is returned on success and failure.

⚠️ You need to encode the base URL yourself if it contains special characters like whitespaces. You can use encodeURI() for this purpose.

The options object contains following keys:

  • method: HTTP method to be used, defaults to get, needs to be one of the following values:
    • get, post, put, patch, head, delete, options, upload, download
  • data: payload to be send to the server (only applicable on post, put or patch methods)
  • params: query params to be appended to the URL (only applicable on get, head, delete, upload or download methods)
  • serializer: data serializer to be used (only applicable on post, put or patch methods), defaults to global serializer value, see setDataSerializer for supported values
  • responseType: expected response type, defaults to text, needs to be one of the following values:
    • text: data is returned as decoded string, use this for all kinds of string responses (e.g. XML, HTML, plain text, etc.)
    • json data is treated as JSON and returned as parsed object, returns undefined when response body is empty
    • arraybuffer: data is returned as ArrayBuffer instance, returns null when response body is empty
    • blob: data is returned as Blob instance, returns null when response body is empty
  • timeout: timeout value for the request in seconds, defaults to global timeout value
  • followRedirect: enable or disable automatically following redirects
  • headers: headers object (key value pair), will be merged with global values
  • filePath: file path(s) to be used during upload and download see uploadFile and downloadFile for detailed information
  • name: name(s) to be used during upload see uploadFile for detailed information

Here's a quick example:

const options = {
  method: 'post',
  data: { id: 12, message: 'test' },
  headers: { Authorization: 'OAuth2: token' }
};

cordova.plugin.http.sendRequest('https://google.com/', options, function(response) {
  // prints 200
  console.log(response.status);
}, function(response) {
  // prints 403
  console.log(response.status);

  //prints Permission denied
  console.log(response.error);
});

post

Execute a POST request. Takes a URL, data, and headers.

cordova.plugin.http.post('https://google.com/', {
  test: 'testString'
}, {
  Authorization: 'OAuth2: token'
}, function(response) {
  console.log(response.status);
}, function(response) {
  console.error(response.error);
});

success

The success function receives a response object with 4 properties: status, data, url, and headers. status is the HTTP response code as numeric value. data is the response from the server as a string. url is the final URL obtained after any redirects as a string. headers is an object with the headers. The keys of the returned object are the header names and the values are the respective header values. All header names are lowercase.

Here's a quick example:

{
  status: 200,
  data: '{"id": 12, "message": "test"}',
  url: 'http://example.net/rest'
  headers: {
    'content-length': '247'
  }
}

Most apis will return JSON meaning you'll want to parse the data like in the example below:

cordova.plugin.http.post('https://google.com/', {
  id: 12,
  message: 'test'
}, { Authorization: 'OAuth2: token' }, function(response) {
  // prints 200
  console.log(response.status);
  try {
    response.data = JSON.parse(response.data);
    // prints test
    console.log(response.data.message);
  } catch(e) {
    console.error('JSON parsing error');
  }
}, function(response) {
  // prints 403
  console.log(response.status);

  //prints Permission denied
  console.log(response.error);
});

failure

The error function receives a response object with 4 properties: status, error, url, and headers (url and headers being optional). status is a HTTP response code or an internal error code. Positive values are HTTP status codes whereas negative values do represent internal error codes. error is the error response from the server as a string or an internal error message. url is the final URL obtained after any redirects as a string. headers is an object with the headers. The keys of the returned object are the header names and the values are the respective header values. All header names are lowercase.

Here's a quick example:

{
  status: 403,
  error: 'Permission denied',
  url: 'http://example.net/noperm'
  headers: {
    'content-length': '247'
  }
}

⚠️ An enumeration style object is exposed as cordova.plugin.http.ErrorCode. You can use it to check against internal error codes.

get

Execute a GET request. Takes a URL, parameters, and headers. See the post documentation for details on what is returned on success and failure.


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
trusche/httplog: Log outgoing HTTP requests in ruby发布时间:2022-06-17
下一篇:
JuliaWeb/HTTP.jl: HTTP for Julia发布时间:2022-06-17
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap