forked from nondanee/UnblockNeteaseMusic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrequest.js
101 lines (95 loc) · 2.47 KB
/
request.js
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
const zlib = require('zlib')
const url = require('url')
const http = require('http')
const https = require('https')
function init(method, urlObj, extraHeaders){
var headers = {
'Host': urlObj.host
'Accept': 'application/json, text/plain, */*',
'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'zh-CN,zh;q=0.9',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36'
}
if(typeof(extraHeaders) != 'undefined'){
for(var key in extraHeaders){
headers[key] = extraHeaders[key]
}
}
var options = {method: method, headers: headers}
if(proxy){
options.hostname = switchHost(proxy.hostname)
options.port = proxy.port || ((proxy.protocol == 'https:') ? 443 : 80)
options.path = urlObj.protocol + '//' + switchHost(urlObj.hostname) + urlObj.path
}
else{
options.hostname = switchHost(urlObj.hostname)
options.port = urlObj.port || ((urlObj.protocol == 'https:') ? 443 : 80)
options.path = urlObj.path
}
return options
}
function make(urlObj){
if(proxy)
return (proxy.protocol == 'https:' ? https.request : http.request)
else
return (urlObj.protocol == 'https:' ? https.request : http.request)
}
function request(method, uri, extraHeaders, body, raw){
var urlObj = url.parse(uri)
var options = init(method, urlObj, extraHeaders)
var makeRequest = make(urlObj)
return new Promise(function(resolve, reject){
var req = makeRequest(options, function(res){
if(method == 'HEAD')
resolve(res)
else
read(res, raw).then(function(body){resolve(body)}).catch(function(e){reject(e)})
}).on('error', function(e){
reject(e)
})
if(typeof(body) != 'undefined'){
req.write(body)
}
req.end()
})
}
function read(connect, raw){
return new Promise(function(resolve, reject){
var chunks = []
if(connect.headers['content-encoding'] == 'gzip'){
var gunzip = zlib.createGunzip()
connect.pipe(gunzip)
gunzip.on('data', function(chunk){
chunks.push(chunk)
})
gunzip.on('end', function(){
end()
})
gunzip.on('error', function(e){
reject(e)
})
}
else{
connect.on('data', function(chunk){
chunks.push(chunk)
})
connect.on('end', function(){
end()
})
connect.on('error', function(e){
reject(e)
})
}
function end(){
var buffer = Buffer.concat(chunks)
if(raw == true)
resolve(buffer)
else
resolve(buffer.toString())
}
})
}
request.init = init
request.make = make
request.read = read
module.exports = request