0
# HTTP Client
1
2
Full-featured HTTP client for REST API calls, file downloads, and network communication. The HTTP module provides both high-level convenience methods and low-level request configuration for comprehensive network operations.
3
4
## Capabilities
5
6
### HTTP Namespace
7
8
Core HTTP functionality providing convenience methods for common network operations.
9
10
```typescript { .api }
11
/**
12
* HTTP client namespace with convenience methods
13
*/
14
namespace Http {
15
// Convenience methods
16
function request(options: HttpRequestOptions): Promise<HttpResponse>;
17
function getJSON<T>(url: string): Promise<T>;
18
function getString(url: string): Promise<string>;
19
function getFile(url: string, destinationFilePath?: string): Promise<File>;
20
function getImage(url: string): Promise<ImageSource>;
21
}
22
```
23
24
**Usage Examples:**
25
26
```typescript
27
import { Http } from "tns-core-modules";
28
29
// GET JSON data
30
async function fetchUserData(userId: string) {
31
try {
32
const user = await Http.getJSON<User>(`https://api.example.com/users/${userId}`);
33
console.log("User:", user);
34
return user;
35
} catch (error) {
36
console.error("Failed to fetch user:", error);
37
}
38
}
39
40
// GET string content
41
async function fetchTextContent(url: string) {
42
const content = await Http.getString(url);
43
return content;
44
}
45
46
// Download file
47
async function downloadFile(url: string, localPath: string) {
48
const file = await Http.getFile(url, localPath);
49
console.log("Downloaded to:", file.path);
50
return file;
51
}
52
53
// Download image
54
async function loadImage(imageUrl: string) {
55
const imageSource = await Http.getImage(imageUrl);
56
return imageSource;
57
}
58
```
59
60
### HTTP Request Configuration
61
62
Comprehensive request configuration interface for advanced HTTP operations.
63
64
```typescript { .api }
65
/**
66
* HTTP request options interface
67
*/
68
interface HttpRequestOptions {
69
url: string;
70
method?: "GET" | "POST" | "PUT" | "DELETE" | "PATCH" | "HEAD" | "OPTIONS";
71
headers?: { [key: string]: string };
72
content?: string | HttpContent | any;
73
timeout?: number;
74
dontFollowRedirects?: boolean;
75
76
// Authentication
77
username?: string;
78
password?: string;
79
80
// SSL/TLS
81
allowLargeResponse?: boolean;
82
}
83
84
/**
85
* HTTP content interface for request bodies
86
*/
87
interface HttpContent {
88
data: any;
89
contentType: string;
90
}
91
```
92
93
**Advanced Request Examples:**
94
95
```typescript
96
import { Http, HttpRequestOptions } from "tns-core-modules";
97
98
// POST with JSON data
99
async function createUser(userData: any) {
100
const options: HttpRequestOptions = {
101
url: "https://api.example.com/users",
102
method: "POST",
103
headers: {
104
"Content-Type": "application/json",
105
"Authorization": "Bearer " + getAuthToken()
106
},
107
content: JSON.stringify(userData),
108
timeout: 30000
109
};
110
111
const response = await Http.request(options);
112
return response.content.toJSON();
113
}
114
115
// PUT with form data
116
async function updateProfile(profileData: any) {
117
const formData = new FormData();
118
Object.keys(profileData).forEach(key => {
119
formData.append(key, profileData[key]);
120
});
121
122
const options: HttpRequestOptions = {
123
url: "https://api.example.com/profile",
124
method: "PUT",
125
content: formData,
126
headers: {
127
"Authorization": "Bearer " + getAuthToken()
128
}
129
};
130
131
return await Http.request(options);
132
}
133
134
// DELETE with authentication
135
async function deleteResource(resourceId: string) {
136
const options: HttpRequestOptions = {
137
url: `https://api.example.com/resources/${resourceId}`,
138
method: "DELETE",
139
headers: {
140
"Authorization": "Bearer " + getAuthToken()
141
}
142
};
143
144
const response = await Http.request(options);
145
return response.statusCode === 204;
146
}
147
```
148
149
### HTTP Response Interface
150
151
Response interface providing access to response data, headers, and status information.
152
153
```typescript { .api }
154
/**
155
* HTTP response interface
156
*/
157
interface HttpResponse {
158
statusCode: number;
159
content: HttpContent;
160
headers: { [key: string]: string };
161
162
// Response body access methods
163
textContent: string;
164
}
165
166
/**
167
* HTTP response content interface
168
*/
169
interface HttpContent {
170
raw: any;
171
172
// Content conversion methods
173
toString(): string;
174
toJSON(): any;
175
toImage(): Promise<any>;
176
toFile(destinationFilePath?: string): Promise<File>;
177
}
178
179
/**
180
* HTTP response encoding options
181
*/
182
enum HttpResponseEncoding {
183
UTF8 = "utf8",
184
GBK = "gbk",
185
ISO88591 = "iso88591"
186
}
187
```
188
189
**Response Handling Examples:**
190
191
```typescript
192
import { Http, HttpResponse } from "tns-core-modules";
193
194
async function handleApiResponse() {
195
const response = await Http.request({
196
url: "https://api.example.com/data",
197
method: "GET"
198
});
199
200
// Check status code
201
if (response.statusCode === 200) {
202
// Access response data
203
const jsonData = response.content.toJSON();
204
console.log("Data:", jsonData);
205
206
// Access headers
207
const contentType = response.headers["content-type"];
208
const serverTime = response.headers["date"];
209
210
return jsonData;
211
} else {
212
throw new Error(`HTTP ${response.statusCode}: ${response.content.toString()}`);
213
}
214
}
215
216
// Handle different content types
217
async function processResponse(response: HttpResponse) {
218
const contentType = response.headers["content-type"] || "";
219
220
if (contentType.includes("application/json")) {
221
return response.content.toJSON();
222
} else if (contentType.includes("text/")) {
223
return response.content.toString();
224
} else if (contentType.includes("image/")) {
225
return await response.content.toImage();
226
} else {
227
// Handle binary content
228
return response.content.raw;
229
}
230
}
231
```
232
233
### Headers Interface
234
235
HTTP headers management for request and response header handling.
236
237
```typescript { .api }
238
/**
239
* HTTP headers interface
240
*/
241
interface Headers {
242
[key: string]: string;
243
}
244
245
/**
246
* Common HTTP headers constants
247
*/
248
namespace HttpHeaders {
249
const CONTENT_TYPE: "Content-Type";
250
const AUTHORIZATION: "Authorization";
251
const ACCEPT: "Accept";
252
const USER_AGENT: "User-Agent";
253
const CACHE_CONTROL: "Cache-Control";
254
const IF_MODIFIED_SINCE: "If-Modified-Since";
255
const ETAG: "ETag";
256
}
257
```
258
259
### Error Handling
260
261
HTTP error handling and network exception management.
262
263
```typescript { .api }
264
/**
265
* HTTP error interface
266
*/
267
interface HttpError extends Error {
268
response?: HttpResponse;
269
statusCode?: number;
270
responseText?: string;
271
}
272
273
/**
274
* Network error types
275
*/
276
namespace HttpErrorType {
277
const TIMEOUT: "timeout";
278
const NO_CONNECTION: "no_connection";
279
const SERVER_ERROR: "server_error";
280
const CLIENT_ERROR: "client_error";
281
const PARSE_ERROR: "parse_error";
282
}
283
```
284
285
**Error Handling Examples:**
286
287
```typescript
288
import { Http } from "tns-core-modules";
289
290
class ApiClient {
291
private baseUrl: string;
292
private authToken: string;
293
294
constructor(baseUrl: string) {
295
this.baseUrl = baseUrl;
296
}
297
298
async get<T>(endpoint: string): Promise<T> {
299
try {
300
const response = await Http.request({
301
url: `${this.baseUrl}${endpoint}`,
302
method: "GET",
303
headers: this.getHeaders(),
304
timeout: 10000
305
});
306
307
if (response.statusCode >= 200 && response.statusCode < 300) {
308
return response.content.toJSON();
309
} else {
310
throw this.createHttpError(response);
311
}
312
} catch (error) {
313
console.error(`API GET error for ${endpoint}:`, error);
314
throw this.handleNetworkError(error);
315
}
316
}
317
318
async post<T>(endpoint: string, data: any): Promise<T> {
319
try {
320
const response = await Http.request({
321
url: `${this.baseUrl}${endpoint}`,
322
method: "POST",
323
headers: {
324
...this.getHeaders(),
325
"Content-Type": "application/json"
326
},
327
content: JSON.stringify(data),
328
timeout: 15000
329
});
330
331
if (response.statusCode >= 200 && response.statusCode < 300) {
332
return response.content.toJSON();
333
} else {
334
throw this.createHttpError(response);
335
}
336
} catch (error) {
337
console.error(`API POST error for ${endpoint}:`, error);
338
throw this.handleNetworkError(error);
339
}
340
}
341
342
private getHeaders(): Headers {
343
const headers: Headers = {
344
"Accept": "application/json",
345
"User-Agent": "NativeScript-App/1.0"
346
};
347
348
if (this.authToken) {
349
headers["Authorization"] = `Bearer ${this.authToken}`;
350
}
351
352
return headers;
353
}
354
355
private createHttpError(response: HttpResponse): HttpError {
356
const error = new Error(`HTTP ${response.statusCode}`) as HttpError;
357
error.response = response;
358
error.statusCode = response.statusCode;
359
error.responseText = response.content.toString();
360
return error;
361
}
362
363
private handleNetworkError(error: any): Error {
364
if (error.message?.includes("timeout")) {
365
return new Error("Request timeout - please check your connection");
366
} else if (error.message?.includes("network")) {
367
return new Error("Network error - please check your internet connection");
368
}
369
return error;
370
}
371
372
setAuthToken(token: string): void {
373
this.authToken = token;
374
}
375
}
376
```