當前位置: 首頁>>代碼示例>>TypeScript>>正文


TypeScript http.ClientRequest類代碼示例

本文整理匯總了TypeScript中http.ClientRequest的典型用法代碼示例。如果您正苦於以下問題:TypeScript ClientRequest類的具體用法?TypeScript ClientRequest怎麽用?TypeScript ClientRequest使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


在下文中一共展示了ClientRequest類的9個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的TypeScript代碼示例。

示例1: resolve

 return new Promise<string>((resolve, reject) => {
     let parsedUrl: url.Url = url.parse(urlStr);
     let request: ClientRequest = https.request({
         host: parsedUrl.host,
         path: parsedUrl.path,
         agent: getHttpsProxyAgent(),
         rejectUnauthorized: vscode.workspace.getConfiguration().get('http.proxyStrictSSL', true),
         headers: headers
     }, (response) => {
         if (response.statusCode === 301 || response.statusCode === 302) { // If redirected
             // Download from new location
             let redirectUrl: string;
             if (typeof response.headers.location === 'string') {
                 redirectUrl = response.headers.location;
             } else {
                 redirectUrl = response.headers.location[0];
             }
             return resolve(downloadFileToStr(redirectUrl, headers));
         }
         if (response.statusCode !== 200) { // If request is not successful
             return reject();
         }
         let downloadedData: string = '';
         response.on('data', (data) => { downloadedData += data; });
         response.on('error', (error) => { reject(error); });
         response.on('end', () => { resolve(downloadedData); });
     });
     request.on('error', (error) => { reject(error); });
     request.end();
 });
開發者ID:swyphcosmo,項目名稱:vscode-cpptools,代碼行數:30,代碼來源:common.ts

示例2: resolve

 return new Promise<void>((resolve, reject) => {
     let parsedUrl: url.Url = url.parse(urlString);
     let request: ClientRequest = https.request({
         host: parsedUrl.host,
         path: parsedUrl.path,
         agent: util.GetHttpsProxyAgent(),
         rejectUnauthorized: vscode.workspace.getConfiguration().get("http.proxyStrictSSL", true)
     }, (response) => {
         if (response.statusCode == 301 || response.statusCode == 302) {
             let redirectUrl: string | string[];
             if (typeof response.headers.location === "string") {
                 redirectUrl = response.headers.location;
             } else {
                 redirectUrl = response.headers.location[0];
             }
             return resolve(downloadCpptoolsJson(redirectUrl)); // Redirect - download from new location
         }
         if (response.statusCode != 200) {
             return reject();
         }
         let downloadedBytes = 0; // tslint:disable-line
         let cppToolsJsonFile: fs.WriteStream = fs.createWriteStream(util.getExtensionFilePath("cpptools.json"));
         response.on('data', (data) => { downloadedBytes += data.length; });
         response.on('end', () => { cppToolsJsonFile.close(); });
         cppToolsJsonFile.on('close', () => { resolve(); });
         response.on('error', (error) => { reject(); });
         response.pipe(cppToolsJsonFile, { end: false });
     });
     request.on('error', (error) => { reject(); });
     request.end();
 });
開發者ID:appTimesTV,項目名稱:vscode-cpptools,代碼行數:31,代碼來源:abTesting.ts

示例3: uploadProgress

export function uploadProgress(request: ClientRequest, emitter: EventEmitter, uploadBodySize?: number): void {
	const uploadEventFrequency = 150;
	let uploaded = 0;
	let progressInterval: NodeJS.Timeout;

	emitter.emit('uploadProgress', {
		percent: 0,
		transferred: 0,
		total: uploadBodySize
	});

	request.once('error', () => {
		clearInterval(progressInterval);
	});

	request.once('response', () => {
		clearInterval(progressInterval);

		emitter.emit('uploadProgress', {
			percent: 1,
			transferred: uploaded,
			total: uploadBodySize
		});
	});

	request.once('socket', (socket: Socket) => {
		const onSocketConnect = (): void => {
			progressInterval = setInterval(() => {
				const lastUploaded = uploaded;
				/* istanbul ignore next: see #490 (occurs randomly!) */
				const headersSize = (request as any)._header ? Buffer.byteLength((request as any)._header) : 0;
				uploaded = socket.bytesWritten - headersSize;

				// Don't emit events with unchanged progress and
				// prevent last event from being emitted, because
				// it's emitted when `response` is emitted
				if (uploaded === lastUploaded || uploaded === uploadBodySize) {
					return;
				}

				emitter.emit('uploadProgress', {
					percent: uploadBodySize ? uploaded / uploadBodySize : 0,
					transferred: uploaded,
					total: uploadBodySize
				});
			}, uploadEventFrequency);
		};

		/* istanbul ignore next: hard to test */
		if (socket.connecting) {
			socket.once('connect', onSocketConnect);
		} else if (socket.writable) {
			// The socket is being reused from pool,
			// so the connect event will not be emitted
			onSocketConnect();
		}
	});
}
開發者ID:sindresorhus,項目名稱:got,代碼行數:58,代碼來源:progress.ts

