nodejs实现http客户端发送请求,可通过http模块的request()方法实现。一般http消息发送可分为POST、GET、DELETE和PUT,不过此处仅以POST方式进行编写调测。本次编写有index.js和data.js脚本,其中index.js为接口模型调用方法,data.js中则将各可能会使用到的参数值以变量形式收集在一块,这样调测时我们只要对data中各参数值进行修改即可,操作性更强,使用上也更方便。
index.js:
//引入模块
var http = require('http');
var data = require('./data');
const querystring = require('querystring');
//定义请求消息头
var headers = {
'Content-type':'application/json;charset=UTF-8'
};
//定义请求消息url和头部
var options = {
method:'POST',
host:data.data.host,
port:data.data.port,
path:data.data.path,
headers:headers
};
//定义消息body
var body = {
"callerNum":data.data.callerNum,
"relationNum":data.data.relationNum,
"calleeNum":data.data.calleeNum,
"callDirection":data.data.callDirection,
"duration":data.data.duration,
"maxDuration":data.data.maxDuration
};
//发送请求
var req = http.request(options,function(res){
console.log(res.statusCode);
console.log(res.headers);
res.setEncoding('utf-8');
res.on('data',function(chunk){
//输出响应内容
console.log(chunk);
//将chunk转为对象
console.log(JSON.parse(chunk));
//通过对象调用各参数,不发散其他操作
console.log(JSON.parse(chunk).resultcode);
});
});
//监控错误情况时报错
req.on('error',function(e){
console.log(e);
});
//写入请求body内容
req.write(JSON.stringify(body));
//结束请求输入
req.end();
data.js:
exports.data = {
host:'127.0.0.1',
port:'8888',
path:'/bind',
callerNum:"+8613800000021",
relationNum:"+867552800008",
calleeNum:"+8613800000023",
callDirection:0,
duration:0,
maxDuration:0
}
以上就是所有的脚本了,接下来我们进行简单的拨测,不过我们需要一个模拟的服务器,这里可以结合我之前写的通过nodejs实现http服务器来构造一个,然后开两个窗口分别运行服务器和客户端,如下:
客户端发起POST消息,接收响应:
服务器接收POST消息,返回响应: