1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
| var httpServer = require("http"); var queryString = require("querystring");
class Http{ constructor(){ this.params = {}; this.isPost = false; this.req = null; this.hostname = ''; this.port = 80; this.urlPath = ''; this.protocol = 'http:'; this.timeout = 10000; this.headers = {}; }
setParams(params){ this.params = queryString.stringify(params); }
setHostName(hostname){ this.hostname = hostname; }
setUrlPath(path){ this.urlPath = path; }
setIsPost(isPost){ this.isPost = isPost; }
setPort(port){ this.port = port; }
setProtocol(protocol){ this.protocol = protocol; }
setTimeout(timeout){ this.timeout = timeout; }
setHeader(headers){ this.headers = headers; }
sendRequest(){ let options = { protocol:this.protocol, hostname:this.hostname, port: this.port, path: this.urlPath, method: "GET", timeout:this.timeout, headers:this.headers } if (this.isPost) { options.method = "POST"; options.headers['Content-Type'] = "application/x-www-form-urlencoded"; options.path = this.urlPath; options.headers['Content-Length'] = Buffer.byteLength(this.params); } else { options.path = this.urlPath + "?" + this.params; } return new Promise((resolve, reject)=>{ this._request(options).then((res)=>{ this._getResponse(res).then((chunk)=>{ resolve(chunk.toString()); }); }).catch((msg)=>{ reject(msg); }); this._requestStatus().then((err)=>{ reject(err); }); }); }
_getResponse(res){ return new Promise((resolve, reject)=>{ res.on("data", (chunk) => { resolve(chunk); }); }); }
_requestStatus(){ return new Promise((resolve, reject)=>{ this.req.on('error', function (e) { resolve(e); }); if (this.isPost) { this.req.write(this.params); } this.req.end(); }); }
_request(options){ return new Promise((resolve, reject)=>{ this.req = httpServer.request(options, (res)=>{ if (res) { resolve(res); } else { reject("请求失败"); } }); }); } }
module.exports = Http;
|