nodejs利用http模块实现银行卡所属银行查询和骚扰电话验证


nodejs利用http模块实现银行卡所属银行查询和骚扰电话验证 - SniffRose - 博客园 var currentBlogApp = 'zmxmumu', cb_enable_mathjax=false;var isLogined=false;

nodejs利用http模块实现银行卡所属银行查询和骚扰电话验证

http模块内部封装了http服务器和客户端,因此Node.js不需要借助Apache、IIS、Nginx、Tomcat等传统HTTP服务器,就可以构建http服务器,亦可以用来做一些爬虫。下面简单介绍该模块的使用,其具体API,大家可以自行去nodejs官方文档查看。

1、http.Server服务器

使用http.createServer([requestListener])方法创建一个http服务器,该方法返回一个新的http.Server实例,如果指定了requestListener,则会自动添加request事件。http.Server继承于net.Server,故默认拥有很多的属性、方法和事件,如下图所示(只给出部分):
server类
使用如下所示:

const http = require('http');
const server = http.createServer();
server.on('request', (req, res) => {
    res.writeHead(200, {
        'content-type': 'text/plain'
    });
    res.end('hello world');
});
server.on('listening', () => {
    console.log(`Server is lintening on ${server.address().address}:${server.address().port}`);
});
server.listen(3000);

代码中的request事件监听的参数req,res分别是http.IncomingMessagehttp.ServerResponse的实例,IncomingMessage对象是由 http.Server 或 http.ClientRequest 创建,并且被自动添加到'request' and 'response' 事件监听函数的第一个参数,是一个可读流,主要包括一些状态信息,请求信息,属性如下所示:

ServerResponse对象是HTTP server内部创建,并作为request事件监听函数的第二个参数,实现了可写流,决定返回给客户端的内容,属性如下所示:

创建一个http服务器,并监听3000端口,用浏览器打开http://127.0.0.1:3000浏览,即可看到hello world
我们还可以创建一个简易的路由,对用户的请求进行处理,如下所示:

//router.js
module.exports = router;
function router(req,res,pathname,handle){
    if(typeof handle[pathname] === 'function'){
        return handle[pathname](req,res);
    }else{
        res.writeHead(200,{'Content-Type':'text/html'});
        res.end('The request is not found!');
    }
}
//handle.js
const dns = require('dns');
const fs = require('fs');
const qs   = require('querystring');
function showIndex(req,res){
    ...
}
function lookup(req,res){
    ...
}
exports['/'] = showIndex;
exports['/dnslookup'] = lookup;

2、http.ClientRequest客户端

该对象通过http.request()http.get()方法创建,可以作为一个向服务器发起请求的客户端,该对象的属性(只列出部分)如下:

http.request(options[, callback])方法使用
参数options可以是一个对象或字符串,如果是字符串则会自动调用url.parse()进行解析,包涵以下属性(部分):

protocol,协议,默认为http: host,主机地址 hostname,主机名 family,IP版本 port,端口 method,请求方法 path ,路径 headers ,请求头 timeout ,超时时间

callback会自动添加给reponse事件监听,返回值为http.ClientRequest,下面利用该知识写一个利用支付宝接口查询银行卡号所属银行,不过http换成了https,接口一致,代码如下:

const https = require('https');
const banknames = require('./bankname.js');
const btypes = {
    DC: '借记卡',
    CC: '信用卡'
};
var baseUrl = 'https://ccdcapi.alipay.com/validateAndCacheCardInfo.json?_input_charset=utf-8&cardBinCheck=true&cardNo=';
var cardNo = process.argv.slice(2)[0];

if (!/^\d{16,}$/.test(cardNo)) {
    console.log(`参数错误,请输入16位以上银行卡号。例如:node http-get.js 6228430120000000000`);
    process.exit(0);
}
baseUrl = baseUrl + cardNo;
const client = https.get(baseUrl, (res) => {
    const status = res.statusCode;
    const type = res.headers['content-type'];
    let msg = '';
    let data = '';
    if (status !== 200) {
        msg = '发送请求失败 code:' + statusCode;
    } else if (!/^application\/json/.test(type)) {
        msg = '返回的数据格式不正确,应返回JSON';
    }
    if (msg != '') {
        console.log(msg);
        process.exit(0);
    }
    res.setEncoding('utf8');
    res.on('data', (chunk) => {
        data += chunk;
    });
    res.on('end', () => {
        try {
            let bankObj = JSON.parse(data);
            dealBankObj(bankObj);
        } catch (e) {
            console.log(e.message);
        }
    });
});
client.on('error', (err) => {
    console.log(err.message);
});

