## 發送http請求的不同方式
在瀏覽器中的url地址欄輸入地址發送http請求
```
//req.headers
<<<
{ host: 'localhost:8080',
connection: 'keep-alive',
'upgrade-insecure-requests': '1',
'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.162 Safari/537.36',
accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'accept-encoding': 'gzip, deflate, br',
'accept-language': 'zh-CN,zh;q=0.9' }
```
瀏覽器可作為客戶端發送http請求,但這并不是唯一能發送http請求的方式
還可以用`curl` 發送http請求
```
//req.headers
<<<
{ host: 'localhost:8080',
'user-agent': 'curl/7.53.0',
accept: '*/*' }
```
利用node構建http客戶端
```
let http = require('http');
// node可以做爬蟲
let options = {
hostname:'localhost'
,port:4000
,path:'/'
,method:'get'
// 告訴服務端我當前要給你發什么樣的數據
,headers:{
// 'Content-Type':'application/json'
'Content-Type':'application/x-www-form-urlencoded'
,'Content-Length':15 //buffer的長度
}
}
let req = http.request(options);
// req.end('{"name":"zfpx"}'); //調用end以后才是真正發送請求
req.end('name=zfpx&&age=9');
let result = [];
req.on('response',function(res){
res.on('data',function(data){
result.push(data);
})
res.on('end',function(data){
let str = Buffer.concat(result);
console.log(str.toString());
})
})
```
還可以把`request()`和`on response`合在一起寫
```
http.get(options,function(res){
let range = res.headers['content-range'];
let total = range.split('/')[1];
let buffers = [];
res.on('data',function(chunk){
buffers.push(chunk);
});
res.on('end',function(){
//將獲取的數據寫入到文件中
ws.write(Buffer.concat(buffers));
setTimeout(function(){
if(pause === false&&start<total){
download();
}
},1000)
})
})
```