CapacitorHttp
The Capacitor Http API provides native http support via patching fetch and XMLHttpRequest to use native libraries. It also provides helper methods for native http requests without the use of fetch and XMLHttpRequest. This plugin is bundled with @capacitor/core.
Configuration
By default, the patching of window.fetch and XMLHttpRequest to use native libraries is disabled.
If you would like to enable this feature, modify the configuration below in the capacitor.config file.
| Prop | Type | Description | Default |
|---|---|---|---|
enabled | boolean | Enable the patching of fetch and XMLHttpRequest to use native libraries instead. | false |
Example Configuration
In capacitor.config.json:
{
"plugins": {
"CapacitorHttp": {
"enabled": true
}
}
}
In capacitor.config.ts:
import { CapacitorConfig } from '@capacitor/cli';
const config: CapacitorConfig = {
plugins: {
CapacitorHttp: {
enabled: true,
},
},
};
export default config;
Example
import { CapacitorHttp } from '@capacitor/core';
// Example of a GET request
const doGet = () => {
const options = {
url: 'https://example.com/my/api',
headers: { 'X-Fake-Header': 'Fake-Value' },
params: { size: 'XL' },
};
const response: HttpResponse = await CapacitorHttp.get(options);
// or...
// const response = await CapacitorHttp.request({ ...options, method: 'GET' })
};
// Example of a POST request. Note: data
// can be passed as a raw JS Object (must be JSON serializable)
const doPost = () => {
const options = {
url: 'https://example.com/my/api',
headers: { 'X-Fake-Header': 'Fake-Value' },
data: { foo: 'bar' },
};
const response: HttpResponse = await CapacitorHttp.post(options);
// or...
// const response = await CapacitorHttp.request({ ...options, method: 'POST' })
};
Large File Support
Due to the nature of the bridge, parsing and transferring large amount of data from native to the web can cause issues. Support for downloading and uploading files has been added to the @capacitor/file-transfer plugin. In many cases, you may also need @capacitor/filesystem to generate a valid file URI.
API
****** HTTP PLUGIN *******
request(...)
request(options: HttpOptions) => Promise<HttpResponse>
Make a Http Request to a server using native libraries.
| Param | Type |
|---|---|
options | |
Returns:
Promise<HttpResponse>
get(...)
get(options: HttpOptions) => Promise<HttpResponse>
Make a Http GET Request to a server using native libraries.
| Param | Type |
|---|---|
options | |
Returns:
Promise<HttpResponse>
post(...)
post(options: HttpOptions) => Promise<HttpResponse>
Make a Http POST Request to a server using native libraries.
| Param | Type |
|---|---|
options | |
Returns:
Promise<HttpResponse>
put(...)
put(options: HttpOptions) => Promise<HttpResponse>
Make a Http PUT Request to a server using native libraries.
| Param | Type |
|---|---|
options | |
Returns:
Promise<HttpResponse>
patch(...)
patch(options: HttpOptions) => Promise<HttpResponse>
Make a Http PATCH Request to a server using native libraries.
| Param | Type |
|---|---|
options | |
Returns:
Promise<HttpResponse>
delete(...)
delete(options: HttpOptions) => Promise<HttpResponse>
Make a Http DELETE Request to a server using native libraries.
| Param | Type |
|---|---|
options | |
Returns:
Promise<HttpResponse>
Interfaces
HttpResponse
| Prop | Type | Description |
|---|---|---|
data | any | Additional data received with the Http response. |
status | number | The status code received from the Http response. |
headers | | The headers received from the Http response. |
url | string | The response URL received from the Http response. |
HttpHeaders
HttpOptions
| Prop | Type | Description |
|---|---|---|
url | string | The URL to send the request to. |
method | string | The Http Request method to run. (Default is GET) |
params | | URL parameters to append to the request. |
data | any | Note: On Android and iOS, data can only be a string or a JSON. FormData, Blob, ArrayBuffer, and other complex types are only directly supported on web or through enabling CapacitorHttp in the config and using the patched window.fetch or XMLHttpRequest. If you need to send a complex type, you should serialize the data to base64 and set the headers["Content-Type"] and dataType attributes accordingly. |
headers | | Http Request headers to send with the request. |
readTimeout | number | How long to wait to read additional data in milliseconds. Resets each time new data is received. |
connectTimeout | number | How long to wait for the initial connection in milliseconds. |
disableRedirects | boolean | Sets whether automatic HTTP redirects should be disabled |
webFetchExtra | | Extra arguments for fetch when running on the web |
responseType | | This is used to parse the response appropriately before returning it to the requestee. If the response content-type is "json", this value is ignored. |
shouldEncodeUrlParams | boolean | Use this option if you need to keep the URL unencoded in certain cases (already encoded, azure/firebase testing, etc.). The default is true. |
dataType | 'file' | 'formData' | This is used if we've had to convert the data from a JS type that needs special handling in the native layer |
HttpParams
RequestInit
| Prop | Type | Description |
|---|---|---|
body | | A BodyInit object or null to set request's body. |
cache | | A string indicating how the request will interact with the browser's cache to set request's cache. |
credentials | | A string indicating whether credentials will be sent with the request always, never, or only when sent to a same-origin URL. Sets request's credentials. |
headers | | A Headers object, an object literal, or an array of two-item arrays to set request's headers. |
integrity | string | A cryptographic hash of the resource to be fetched by request. Sets request's integrity. |
keepalive | boolean | A boolean to set request's keepalive. |
method | string | A string to set request's method. |
mode | | A string to indicate whether the request will use CORS, or will be restricted to same-origin URLs. Sets request's mode. |
redirect | | A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. |
referrer | string | A string whose value is a same-origin URL, "about:client", or the empty string, to set request's referrer. |
referrerPolicy | | A referrer policy to set request's referrerPolicy. |
signal | | An AbortSignal to set request's signal. |
window | any | Can only be null. Used to disassociate request from any Window. |
Blob
A file-like object of immutable, raw data. Blobs represent data that isn't necessarily in a JavaScript-native format. The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user's system.
Blob class is a global reference for require('node:buffer').Blob
https://nodejs.org/api/buffer.html#class-blob
| Prop | Type |
|---|---|
size | number |
type | string |
| Method | Signature |
|---|---|
| arrayBuffer | () => Promise<ArrayBuffer> |
| slice | (start?: number, end?: number, contentType?: string) => Blob |
| stream | () => ReadableStream |
| text | () => Promise<string> |
ArrayBuffer
Represents a raw buffer of binary data, which is used to store data for the different typed arrays. ArrayBuffers cannot be read from or written to directly, but can be passed to a typed array or DataView Object to interpret the raw buffer as needed.
| Prop | Type | Description |
|---|---|---|
byteLength | number | Read-only. The length of the ArrayBuffer (in bytes). |
| Method | Signature | Description |
|---|---|---|
| slice | (begin: number, end?: number) => ArrayBuffer | Returns a section of an ArrayBuffer. |
ReadableStream
This Streams API interface represents a readable stream of byte data. The Fetch API offers a concrete instance of a ReadableStream through the body property of a Response object.
| Prop | Type |
|---|---|
locked | boolean |
| Method | Signature |
|---|---|
| cancel | (reason?: any) => Promise<void> |
| getReader | () => ReadableStreamDefaultReader<R> |
| pipeThrough | <T>(transform: ReadableWritablePair<T, R>, options?: StreamPipeOptions) => ReadableStream<T> |
| pipeTo | (dest: WritableStream<R>, options?: StreamPipeOptions) => Promise<void> |
| tee | () => [ReadableStream<R>, ReadableStream<R>] |