function dealBankObj(obj) {
    const bname = banknames[obj['bank']];
    const btype = obj['cardType'];
    const cardId = obj['key'];

    console.log(`卡号:${cardNo}\r\n银行:${bname}\r\n类型:${btypes[btype]}`);
}

bankname.js

const banknames = {
  "SRCB": "深圳农村商业银行", 
  "BGB": "广西北部湾银行", 
  "SHRCB": "上海农村商业银行", 
  "BJBANK": "北京银行", 
  "WHCCB": "威海市商业银行", 
  "BOZK": "周口银行", 
  "KORLABANK": "库尔勒市商业银行", 
  "SPABANK": "平安银行", 
  "SDEB": "顺德农商银行", 
  "HURCB": "湖北省农村信用社", 
  "WRCB": "无锡农村商业银行", 
  "BOCY": "朝阳银行", 
  "CZBANK": "浙商银行", 
  "HDBANK": "邯郸银行", 
  "BOC": "中国银行", 
  "BOD": "东莞银行", 
  "CCB": "中国建设银行", 
  "ZYCBANK": "遵义市商业银行", 
  "SXCB": "绍兴银行", 
  "GZRCU": "贵州省农村信用社", 
  "ZJKCCB": "张家口市商业银行", 
  "BOJZ": "锦州银行", 
  "BOP": "平顶山银行", 
  "HKB": "汉口银行", 
  "SPDB": "上海浦东发展银行", 
  "NXRCU": "宁夏黄河农村商业银行", 
  "NYNB": "广东南粤银行", 
  "GRCB": "广州农商银行", 
  "BOSZ": "苏州银行", 
  "HZCB": "杭州银行", 
  "HSBK": "衡水银行", 
  "HBC": "湖北银行", 
  "JXBANK": "嘉兴银行", 
  "HRXJB": "华融湘江银行", 
  "BODD": "丹东银行", 
  "AYCB": "安阳银行", 
  "EGBANK": "恒丰银行", 
  "CDB": "国家开发银行", 
  "TCRCB": "江苏太仓农村商业银行", 
  "NJCB": "南京银行", 
  "ZZBANK": "郑州银行", 
  "DYCB": "德阳商业银行", 
  "YBCCB": "宜宾市商业银行", 
  "SCRCU": "四川省农村信用", 
  "KLB": "昆仑银行", 
  "LSBANK": "莱商银行", 
  "YDRCB": "尧都农商行", 
  "CCQTGB": "重庆三峡银行", 
  "FDB": "富滇银行", 
  "JSRCU": "江苏省农村信用联合社", 
  "JNBANK": "济宁银行", 
  "CMB": "招商银行", 
  "JINCHB": "晋城银行JCBANK", 
  "FXCB": "阜新银行", 
  "WHRCB": "武汉农村商业银行", 
  "HBYCBANK": "湖北银行宜昌分行", 
  "TZCB": "台州银行", 
  "TACCB": "泰安市商业银行", 
  "XCYH": "许昌银行", 
  "CEB": "中国光大银行", 
  "NXBANK": "宁夏银行", 
  "HSBANK": "徽商银行", 
  "JJBANK": "九江银行", 
  "NHQS": "农信银清算中心", 
  "MTBANK": "浙江民泰商业银行", 
  "LANGFB": "廊坊银行", 
  "ASCB": "鞍山银行", 
  "KSRB": "昆山农村商业银行", 
  "YXCCB": "玉溪市商业银行", 
  "DLB": "大连银行", 
  "DRCBCL": "东莞农村商业银行", 
  "GCB": "广州银行", 
  "NBBANK": "宁波银行", 
  "BOYK": "营口银行", 
  "SXRCCU": "陕西信合", 
  "GLBANK": "桂林银行", 
  "BOQH": "青海银行", 
  "CDRCB": "成都农商银行", 
  "QDCCB": "青岛银行", 
  "HKBEA": "东亚银行", 
  "HBHSBANK": "湖北银行黄石分行", 
  "WZCB": "温州银行", 
  "TRCB": "天津农商银行", 
  "QLBANK": "齐鲁银行", 
  "GDRCC": "广东省农村信用社联合社", 
  "ZJTLCB": "浙江泰隆商业银行", 
  "GZB": "赣州银行", 
  "GYCB": "贵阳市商业银行", 
  "CQBANK": "重庆银行", 
  "DAQINGB": "龙江银行", 
  "CGNB": "南充市商业银行", 
  "SCCB": "三门峡银行", 
  "CSRCB": "常熟农村商业银行", 
  "SHBANK": "上海银行", 
  "JLBANK": "吉林银行", 
  "CZRCB": "常州农村信用联社", 
  "BANKWF": "潍坊银行", 
  "ZRCBANK": "张家港农村商业银行", 
  "FJHXBC": "福建海峡银行", 
  "ZJNX": "浙江省农村信用社联合社", 
  "LZYH": "兰州银行", 
  "JSB": "晋商银行", 
  "BOHAIB": "渤海银行", 
  "CZCB": "浙江稠州商业银行", 
  "YQCCB": "阳泉银行", 
  "SJBANK": "盛京银行", 
  "XABANK": "西安银行", 
  "BSB": "包商银行", 
  "JSBANK": "江苏银行", 
  "FSCB": "抚顺银行", 
  "HNRCU": "河南省农村信用", 
  "COMM": "交通银行", 
  "XTB": "邢台银行", 
  "CITIC": "中信银行", 
  "HXBANK": "华夏银行", 
  "HNRCC": "湖南省农村信用社", 
  "DYCCB": "东营市商业银行", 
  "ORBANK": "鄂尔多斯银行", 
  "BJRCB": "北京农村商业银行", 
  "XYBANK": "信阳银行", 
  "ZGCCB": "自贡市商业银行", 
  "CDCB": "成都银行", 
  "HANABANK": "韩亚银行", 
  "CMBC": "中国民生银行", 
  "LYBANK": "洛阳银行", 
  "GDB": "广东发展银行", 
  "ZBCB": "齐商银行", 
  "CBKF": "开封市商业银行", 
  "H3CB": "内蒙古银行", 
  "CIB": "兴业银行", 
  "CRCBANK": "重庆农村商业银行", 
  "SZSBK": "石嘴山银行", 
  "DZBANK": "德州银行", 
  "SRBANK": "上饶银行", 
  "LSCCB": "乐山市商业银行", 
  "JXRCU": "江西省农村信用", 
  "ICBC": "中国工商银行", 
  "JZBANK": "晋中市商业银行", 
  "HZCCB": "湖州市商业银行", 
  "NHB": "南海农村信用联社", 
  "XXBANK": "新乡银行", 
  "JRCB": "江苏江阴农村商业银行", 
  "YNRCC": "云南省农村信用社", 
  "ABC": "中国农业银行", 
  "GXRCU": "广西省农村信用", 
  "PSBC": "中国邮政储蓄银行", 
  "BZMD": "驻马店银行", 
  "ARCU": "安徽省农村信用社", 
  "GSRCU": "甘肃省农村信用", 
  "LYCB": "辽阳市商业银行", 
  "JLRCU": "吉林农信", 
  "URMQCCB": "乌鲁木齐市商业银行", 
  "XLBANK": "中山小榄村镇银行", 
  "CSCB": "长沙银行", 
  "JHBANK": "金华银行", 
  "BHB": "河北银行", 
  "NBYZ": "鄞州银行", 
  "LSBC": "临商银行", 
  "BOCD": "承德银行", 
  "SDRCU": "山东农信", 
  "NCB": "南昌银行", 
  "TCCB": "天津银行", 
  "WJRCB": "吴江农商银行", 
  "CBBQS": "城市商业银行资金清算中心", 
  "HBRCU": "河北省农村信用社"
};
module.exports = banknames;

