it('should get correct env value', function (done) { urllib.request('http://localhost:1988/env', function (err, body, resp) { should.ifError(err); body.toString().should.equal('😂'); resp.statusCode.should.equal(200); urllib.request('http://localhost:1989/env', function (err, body, resp) { should.ifError(err); body.toString().should.equal('😂'); resp.statusCode.should.equal(200); done(); }); }); });
urllib.request(img_url46,{},function(err,img46){ urllib.request(img_url64,{},function(err,img64){ urllib.request(img_url96,{},function(err,img196){ urllib.request(img_url132,{},function(err,img132){ Db.query('update users set user_headimgurl_0=?,user_headimgurl_46=?,user_headimgurl_64=?,' + 'user_headimgurl_96=?,user_headimgurl_132=?,user_status=0,user_nickname=?,user_city=?,user_province=?,user_country=? where user_openid=?', [img0,img46,img64,img196,img132,user.nickname,user.city,user.province,user.country,user.openid],function(err){ config.debug || console.log( err?'获取用户的头像出错'+err:'获取用户的头像成功success'); }); }); }); }); });
it('should slave listen worked', function (done) { urllib.request('http://localhost:1989/', function (err, body, res) { should.not.exist(err); body.toString().should.equal('GET /'); res.statusCode.should.equal(200); urllib.request('http://localhost:1990/', function (err, body, res) { should.not.exist(err); body.toString().should.equal('GET /'); res.statusCode.should.equal(200); done(); }); }); });
OAuth.prototype._getUser = function (options, accessToken, callback) { var url = 'https://api.weixin.qq.com/sns/userinfo'; var info = { access_token: accessToken, openid: options.openid, lang: options.lang ? options.lang : 'en' }; var args = { data: info, dataType: 'json' }; urllib.request(url, args, wrapper(callback)); };
OAuth.prototype.refreshAccessToken = function (refreshToken, callback) { var url = 'https://api.weixin.qq.com/sns/oauth2/refresh_token'; var info = { appid: this.appid, grant_type: 'refresh_token', refresh_token: refreshToken }; var args = { data: info, dataType: 'json' }; urllib.request(url, args, wrapper(processToken(this, callback))); };
exports.getZoneInfo = function(accessKey, bucket, callbackFunc) { var apiAddr = util.format('https://uc.qbox.me/v2/query?ak=%s&bucket=%s', accessKey, bucket); urllib.request(apiAddr, function(respErr, respData, respInfo) { if (respErr) { callbackFunc(respErr, null, null); return; } if (respInfo.statusCode != 200) { //not ok respErr = new Error(respInfo.statusCode + "\n" + respData); callbackFunc(respErr, null, null); return; } var zoneData = JSON.parse(respData); var srcUpHosts = []; var cdnUpHosts = []; var zoneExpire = 0; try { zoneExpire = zoneData.ttl; //read src hosts zoneData.up.src.main.forEach(function(host) { srcUpHosts.push(host); }); if (zoneData.up.src.backup) { zoneData.up.src.backup.forEach(function(host) { srcUpHosts.push(host); }); } //read acc hosts zoneData.up.acc.main.forEach(function(host) { cdnUpHosts.push(host); }); if (zoneData.up.acc.backup) { zoneData.up.acc.backup.forEach(function(host) { cdnUpHosts.push(host); }); } var ioHost = zoneData.io.src.main[0]; var zoneInfo = new conf.Zone(srcUpHosts, cdnUpHosts, ioHost) callbackFunc(null, zoneInfo, zoneExpire); } catch (e) { callbackFunc(e, null, null); } }); }
fs.writeFile(__dirname + '/status.tmp', 'ON', function (error) { should.ok(!error); urllib.request('http:/' + '/localhost:8124/are_you_ok', function (error, data, res) { res.should.have.property('statusCode', 404); res.headers.should.have.property('x-powered-by', x); onoffer.online(); urllib.request('http:/' + '/localhost:8124/are_you_ok', function (error, data, res) { res.should.have.property('statusCode', 200); res.headers.should.have.property('x-powered-by', x); done(); }); }); });
API.prototype.getAccessToken = function (callback) { var that = this; var url = this.prefix + 'token?grant_type=client_credential&appid=' + this.appid + '&secret=' + this.appsecret; urllib.request(url, {dataType: 'json'}, wrapper(function (err, data) { if (err) { return callback(err); } that.token = data.access_token; // 过期时间,因网络延迟等,将实际过期时间提前10秒,以防止临界点 that.expireTime = (new Date().getTime()) + (data.expires_in - 10) * 1000; callback(err, data); })); return this; };
API.prototype[method] = function (filepath, callback) { var form = formstream(); form.file('media', filepath); form.headers({ 'Content-Type': 'application/json' }); var url = this.fileServerPrefix + 'media/upload?access_token=' + this.token + '&type=' + type; urllib.request(url, { dataType: 'json', type: 'POST', headers: form.headers(), stream: form }, wrapper(callback)); };
OAuth.prototype.getAccessToken = function (code, callback) { var url = 'https://api.weixin.qq.com/sns/oauth2/access_token'; var info = { appid: this.appid, secret: this.appsecret, code: code, grant_type: 'authorization_code' }; var args = { data: info, dataType: 'json' }; urllib.request(url, args, wrapper(processToken(this, callback))); };
urllib.request(url, {dataType: 'json'}, function(err, data){ if(err){ throw err; } var openids = data.data.openid; var proxy = new EventProxy(); proxy.after('get_user_info', openids.length, function(users){ res.render('test/index', {layout: false, users: users}); }); for(var i=0, len=openids.length; i<len; i++){ var getUserUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + token.accessToken + "&openid=" + openids[i] + "&lang=zh_CN"; urllib.request(getUserUrl, {dataType: 'json'}, proxy.group('get_user_info')); } });
Strategy.prototype.userProfile = function (params, done) { urllib.request(this._oauth2._userProfileURL + '?sns_token=' + params.sns_token, { headers: { 'Content-Type': 'application/json' }, dataType: 'json' }, function (err, data) { if (data.errcode) { e = new Error(data.errmsg) return done(e) } return done(err, data.user_info) }) }
function executer(task) { var _this = this; mUrllib.request(task.url, {gzip: true, timeout: 20000}) .then(function(result) { return new Promise(function(resolve, reject) { try { var data = result.data.toString(); if(task.dataType == 'html') resolve(mCheerio.load(data)); else if(task.dataType == 'json') resolve(JSON.parse(data)); else resolve(data); } catch (err) { reject(err); } }); }).then(function(data) { var company = task.meta.company; if(task.type == 0) { if(typeof gParsers.parseCates == 'function') gParsers.parseCates(_this, task, data); else { var parseCates = gParsers.parseCates[company] || gParsers.parseCates.default; parseCates(_this, task, data); } } else if(task.type == 1) { if(typeof gParsers.parseProducts == 'function') gParsers.parseProducts(_this, task, data); else { var parseProducts = gParsers.parseProducts[company] || gParsers.parseProducts.default; parseProducts(_this, task, data); } } }).catch(function(err) { console.log(">>Error", err); }).then(function() { _this.done(); }); }
function* _get(url, options, retry) { try { return yield urllib.request(url, options); } catch (err) { retry--; if (retry > 0) { if (RETRY_CODES.indexOf(err.code) >= 0 || err.message.indexOf('socket hang up') >= 0) { debug('retry GET %s, retry left %s', url, retry); return yield _get(url, options, retry); } } throw err; } }
return new Promise(function(resolve, reject) { urllib.request('https://api.weixin.qq.com/sns/oauth2/access_token?appid=' + wechatConfig._appId + '&secret=' + wechatConfig._appScret + '&code=' + code + '&grant_type=authorization_code').then(function(result) { var statusCode = result.res.statusCode; var data = result.data; if (result.res.statusCode == 200) { data = JSON.parse(data.toString()); resolve(data); } }).catch(function(err) { reject(err); }); });
child.once('message', function(message) { if (message === 'listening') { urllib.request('http://localhost:1988/', function (err, body, res) { should.not.exist(err); body.toString().should.equal('GET /'); res.statusCode.should.equal(200); urllib.request('http://localhost:1988/env', function (err, body, resp) { should.ifError(err); body.toString().should.equal('😂'); resp.statusCode.should.equal(200); done(); }); }); } });
urllib.request(url, { agent }).then(r => { assert.equal(r.headers['x-remote-port'], lastPort); assert.equal(r.status, 200); assert.equal(r.headers.connection, 'close'); assert.equal(r.headers['x-current-requests'], '2'); // use new socket again urllib.request(url, { agent }).then(r => { assert.notEqual(r.headers['x-remote-port'], lastPort); assert.equal(r.status, 200); assert.equal(r.headers.connection, 'keep-alive'); assert.equal(r.headers['x-current-requests'], '1'); done(); }).catch(done); }).catch(done);
exports.check = function (source, callback) { var pkgInfo; // try to load package.json try { pkgInfo = require(path.join(source, 'package.json')); } catch(e) { if (e.code == 'MODULE_NOT_FOUND') { return callback(null, {score: 0, info: 'File `package.json` is missing. Skipped checking.'}); } else { return callback(e); } } if (pkgInfo.repository && pkgInfo.repository.type == 'git' && pkgInfo.repository.url) { var github; var isGithubRepo = [ /^https\:\/\/github\.com\/(.*?)\/(.*?)\.git$/, /^git\@github\.com\:(.*?)\/(.*?)\.git$/, /^git\:\/\/github\.com\/(.*?)\/(.*?)\.git$/ ].some(function(exp) { return github = pkgInfo.repository.url.match(exp); }); if (isGithubRepo) { urllib.request('https://api.travis-ci.org/repos/' + github[1] + '/' + github[2], { dataType: 'json' }, function (err, repoInfo, res) { if (err) { return callback(err); } // not found if (repoInfo.file && repoInfo.file == 'not found') { return callback(null, {score: 0, info: 'The repository did not associate with Travis CI. Skipped.'}); } if (repoInfo.last_build_status == 0) { return callback(null, {score: 15}); } else { return callback(null, {score: 5, info: 'Associated with Travis CI but not in passing status.'}); } }); } else { return callback(null, {score: 0, info: 'Git is not a Github Repository. Skipped checking.'}); } } else { return callback(null, {score: 0, info: 'Github url is not specified. Skipped checking.'}); } /**/ };
function request() { if (!checkTime()) { work = false; return; } if (!work) { work = true; wechat.multiSend(config.wechat.user, '开始获取交易!', noop); } urllib.request(config.url, function (err, data) { if (err) { return ; } eval(data.toString()); }); }
fs.stat(filepath, function (err, stat) { if (err) { return callback(err); } var form = formstream(); form.file('media', filepath, path.basename(filepath), stat.size); var url = that.fileServerPrefix + 'media/upload?access_token=' + that.token.accessToken + '&type=' + type; var opts = { dataType: 'json', type: 'POST', timeout: 60000, // 60秒超时 headers: form.headers(), stream: form }; urllib.request(url, opts, wrapper(callback)); });
module.exports = function *() { const getAccessToken = `https://api.weibo.com/oauth2/access_token?client_id=${this.state.config.weibo.app_key}&client_secret=${this.state.config.weibo.app_secret}&grant_type=authorization_code&redirect_uri=${this.state.config.weibo.redirect_uri}&code=${this.query.code}`; let response = yield urllib.request(getAccessToken, {"method": "POST"}); try { let dataObject = JSON.parse(new Buffer(response.data).toString()); dataObject.auth_time = Date.now(); fs.writeFile(`${__dirname}/tmp/token`, JSON.stringify(dataObject), function(err) { if (err) util.log.default(`[${new Date()}] write token failed. ${err}`); }); this.session.weibo.token = dataObject; util.log.default(this.session.weibo.token); } catch(e) {} return this.redirect(`${this.state.config.routerPrefix}/weibo`); }
function doQuery(http_method, endpoint, req_data, http_options_param, callback) { // Add version to resource var endpoint = '/' + get_default_options().apiVersion + endpoint; // Empty http_options (declare) var http_options = {}; // JSON or QueryString var data = req_data; // If method is GET then encode as query string, otherwise as JSON-RPC if (http_method === 'GET') { if (typeof data !== 'string') { data = querystring.stringify(data); } if (data) { // add to resource and empty data endpoint = endpoint + "?" + data; data = ""; } } else if (typeof data !== 'string') { data = JSON.stringify(data); } // Auth with digest only! http_options.digestAuth = get_default_options().apiKey + ':' + get_default_options().apiSecret; // Method http_options.method = http_method; // If method POST then append data if ( http_method === 'POST' || http_method === 'PUT') { http_options.data = data; } client.request(get_default_options().url + endpoint, http_options, function(err, data, res) { if (err) { callback(err, null); } else { var response = {}; response.httpStatusCode = res.statusCode; response.body = JSON.parse(data.toString()); callback(null, response); } }); }
module.exports = function (request, options, callback) { if (typeof options === 'function') { callback = options; options = {}; } options = options || {}; for (var key in DEFAULT_NPM_OPTIONS) { options[key] = options[key] || DEFAULT_NPM_OPTIONS[key]; } var reqOptions = { method: request.method, headers: {}, data: request.data, timeout: request.timeout || 30000, gzip: true }; var npmConfigInfo = parseConfig(options.configFile); if (npmConfigInfo.cookie) { reqOptions.headers.Cookie = npmConfigInfo.cookie; } if (npmConfigInfo.userconfig._auth) { reqOptions.headers.authorization = 'Basic ' + npmConfigInfo.userconfig._auth; } if (reqOptions.data) { reqOptions.headers['Content-Length'] = JSON.stringify(reqOptions.data).length; reqOptions.headers['Content-Type'] = 'application/json'; } var host = options.registry.replace(/\/$/, ''); request.path.replace(/^\//, ''); var url = host + '/' + request.path; urllib.request(url, reqOptions, function (err, data, res) { var parsed = {}; if (err) { return callback(err, parsed, data, res); } try { parsed = JSON.parse(data.toString()); } catch (err) { //ignore } callback(err, parsed, data, res); }); };
function post(requestURI, requestForm, headers, callbackFunc) { //var start = parseInt(Date.now() / 1000); headers = headers || {}; headers['User-Agent'] = headers['User-Agent'] || conf.USER_AGENT; headers['Connection'] = 'keep-alive'; var data = { headers: headers, method: 'POST', dataType: 'json', timeout: conf.RPC_TIMEOUT, gzip: true, // timing: true, }; if (conf.RPC_HTTP_AGENT) { data['agent'] = conf.RPC_HTTP_AGENT; } if (conf.RPC_HTTPS_AGENT) { data['httpsAgent'] = conf.RPC_HTTPS_AGENT; } if (Buffer.isBuffer(requestForm) || typeof requestForm === 'string') { data.content = requestForm; } else if (requestForm) { data.stream = requestForm; } else { data.headers['Content-Length'] = 0; }; var req = urllib.request(requestURI, data, function(respErr, respBody, respInfo) { //var end = parseInt(Date.now() / 1000); // console.log((end - start) + " seconds"); // console.log("queuing:\t" + respInfo.timing.queuing); // console.log("dnslookup:\t" + respInfo.timing.dnslookup); // console.log("connected:\t" + respInfo.timing.connected); // console.log("requestSent:\t" + respInfo.timing.requestSent); // console.log("waiting:\t" + respInfo.timing.waiting); // console.log("contentDownload:\t" + respInfo.timing.contentDownload); callbackFunc(respErr, respBody, respInfo); }); return req; }
it('should rotate a image', function (done) { var url = this.client.imageMogr('qn/fixtures/logo.png', { thumbnail: '!50p', gravity: 'NorthWest', quality: 50, rotate: -50, format: 'gif' }); url.should.match(/\?imageMogr\/v2\/auto\-orient\/thumbnail\/\!50p\/gravity\/NorthWest\/quality\/50\/rotate\/\-50\/format\/gif$/); urllib.request(url, function (err, data, res) { should.not.exist(err); data.length.should.above(0); res.should.status(200); res.should.have.header('Content-Type', 'image/gif'); done(); }); });
BaseService.prototype.getSupplier = function (_id, callBack) { var param = { method: "GET", dataType: "json", data: { supplierId: _id } }; urllib.request(this.supplierUrl, param, function (err, data, res) { if (err) { callBack(err); } else { callBack(err, data); } }); };
async request(api, options) { let data = null; if(options.cacheKey) { data = await this.ctx.cache.get(options.cacheKey); if(data) { return data; } } const opts = Object.assign({ dataType: 'json' }, options); const url = `${this.serverUrl}/${api}`; const request = await urllib.request(url, opts); data = request.data; if(options.cacheKey && data) { await this.ctx.cache.set(options.cacheKey, data, options.cacheExpire); } return data; }
Qiniu.prototype._request = function (url, options, callback) { if (typeof options === 'function') { callback = options; options = { dataType: 'json' }; } // use global default timeout if options.timeout not set. options.timeout = options.timeout || this.options.timeout; urllib.request(url, options, function (err, data, res) { err = utils.handleResponse(err, data, res); if (err) { return callback(err, data, res); } callback(null, data, res); }); };
this.sendMessage = function (option, callback) { if(!util.isFunction(callback)){ throwError('callback function required.'); } // TODO 处理xml数据格式化 urllib.request(this.remote, option, function (err, data, res) { if(err) return callback(err); // 把res.data转换成xml数据 // 把data转换成json/js数据 xml2js.parseString(res.data.toString(),{trim:true}, function (err, result) { res.data = result; data = data.toString(); if(err) return callback(err); return callback(null, data, res); }); }); }
BaseService.prototype.getOrder = function (openId,callBack) { var param = { method: "GET", dataType: "json", data: { deviceId: openId } }; urllib.request(this.getOrderUrl, param, function (err, data, res) { if (err) { callBack(err); } else { callBack(err, data); } }); };