Native HTTP client with web fallback for making network requests with advanced features like custom headers, timeouts, and response type handling. The HTTP client provides a unified interface for network operations across all platforms while leveraging native implementations for better performance and capabilities on mobile devices.
Main HTTP client plugin providing all HTTP methods with consistent interface across platforms.
/**
* HTTP plugin interface for making network requests
*/
interface CapacitorHttpPlugin {
/** Make generic HTTP request */
request(options: HttpOptions): Promise<HttpResponse>;
/** Make HTTP GET request */
get(options: HttpOptions): Promise<HttpResponse>;
/** Make HTTP POST request */
post(options: HttpOptions): Promise<HttpResponse>;
/** Make HTTP PUT request */
put(options: HttpOptions): Promise<HttpResponse>;
/** Make HTTP PATCH request */
patch(options: HttpOptions): Promise<HttpResponse>;
/** Make HTTP DELETE request */
delete(options: HttpOptions): Promise<HttpResponse>;
}Usage Examples:
import { CapacitorHttp } from "@capacitor/core";
// GET request
const response = await CapacitorHttp.get({
url: 'https://api.example.com/users',
headers: {
'Authorization': 'Bearer token123',
},
});
console.log(response.data);
// POST request with JSON data
const postResponse = await CapacitorHttp.post({
url: 'https://api.example.com/users',
data: {
name: 'John Doe',
email: 'john@example.com',
},
headers: {
'Content-Type': 'application/json',
},
});
// Generic request method
const customResponse = await CapacitorHttp.request({
url: 'https://api.example.com/data',
method: 'PATCH',
data: { status: 'updated' },
headers: {
'Content-Type': 'application/json',
'X-Custom-Header': 'value',
},
});Comprehensive request configuration options for all HTTP operations.
/**
* HTTP request configuration options
*/
interface HttpOptions {
/** URL to send the request to */
url: string;
/** HTTP method (default: GET) */
method?: string;
/** URL parameters to append */
params?: HttpParams;
/** Request body data */
data?: any;
/** HTTP headers */
headers?: HttpHeaders;
/** Read timeout in milliseconds */
readTimeout?: number;
/** Connection timeout in milliseconds */
connectTimeout?: number;
/** Disable automatic redirects */
disableRedirects?: boolean;
/** Extra fetch options for web platform */
webFetchExtra?: RequestInit;
/** Response parsing type */
responseType?: HttpResponseType;
/** Keep URL unencoded (default: true) */
shouldEncodeUrlParams?: boolean;
/** Data type indicator for native handling */
dataType?: 'file' | 'formData';
}
/**
* URL parameters object
*/
interface HttpParams {
[key: string]: string | string[];
}
/**
* HTTP headers object
*/
interface HttpHeaders {
[key: string]: string;
}
/**
* Response parsing types
*/
type HttpResponseType = 'arraybuffer' | 'blob' | 'json' | 'text' | 'document';Usage Examples:
import { CapacitorHttp } from "@capacitor/core";
// Request with URL parameters
const response = await CapacitorHttp.get({
url: 'https://api.example.com/search',
params: {
q: 'capacitor',
page: '1',
limit: '10',
tags: ['mobile', 'typescript'], // Array parameters
},
});
// Request with custom timeouts
const timeoutResponse = await CapacitorHttp.get({
url: 'https://slow-api.example.com/data',
connectTimeout: 5000, // 5 second connection timeout
readTimeout: 30000, // 30 second read timeout
});
// File upload with FormData
const formData = new FormData();
formData.append('file', fileBlob, 'image.jpg');
formData.append('description', 'Profile image');
const uploadResponse = await CapacitorHttp.post({
url: 'https://api.example.com/upload',
data: formData,
dataType: 'formData',
});
// Raw binary data
const binaryResponse = await CapacitorHttp.get({
url: 'https://api.example.com/image.jpg',
responseType: 'arraybuffer',
});
// Web-specific fetch options
const webResponse = await CapacitorHttp.get({
url: 'https://api.example.com/data',
webFetchExtra: {
credentials: 'include',
cache: 'no-cache',
},
});Response object structure and handling for all HTTP operations.
/**
* HTTP response object
*/
interface HttpResponse {
/** Response data (parsed based on responseType) */
data: any;
/** HTTP status code */
status: number;
/** Response headers */
headers: HttpHeaders;
/** Final response URL (after redirects) */
url: string;
}Usage Examples:
import { CapacitorHttp } from "@capacitor/core";
try {
const response = await CapacitorHttp.get({
url: 'https://api.example.com/data',
});
// Check status
if (response.status >= 200 && response.status < 300) {
console.log('Success:', response.data);
}
// Access headers
const contentType = response.headers['content-type'];
const serverHeader = response.headers['server'];
console.log(`Content-Type: ${contentType}`);
// Check final URL (useful for redirects)
console.log(`Final URL: ${response.url}`);
} catch (error) {
console.error('Request failed:', error);
}
// Handle different response types
const jsonResponse = await CapacitorHttp.get({
url: 'https://api.example.com/json',
responseType: 'json',
});
console.log(jsonResponse.data.property); // Direct JSON access
const textResponse = await CapacitorHttp.get({
url: 'https://api.example.com/text',
responseType: 'text',
});
console.log(textResponse.data); // String content
const blobResponse = await CapacitorHttp.get({
url: 'https://api.example.com/file.pdf',
responseType: 'blob',
});
// Note: On native platforms, blob data is returned as base64 string
const base64Data = blobResponse.data;Utility functions for building and customizing HTTP requests.
/**
* Build RequestInit object for web fetch operations
* @param options HTTP options to convert
* @param extra Additional RequestInit properties
* @returns RequestInit object for fetch API
*/
function buildRequestInit(options: HttpOptions, extra?: RequestInit): RequestInit;
/**
* Convert Blob to base64 string
* @param blob Blob to convert
* @returns Promise resolving to base64 string
*/
function readBlobAsBase64(blob: Blob): Promise<string>;Usage Examples:
import { buildRequestInit, readBlobAsBase64 } from "@capacitor/core";
// Build fetch RequestInit from HttpOptions
const httpOptions = {
method: 'POST',
data: { name: 'John' },
headers: { 'Content-Type': 'application/json' },
};
const requestInit = buildRequestInit(httpOptions, {
credentials: 'include',
});
// Use with fetch directly on web
const response = await fetch('https://api.example.com/data', requestInit);
// Convert blob to base64 for native platforms
const fileInput = document.getElementById('file') as HTMLInputElement;
const file = fileInput.files[0];
const base64 = await readBlobAsBase64(file);
// Send base64 data to native
await CapacitorHttp.post({
url: 'https://api.example.com/upload',
data: {
file: base64,
filename: file.name,
mimeType: file.type,
},
dataType: 'file',
});Common patterns for complex HTTP operations and error handling.
Usage Examples:
import { CapacitorHttp } from "@capacitor/core";
// Retry pattern with exponential backoff
async function requestWithRetry(url: string, maxRetries = 3): Promise<HttpResponse> {
let lastError;
for (let i = 0; i < maxRetries; i++) {
try {
return await CapacitorHttp.get({ url });
} catch (error) {
lastError = error;
if (i < maxRetries - 1) {
const delay = Math.pow(2, i) * 1000; // Exponential backoff
await new Promise(resolve => setTimeout(resolve, delay));
}
}
}
throw lastError;
}
// Request with authentication header
async function authenticatedRequest(url: string, token: string) {
return await CapacitorHttp.get({
url,
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
},
});
}
// File upload with progress (web implementation)
async function uploadWithProgress(file: File, url: string, onProgress?: (percent: number) => void) {
// On web, use regular fetch for upload progress
if (typeof window !== 'undefined') {
const formData = new FormData();
formData.append('file', file);
const xhr = new XMLHttpRequest();
return new Promise<HttpResponse>((resolve, reject) => {
xhr.upload.addEventListener('progress', (event) => {
if (event.lengthComputable && onProgress) {
const percent = (event.loaded / event.total) * 100;
onProgress(percent);
}
});
xhr.addEventListener('load', () => {
resolve({
data: JSON.parse(xhr.responseText),
status: xhr.status,
headers: {}, // Parse from xhr.getAllResponseHeaders() if needed
url: xhr.responseURL,
});
});
xhr.addEventListener('error', () => reject(new Error('Upload failed')));
xhr.open('POST', url);
xhr.send(formData);
});
}
// On native, use CapacitorHttp (no progress support)
return await CapacitorHttp.post({
url,
data: file,
dataType: 'file',
});
}
// JSON API client pattern
class ApiClient {
constructor(private baseUrl: string, private token?: string) {}
private async request(method: string, endpoint: string, data?: any) {
const headers: any = {
'Content-Type': 'application/json',
};
if (this.token) {
headers['Authorization'] = `Bearer ${this.token}`;
}
return await CapacitorHttp.request({
method,
url: `${this.baseUrl}${endpoint}`,
data: data ? JSON.stringify(data) : undefined,
headers,
});
}
async get(endpoint: string) {
return this.request('GET', endpoint);
}
async post(endpoint: string, data: any) {
return this.request('POST', endpoint, data);
}
async put(endpoint: string, data: any) {
return this.request('PUT', endpoint, data);
}
async delete(endpoint: string) {
return this.request('DELETE', endpoint);
}
}
// Usage
const api = new ApiClient('https://api.example.com', 'your-token');
const users = await api.get('/users');
const newUser = await api.post('/users', { name: 'John', email: 'john@example.com' });