执行结果如下所示:

E:\developmentdocument\nodejsdemo>node http-get.js 6228430120000000000
卡号:6228430120000000000
银行:中国农业银行
类型:借记卡

下面再举一个爬虫例子,利用百度和360搜索的数据,验证电话号码是否骚扰电话,需要cheerio库,该库类似jquery,语法大部分一致,使用npm安装:

npm install cheerio

我们对两个搜索引擎搜索指定电话号码的结果进行分析,如果是骚扰号码则打印出被标记多少次,否则打印其归属地,实现如下所示:

const https = require('https');
const http = require('http');
const url = require('url');
const cheerio = require('cheerio');
const args = process.argv.slice(2);
const num = args[0];

var optionsBD = {
  host: 'www.baidu.com',
  port: 80,
  path: '/s?wd=' + num,
  method: 'GET'
};

var options360 = {
  host: 'www.so.com',
  port: 443,
  path: '/s?q=' + num,
  method: 'GET'
};

if (!/^\d+$/.test(num)) {
  console.log(`参数错误,请输入正确电话号码或查询平台。\r\n例如:node phoneMark.js 15949566632`);
  process.exit(0);
}

function request(protocol, options, cb) {
  return new Promise((resolve, reject) => {
    var req = protocol.request(options, (res) => {
      var html = '';
      res.setEncoding('utf8');
      res.on('data', (chunk) => {
        html += chunk;
      });
      res.on('end', () => {
        resolve(cb(html));
      });
    });
    req.on('error', (err) => {
      reject(err);
    });
    req.end();
  });
}