示例4: extractChannelTitle

	channels.forEach((channel: IChannel) => {
		let liveUrl: string = channel.url.replace(/^http:\/\//, 'http://live.');
		let request: ClientRequest = http.get(liveUrl, (res: IncomingMessage) => {
			let url: string = channel.url;
			let body: string = "";
			res.setEncoding("utf8");
			res.on("data", (chunk: string) => {
				body += chunk;
			});
			res.on("error", (error: any) => {
				console.log(`Conection Error : ${error.message}`);
			});
			res.on("end", () => {
				let title: string = extractChannelTitle(body);
				let broadcasting: boolean = checkBroadcasting(body);
				if (broadcasting) {
					if (lastChannelBroadcastings[url] === undefined ||
						lastChannelBroadcastings[url] === false) {
						lastChannelBroadcastings[url] = true;
						notifier.notify({
							title: title,
							message: url,
							icon: __dirname + "/../browser/notification.png",
							sound: true,
							wait: true,
						});
						notifier.on("click", (notifierObject: NodeNotifier, options: Notification) => {
							electron.shell.openExternal(options.message + '/live');
						});
					}
				} else {
					lastChannelBroadcastings[url] = false;
				}
				updateTrayIcon();
				if (mainWindow !== undefined) {
					mainWindow.webContents.send("updateChannelStatus", JSON.stringify({
						url: url,
						title: title,
						broadcasting: broadcasting,
					}));
				}
			});
		});
		request.on("error", (error: any) => {
			console.log(`Conection Error : ${error.message}`);
		});
	});
開發者ID:data9824,項目名稱:SavannaAlert,代碼行數:47,代碼來源:main.ts

示例5: addTimeOutHandler

export function addTimeOutHandler(request: ClientRequest, callback: (error: Error) => void) {
  request.on("socket", function (socket: Socket) {
    socket.setTimeout(60 * 1000, () => {
      callback(new Error("Request timed out"))
      request.abort()
    })
  })
}
開發者ID:MatthijsvandenBosch,項目名稱:electron-builder,代碼行數:8,代碼來源:httpRequest.ts

示例6: runPostRequest

function runPostRequest(host:string, path:string, body:string, callback:(ClientResponse)=>void) {
    const options = {
        hostname: host,
        port: 3000,
        path: path,
        method: 'POST',
        headers: {
            'Content-Type': 'text/plain',
            'Content-Length': Buffer.byteLength(body)
        }
    };
    let request:ClientRequest = http.request(options, callback);
    request.on('error', traceErrorIfPresent);
    var splittedBody:Array<string> = body.split('');
    while (splittedBody.length > 0) {
        request.write(splittedBody.splice(0, 15).join(''));
    }
    request.end();
}
開發者ID:jan-osch,項目名稱:nodexplore,代碼行數:19,代碼來源:simple-server.js.ts

示例7:

 return new Promise<number>((resolve, reject)=> {
     request.once('response', (msg: IncomingMessage) => {
         this._getLengthFromHeaders(msg.headers)
             .then(resolve)
             .catch(reject);
     });
 });
開發者ID:Kuchasz,項目名稱:smart-downloader,代碼行數:7,代碼來源:Downloader.ts

示例8: it

    it('should reject on request error', done => {
      (api as any).request('method', 'path').catch((err: any) => {
        expect(err).toBe('Test');
        done();
      });

      latestRequest.emit('error', 'Test');
    });
開發者ID:JohnnyQQQQ,項目名稱:angular,代碼行數:8,代碼來源:github-api.spec.ts

示例9: addTimeout

	request.once('socket', (socket: net.Socket): void => {
		const {socketPath} = request as any;

		/* istanbul ignore next: hard to test */
		if (socket.connecting) {
			if (delays.lookup !== undefined && !socketPath && !net.isIP(hostname || host)) {
				const cancelTimeout = addTimeout(delays.lookup, timeoutHandler, 'lookup');
				socket.once('lookup', cancelTimeout);
			}

			if (delays.connect !== undefined) {
				const timeConnect = () => addTimeout(delays.connect!, timeoutHandler, 'connect');

				if (socketPath || net.isIP(hostname || host)) {
					socket.once('connect', timeConnect());
				} else {
					socket.once('lookup', (error: Error): void => {
						if (error === null) {
							socket.once('connect', timeConnect());
						}
					});
				}
			}

			if (delays.secureConnect !== undefined && options.protocol === 'https:') {
				socket.once('connect', (): void => {
					const cancelTimeout = addTimeout(delays.secureConnect!, timeoutHandler, 'secureConnect');
					socket.once('secureConnect', cancelTimeout);
				});
			}
		}

		if (delays.send !== undefined) {
			const timeRequest = () => addTimeout(delays.send!, timeoutHandler, 'send');
			/* istanbul ignore next: hard to test */
			if (socket.connecting) {
				socket.once('connect', (): void => {
					request.once('upload-complete', timeRequest());
				});
			} else {
				request.once('upload-complete', timeRequest());
			}
		}
	});
開發者ID:sindresorhus,項目名稱:got,代碼行數:44,代碼來源:timed-out.ts


注:本文中的http.ClientRequest類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。