0
# HTTP Transport
1
2
HTTP transport layer with support for custom agents, proxies, SSL configuration, MTOM attachments, and comprehensive request/response handling for SOAP communication.
3
4
## Capabilities
5
6
### HTTP Client Class
7
8
Core HTTP transport implementation providing request/response handling with extensive configuration options.
9
10
```typescript { .api }
11
/**
12
* HTTP client for SOAP transport layer
13
* Handles all HTTP communication between SOAP client and server
14
*/
15
class HttpClient implements IHttpClient {
16
/** HTTP request options */
17
options: IOptions;
18
19
constructor(options?: IOptions);
20
21
/**
22
* Build the HTTP request (method, uri, headers, ...)
23
* @param rurl - The resource url
24
* @param data - The payload
25
* @param exheaders - Extra http headers
26
* @param exoptions - Extra options
27
* @returns The http request object for the request module
28
*/
29
buildRequest(rurl: string, data: any, exheaders?: IHeaders, exoptions?: IExOptions): any;
30
31
/**
32
* Handle the http response
33
* @param req - The request object
34
* @param res - The response object
35
* @param body - The http body
36
* @returns The parsed body
37
*/
38
handleResponse(req: any, res: any, body: any): any;
39
40
/**
41
* Make HTTP request to SOAP endpoint
42
* @param rurl - Target URL
43
* @param data - Request body data
44
* @param callback - Callback receiving (error, response, body)
45
* @param exheaders - HTTP headers to include
46
* @param exoptions - Additional request options
47
* @param caller - Calling context
48
*/
49
request(
50
rurl: string,
51
data: any,
52
callback: (error: any, res?: any, body?: any) => any,
53
exheaders?: IHeaders,
54
exoptions?: IExOptions,
55
caller?: any
56
): any;
57
58
/**
59
* Stream-based HTTP request (optional)
60
* @param rurl - Target URL
61
* @param data - Request body data
62
* @param exheaders - HTTP headers
63
* @param exoptions - Request options
64
* @param caller - Calling context
65
* @returns Readable stream
66
*/
67
requestStream?(
68
rurl: string,
69
data: any,
70
exheaders?: IHeaders,
71
exoptions?: IExOptions,
72
caller?: any
73
): any;
74
}
75
76
/**
77
* HTTP client interface for custom implementations
78
*/
79
interface IHttpClient {
80
request(rurl: string, data: any, callback: (error: any, res?: any, body?: any) => any, exheaders?: IHeaders, exoptions?: IExOptions, caller?: any): any;
81
requestStream?(rurl: string, data: any, exheaders?: IHeaders, exoptions?: IExOptions, caller?: any): any;
82
}
83
```
84
85
**Usage Examples:**
86
87
```typescript
88
import { createClientAsync, HttpClient } from "soap";
89
90
// Use default HTTP client
91
const client = await createClientAsync("http://example.com/service.wsdl");
92
93
// Create custom HTTP client
94
const customHttpClient = new HttpClient({
95
timeout: 30000,
96
proxy: 'http://proxy.company.com:8080'
97
});
98
99
const clientWithCustomHttp = await createClientAsync(
100
"http://example.com/service.wsdl",
101
{ httpClient: customHttpClient }
102
);
103
```
104
105
### HTTP Client Configuration
106
107
Comprehensive configuration options for HTTP transport behavior.
108
109
```typescript { .api }
110
interface IHttpClientOptions {
111
/** Request timeout in milliseconds */
112
timeout?: number;
113
/** Proxy server URL */
114
proxy?: string;
115
/** Custom HTTP headers for all requests */
116
headers?: IHeaders;
117
/** HTTPS agent configuration */
118
httpsAgent?: any;
119
/** HTTP agent configuration */
120
httpAgent?: any;
121
/** Maximum number of redirects to follow */
122
maxRedirects?: number;
123
/** SSL/TLS options */
124
ssl?: {
125
/** Private key for client certificate */
126
key?: string | Buffer;
127
/** Client certificate */
128
cert?: string | Buffer;
129
/** Certificate Authority certificates */
130
ca?: string | Buffer | Array<string | Buffer>;
131
/** PFX certificate data */
132
pfx?: string | Buffer;
133
/** Passphrase for certificate */
134
passphrase?: string;
135
/** Reject unauthorized certificates */
136
rejectUnauthorized?: boolean;
137
};
138
/** Enable request/response logging */
139
enableLogging?: boolean;
140
/** Custom user agent string */
141
userAgent?: string;
142
}
143
```
144
145
**Usage Examples:**
146
147
```typescript
148
// HTTP client with SSL configuration
149
const sslHttpClient = new HttpClient({
150
timeout: 60000,
151
ssl: {
152
key: fs.readFileSync('client-key.pem'),
153
cert: fs.readFileSync('client-cert.pem'),
154
ca: fs.readFileSync('ca-cert.pem'),
155
rejectUnauthorized: true
156
}
157
});
158
159
// HTTP client with proxy
160
const proxyHttpClient = new HttpClient({
161
proxy: 'http://username:password@proxy.company.com:8080',
162
headers: {
163
'User-Agent': 'MySOAPClient/1.0'
164
}
165
});
166
```
167
168
### MTOM (Message Transmission Optimization Mechanism)
169
170
Support for MTOM attachments in SOAP messages for efficient binary data transfer.
171
172
```typescript { .api }
173
/**
174
* Parse MTOM response containing binary attachments
175
* @param payload - Raw MTOM response buffer
176
* @param boundary - MIME boundary string from Content-Type header
177
* @param callback - Callback receiving (error, parsedResponse)
178
* @returns Promise that resolves when parsing is complete
179
*/
180
function parseMTOMResp(
181
payload: Buffer,
182
boundary: string,
183
callback: (err?: Error, resp?: IMTOMAttachments) => void
184
): Promise<void>;
185
186
/**
187
* MTOM response structure with attachments
188
*/
189
interface IMTOMResponse {
190
/** Main SOAP response body */
191
body: any;
192
/** Array of binary attachments */
193
attachments: IMTOMAttachment[];
194
}
195
196
/**
197
* Individual MTOM attachment
198
*/
199
interface IMTOMAttachment {
200
/** Attachment content-type */
201
contentType: string;
202
/** Attachment content-id */
203
contentId: string;
204
/** Binary attachment data */
205
body: Buffer;
206
/** Attachment headers */
207
headers: IHeaders;
208
}
209
```
210
211
**Usage Examples:**
212
213
```typescript
214
import { parseMTOMResp } from "soap";
215
216
// Handle MTOM response in custom HTTP client
217
class MTOMHttpClient implements IHttpClient {
218
request(url: any, data: any, callback: Function, headers?: any, options?: any) {
219
// Make HTTP request...
220
221
// Check if response is MTOM
222
const contentType = response.headers['content-type'];
223
if (contentType && contentType.includes('multipart/related')) {
224
const boundary = contentType.match(/boundary=([^;]+)/)?.[1];
225
226
parseMTOMResp(response.body, boundary, (err, parsed) => {
227
if (err) return callback(err);
228
229
console.log('Main response:', parsed.body);
230
console.log('Attachments:', parsed.attachments.length);
231
232
callback(null, response, parsed.body);
233
});
234
} else {
235
callback(null, response, response.body);
236
}
237
}
238
}
239
```
240
241
### Request/Response Interceptors
242
243
Intercept and modify HTTP requests and responses for custom processing.
244
245
```typescript { .api }
246
/**
247
* Custom HTTP client with request/response interceptors
248
*/
249
class InterceptingHttpClient implements IHttpClient {
250
constructor(
251
private requestInterceptor?: (options: any) => any,
252
private responseInterceptor?: (response: any) => any
253
) {}
254
255
request(url: any, data: any, callback: Function, headers?: any, options?: any) {
256
// Apply request interceptor
257
if (this.requestInterceptor) {
258
const requestOptions = { url, data, headers, ...options };
259
const modifiedOptions = this.requestInterceptor(requestOptions);
260
({ url, data, headers, ...options } = modifiedOptions);
261
}
262
263
// Make actual HTTP request...
264
265
// Apply response interceptor
266
if (this.responseInterceptor && response) {
267
response = this.responseInterceptor(response);
268
}
269
270
callback(error, response, body);
271
}
272
}
273
```
274
275
**Usage Examples:**
276
277
```typescript
278
// Create HTTP client with logging interceptors
279
const loggingHttpClient = new InterceptingHttpClient(
280
// Request interceptor
281
(options) => {
282
console.log('Outgoing request:', {
283
url: options.url,
284
headers: options.headers,
285
bodySize: options.data?.length
286
});
287
return options;
288
},
289
// Response interceptor
290
(response) => {
291
console.log('Incoming response:', {
292
status: response.statusCode,
293
headers: response.headers,
294
bodySize: response.body?.length
295
});
296
return response;
297
}
298
);
299
300
const client = await createClientAsync("http://example.com/service.wsdl", {
301
httpClient: loggingHttpClient
302
});
303
```
304
305
### Custom HTTP Agents
306
307
Configure custom HTTP/HTTPS agents for connection pooling and advanced networking options.
308
309
```typescript { .api }
310
/**
311
* HTTP agent configuration for connection management
312
*/
313
interface IAgentOptions {
314
/** Keep connections alive */
315
keepAlive?: boolean;
316
/** Keep alive initial delay */
317
keepAliveInitialDelay?: number;
318
/** Maximum number of sockets per host */
319
maxSockets?: number;
320
/** Maximum number of free sockets per host */
321
maxFreeSockets?: number;
322
/** Timeout for socket connections */
323
timeout?: number;
324
/** Free socket timeout */
325
freeSocketTimeout?: number;
326
}
327
```
328
329
**Usage Examples:**
330
331
```typescript
332
import * as https from 'https';
333
import * as http from 'http';
334
335
// Custom HTTPS agent with connection pooling
336
const httpsAgent = new https.Agent({
337
keepAlive: true,
338
maxSockets: 10,
339
timeout: 30000,
340
rejectUnauthorized: false
341
});
342
343
const httpClient = new HttpClient({
344
httpsAgent: httpsAgent,
345
timeout: 60000
346
});
347
348
// Custom HTTP agent for non-SSL connections
349
const httpAgent = new http.Agent({
350
keepAlive: true,
351
maxSockets: 5
352
});
353
354
const httpClientWithAgent = new HttpClient({
355
httpAgent: httpAgent,
356
httpsAgent: httpsAgent
357
});
358
```
359
360
## Utility Functions
361
362
### XML Processing Utilities
363
364
Utility functions for XML processing, namespace handling, and data escaping.
365
366
```typescript { .api }
367
/**
368
* Escape XML entities in object values
369
* @param obj - Object containing values to escape
370
* @returns Object with XML-escaped string values
371
*/
372
function xmlEscape(obj: any): any;
373
374
/**
375
* Find namespace prefix for given URI
376
* @param xmlnsMapping - Namespace mapping object
377
* @param nsURI - Namespace URI to find prefix for
378
* @returns Namespace prefix or empty string
379
*/
380
function findPrefix(xmlnsMapping: any, nsURI: any): string;
381
382
/**
383
* Split qualified name into prefix and local name
384
* @param nsName - Qualified name (e.g., "ns1:ElementName")
385
* @returns Object with prefix and name properties
386
*/
387
function splitQName<T>(nsName: T): { prefix: string; name: T | string };
388
```
389
390
**Usage Examples:**
391
392
```typescript
393
import { xmlEscape, findPrefix, splitQName } from "soap";
394
395
// XML escaping
396
const userInput = {
397
name: "John & Jane's Company",
398
description: '<script>alert("xss")</script>'
399
};
400
401
const escaped = xmlEscape(userInput);
402
console.log(escaped);
403
// {
404
// name: "John & Jane's Company",
405
// description: "<script>alert("xss")</script>"
406
// }
407
408
// Use in SOAP call
409
const result = await client.CreateUserAsync(escaped);
410
411
// Namespace utilities
412
const nsMapping = {
413
'ns1': 'http://example.com/service',
414
'ns2': 'http://example.com/types'
415
};
416
417
const prefix = findPrefix(nsMapping, 'http://example.com/service');
418
console.log(prefix); // 'ns1'
419
420
// Split qualified name
421
const qname = splitQName('ns1:GetUserInfo');
422
console.log(qname); // { prefix: 'ns1', name: 'GetUserInfo' }
423
```
424
425
## Advanced HTTP Features
426
427
### Connection Pooling
428
429
Optimize performance with HTTP connection pooling for high-throughput scenarios.
430
431
```typescript
432
import * as https from 'https';
433
434
// Configure agent with connection pooling
435
const poolingAgent = new https.Agent({
436
keepAlive: true,
437
keepAliveInitialDelay: 1000,
438
maxSockets: 50,
439
maxFreeSockets: 10,
440
timeout: 30000,
441
freeSocketTimeout: 15000
442
});
443
444
const httpClient = new HttpClient({
445
httpsAgent: poolingAgent
446
});
447
```
448
449
### Request Retry Logic
450
451
Implement request retry logic for handling transient network failures.
452
453
```typescript
454
class RetryHttpClient implements IHttpClient {
455
constructor(
456
private maxRetries: number = 3,
457
private retryDelay: number = 1000
458
) {}
459
460
request(url: any, data: any, callback: Function, headers?: any, options?: any) {
461
let attempts = 0;
462
463
const attemptRequest = () => {
464
attempts++;
465
466
// Make HTTP request using underlying implementation
467
this.makeRequest(url, data, (error, response, body) => {
468
if (error && attempts < this.maxRetries) {
469
setTimeout(attemptRequest, this.retryDelay * attempts);
470
return;
471
}
472
473
callback(error, response, body);
474
}, headers, options);
475
};
476
477
attemptRequest();
478
}
479
480
private makeRequest(url: any, data: any, callback: Function, headers?: any, options?: any) {
481
// Actual HTTP request implementation
482
}
483
}
484
```
485
486
### Response Compression
487
488
Handle compressed responses for improved performance over slow networks.
489
490
```typescript
491
const httpClient = new HttpClient({
492
headers: {
493
'Accept-Encoding': 'gzip, deflate'
494
}
495
});
496
```