Promise
  .all([request(http, optionsBD, AnalysizeByBD), request(https, options360, AnalysizeBy360)])
  .then((vals) => {
    summary(vals);
  }, (err) => {
    console.log(err);
  });

function summary(vals) {
  if ((/\d+/g).test(vals[0])) {
    console.log(`号码${num}:为骚扰号码,分别被百度、360标记${vals[0]}${vals[1]}次`);
  } else {
    console.log(`号码${num}${vals[0]}`);
  }
}

function AnalysizeByBD(html) {
  var $ = cheerio.load(html);
  var arr = $('.op_fraudphone_word').text().trim().replace(/\s+/g, "").match(/(\d+)/g)
  return arr ? arr[0] : $('.op_mobilephone_r').find('span').eq(1).text().replace(/\s*/g, "");
}

function AnalysizeBy360(html) {
  var $ = cheerio.load(html);
  return $('.mohe-tips').find('b').text();
}

执行结果如下:

E:\developmentdocument\nodejsdemo>node number.js 15656069453
号码15656069453:为骚扰号码,分别被百度、360标记12、8502次

http模块便介绍到这。



posted @ 2016-12-30 10:00 SniffRose 阅读(...) 评论(...) 编辑 收藏
markdown_highlight();var allowComments=true,cb_blogId=219008,cb_entryId=6235760,cb_blogApp=currentBlogApp,cb_blogUserGuid='637614e3-bece-e411-b908-9dcfd8948a71',cb_entryCreatedDate='2016/12/30 10:00:00';loadViewCount(cb_entryId);
var commentManager = new blogCommentManager();commentManager.renderComments(0);
刷新评论刷新页面返回顶部
fixPostBody(); setTimeout(function () { incrementViewCount(cb_entryId); }, 50); deliverAdT2(); deliverAdC1(); deliverAdC2(); loadNewsAndKb(); loadBlogSignature(); LoadPostInfoBlock(cb_blogId, cb_entryId, cb_blogApp, cb_blogUserGuid); GetPrevNextPost(cb_entryId, cb_blogId, cb_entryCreatedDate); loadOptUnderPost(); GetHistoryToday(cb_blogId, cb_blogApp, cb_entryCreatedDate);
var backTopStr = "
"; $('#sideBar').append(backTopStr); $('.backToTop a').hide(); $(window).scroll(function(){ if($(this).scrollTop()>500){ $('.backToTop a').fadeIn(); }else{ $('.backToTop a').fadeOut(); } }); $('.backToTop a').click(function(){ $('body,html').animate({ scrollTop:0 },800); return false; }); $(document).ready(function(){ console.log($(".feedbackItem").length); }); /*****************百度分享***********************/ window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"2","bdMiniList":["mshare","qzone","tsina","weixin","renren","tqq","kaixin001","douban","sqq","diandian","ty"],"bdPic":"","bdStyle":"1","bdSize":"16"},"slide":{"type":"slide","bdImg":"2","bdPos":"right","bdTop":"205.5"}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];