## 发送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)
})
})
```