Typescript中的Http请求

import * as http from 'http';

export class HttpRequest{
url: string;
private path: string;
private host: string;
private args: Array<Array<string>>;

constructor(url: string, args?: string){
    this.url = url;
    this.processUrl(this.url);
    if(!!args){
        this.processArgs(args);
    }
    this.args = [];
}
private processUrl(url: string): void {
    let tld: number = url.lastIndexOf('.')
    let sep: number = url.indexOf('/', tld);
    this.host = url.slice(0, sep);
    this.path = url.slice(sep+1);
}
private processArgs(args: string): void {
    let sep: number = args.indexOf('&');
    if(sep < 0){
        return ;
    }
    let argpair: string = args.slice(0, sep);
    let apsep: number = argpair.indexOf('=');
    let k: string = argpair.slice(0, apsep);
    let v: string = argpair.slice(apsep+1);
    this.args.push([k,v]);
    this.processArgs(args.slice(sep+1));
}
private preparePath(): string {
    let path: string = `?`;
    this.args.forEach((arg: Array<string>, i: number): void => {
        let k: string = arg[0];
        let v: string = arg[1];
        path += k + '=' + v;
        if(i == this.args.length-1){
            return ;
        }
        path += '&';
    });
    return path;
}
public addArg(key: string, value: string): void {
    try{
        this.args.push([key,value]);
    } catch(err) {
        console.log(err);
    }
}
public addArgs(args: Array<Array<string>>): void {
    args.forEach((arg: Array<string>): void => {
        this.args.push(arg);
    });
}
public get(cb: (res: any) => any): void {
    let opts = {
        'host': this.host,
        'path': `/${this.path}/${this.preparePath()}`
    };
    http.request(opts, (r: http.IncomingMessage): void => {
        let data = '';
        r.on('data', (chunk: string): void => {
            console.log('Got chunk: ' + chunk);
            data += chunk;
        });
        r.on('end', (): void =>{
            console.log('Response has ended');
            console.log(data);
            cb(data);
        });
        r.on('error', (err): void => {
            console.log('Following error occured during request:\n');
            console.log(err);
        })
    }).end();
}
public test(): void {
    console.log(this.preparePath());
    console.log(`/${this.path}/${this.preparePath()}`);
}
}

调用:

/ Test httpRequest

import { HttpRequest } from './httpRequest';

const request = new HttpRequest('www.random.org/integers');
request.addArg('num', '1');
request.addArg('min', '1');
request.addArg('max', '50');
request.addArg('col', '1');
request.addArg('base', '10');
request.addArg('format', 'plain');
request.addArg('rnd', 'new');
request.test();
request.get((res: string): void => {
    console.log('Response received: ' + res);
});

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值