想用nodejs写个微博客户端发微博,无奈新浪微博的nodejs sdk是OAuth1.0的。
只能自己根据OAuth1.0 改了改。
只写了statuses/update 和 statuses/upload,其他的实现基本都类似了。
update是简单参数的post,upload是multipart 包含二进制图片的post。
改改帐号参数和发送的图片路径,node weibotest.js就能成功发送了。
如果中文出现乱码,请把这两个js文件保存成utf-8编码。

weibo.js
var querystring = require('querystring'), crypto = require('crypto'), https = require('https'), URL = require('url'), path = require('path'), fs = require('fs'); var apiprefix = 'https://api.weibo.com/2/', appkey = '2849184197', appsecret = '7338acf99a00412983f255767c7643d0'; var userId = "微博帐号", passwd = "微博密码"; var baseurl = "https://api.weibo.com/2/"; var weibo = module.exports = function() { this._accesstoken = ""; this._accessTokenName = "access_token"; }; weibo.prototype = { //oauth2/authorize getAuthorize: function(callback) { var params = {}; params['client_id'] = appkey; // appkey params['redirect_uri'] = ""; // oauth2 回调地址 params['response_type'] = "code"; params['action'] = "submit"; params['userId'] = userId; // 微博帐号 params['passwd'] = passwd; // 帐号密码 var post_data = querystring.stringify(params); var post_headers = { 'Content-Type': 'application/x-www-form-urlencoded' }; var url = apiprefix + "oauth2/authorize"; //https request var m = "POST"; var code = ""; var tt = this; this._request(m, url, post_headers, post_data, null, function(error, body, response) { if (error) { console.log("error:" + error); } else { code = response.headers.location.substr(6); console.log("code:" + code); tt.getAccesstoken(code, function(err, access_token, refresh_token) { console.log(access_token); tt._accesstoken = access_token; callback(err, access_token, refresh_token); }); } }); }, //oauth2/access_token getAccesstoken: function(code, callback) { var params = {}; params['grant_type'] = "authorization_code"; // appkey params['redirect_uri'] = ""; // oauth2 回调地址 params['client_id'] = appkey; params['client_secret'] = appsecret; params['code'] = code; var post_data = querystring.stringify(params); var post_headers = { 'Content-Type': 'application/x-www-form-urlencoded', "contentType":"text/html;charset=uft-8" }; var url = apiprefix + "oauth2/access_token"; //https request var m = "POST"; this._request(m, url, post_headers, post_data, null, function(error, data, response) { if (error) callback(error); else { var results; try { // As of http://tools.ietf.org/html/draft-ietf-oauth-v2-07 // responses should be in JSON results = JSON.parse(data); } catch(e) { // .... However both Facebook + Github currently use rev05 of the spec // and neither seem to specify a content-type correctly in their response headers :( // clients of these services will suffer a *minor* performance cost of the exception // being thrown results = querystring.parse(data); } var access_token = results["access_token"]; var refresh_token = results["refresh_token"]; delete results["refresh_token"]; callback(null, access_token, refresh_token); } }); }, //通用https request,从node-oauth上oauth2摘出来的 _request: function(method, url, headers, post_body, access_token, callback) { var creds = crypto.createCredentials({}); var parsedUrl = URL.parse(url, true); if (parsedUrl.protocol == "https:" && !parsedUrl.port) parsedUrl.port = 443; var realHeaders = {}; if (headers) { for (var key in headers) { realHeaders[key] = headers[key]; } } realHeaders['Host'] = parsedUrl.host; if (Buffer.isBuffer(post_body)) { realHeaders['Content-Length'] = post_body ? post_body.length: 0; } else { realHeaders['Content-Length'] = post_body ? Buffer.byteLength(post_body) : 0; } if (access_token) { if (!parsedUrl.query) parsedUrl.query = {}; parsedUrl.query[this._accessTokenName] = access_token; } var result = ""; var queryStr = querystring.stringify(parsedUrl.query); if (queryStr) queryStr = "?" + queryStr; var options = { host: parsedUrl.hostname, port: parsedUrl.port, path: parsedUrl.pathname + queryStr, method: method, headers: realHeaders }; // Some hosts *cough* google appear to close the connection early / send no content-length header // allow this behaviour. var allowEarlyClose = false; var callbackCalled = false; function passBackControl(response, result) { if (!callbackCalled) { callbackCalled = true; if (response.statusCode != 200 && (response.statusCode != 301) && (response.statusCode != 302)) { callback({ statusCode: response.statusCode, data: result }); } else { callback(null, result, response); } } } console.log("options:"); console.log(options); var request = https.request(options, function(response) { response.on("data", function(chunk) { result += chunk }); response.on("close", function(err) { if (allowEarlyClose) { passBackControl(response, result); } }); response.addListener("end", function() { passBackControl(response, result); }); }); request.on('error', function(e) { callbackCalled = true; callback(e); }); if (method == 'POST' && post_body) { request.write(post_body); } request.end(); }, //普通post,执行类似statuses/update.json post: function(url, params, callback) { if (!this._accesstoken) return callback("not authorize"); var post_data = querystring.stringify(params); var post_headers = { 'Content-Type': 'application/x-www-form-urlencoded' }; if (params.ContentType) { post_headers['Content-Type'] = params.ContentType; } this._request("POST", baseurl + url + '.json', post_headers, post_data, this._accesstoken, callback); }, /********** statuses *********/ //statuses/repost 转发一条微博信息 //statuses/destroy 删除微博信息 //statuses/update 发布一条微博信息 //statuses/upload 上传图片并发布一条微博 //statuses/upload_url_text 发布一条微博同时指定上传的图片或图片url //emotions 获取官方表情 repost: function(args, callback) { /* args参数: * id : 微博id * status : 转发文本 * is_comment 0-不发评论 1-发评论给当前微博 2-发评论给原微博 3-都发 */ if (!args.id) return callback('missing argument id'); this.post('statuses/repost', args, callback); }, update: function(params, callback) { if (!params.status) return callback('missing argument status'); this.post('statuses/update', params, callback); }, FILE_CONTENT_TYPES: { '.gif': 'image/gif', '.jpeg': 'image/jpeg', '.jpg': 'image/jpeg', '.png': 'image/png' }, //获取文件信息,用于statuses/upload 上传图片并发布一条微博 fileinfo: function(file) { var name, content_type; if (typeof(file) === 'string') { var ext = path.extname(file); content_type = this.FILE_CONTENT_TYPES[ext]; name = path.basename(file); } else { name = file.name || file.fileName; content_type = file.fileType || file.type; } return { name: name, content_type: content_type }; }, /** * 上传图片 * pic: filepath * callback: finish callback function **/ upload: function(params, callback) { if (!params.status) return callback('missing argument status'); var pic = params.pic; var pic_field = 'pic'; var boundary = 'boundary' + (new Date).getTime(); var dashdash = '--'; var crlf = '\r\n'; /* Build RFC2388 string. */ var builder = ''; builder += dashdash; builder += boundary; builder += crlf; //微博文字 builder += 'Content-Disposition: form-data; name="status"'; builder += crlf; builder += crlf; /* Append form data. */ builder += params.status; builder += crlf; /* Write boundary. */ builder += dashdash; builder += boundary; builder += crlf; var fileinfo = this.fileinfo(pic); /* Generate headers. [PIC] */ builder += 'Content-Disposition: form-data; name="' + pic_field + '"'; builder += '; filename="' + fileinfo.name + '"'; builder += crlf; builder += 'Content-Type: ' + fileinfo.content_type + ';'; builder += crlf; builder += crlf; var tt = this; // 处理文件内容 //微博图片 this.read_file(pic, function(file_buffer) { var endstr = crlf + dashdash + boundary + dashdash + crlf, buffer = null; if (typeof(BlobBuilder) === 'undefined') { var builderLength = new Buffer(builder).length; var size = builderLength + file_buffer.length + endstr.length; buffer = new Buffer(size); var offset = 0; buffer.write(builder); offset += builderLength; file_buffer.copy(buffer, offset); offset += file_buffer.length; buffer.write(endstr, offset); } else { buffer = new BlobBuilder(); //NOTE WebKitBlogBuilder buffer.append(builder); buffer.append(pic); buffer.append(endstr); buffer = buffer.getBlob(); } if (!tt._accesstoken) return callback("not authorize"); var post_data = buffer; //必须使用multipart/form-data var post_headers = { 'Content-Type': 'multipart/form-data;boundary=' + boundary }; console.log(builder); tt._request("POST", baseurl + 'statuses/upload' + '.json', post_headers, post_data, tt._accesstoken, callback); }); }, read_file: function(pic, callback) { if (typeof(pic) === 'string') { fs.stat(pic, function(err, stats) { fs.readFile(pic, function(err, file_buffer) { console.log(err); if (!err) callback(file_buffer); }); }); } else { callback(pic); } }, };

weibotest.js

var weibo = require('./weibo'); var wb = new weibo(); wb.getAuthorize(function(err, access_token, refresh_token) { //wb.update({ // "status": "中文不行?" //}, //function(error, body, response) { // if (error) { // console.log("error:"); // console.log(error); // } // else { // console.log("body:" + body); // } //}); wb.upload({ "status": "中文不行?", "pic": "E:/XX.jpg" }, function(error, body, response) { if (error) { console.log("error:"); console.log(error); } else { console.log("body:" + body); } }); });

转载于:https://www.cnblogs.com/marryZhan/archive/2012/02/01/2497563.html

新浪微博 OAuth2 NodeJs发微博相关推荐

  1. Java调用 新浪微博API 接口发微博(包含js微博组件、springMVC新浪登录)详解

    参考自:http://www.myexception.cn/program/1930025.html https://blog.csdn.net/qq_36580777/article/details ...

  2. java 微博sdk_Java基于新浪微博SDK实现发微博的功能

    背景 最近用实现了一个简单的发微博的功能. 新浪微博的SDK已经经历了多次更新,而网上的资料.教程大多还是基于旧版本的,很多细节上有了一些变化.本文将基于最新的新浪微博SDK介绍发微博的过程. 简介 ...

  3. Java调用 新浪微博API 接口发微博,逐项讲解,绝对清晰

    转载自:http://www.myexception.cn/program/1930025.html Java调用 新浪微博API 接口发微博,逐条讲解,绝对清晰 最近要做个课程设计,使用微博控制树莓 ...

  4. 利用java语言在eclipse下实现在新浪微博开发平台发微博(转)

    实现原理: 开发者利用sdk包开发某个应用完成后,该应用与新浪微博服务器连接,通过HTTP数据形式与服务器的API接口交换数据.在开发过程中,亦可实时调试. 各种语言的软件开发包(SDK)http:/ ...

  5. java微博开发_利用java语言在eclipse下实现在新浪微博开发平台发微博(转)

    0    INFO  [2012-06-08 11:00:53]  code: xxxxxxxxxxxxxxxxxx(code的值) 360  DEBUG [2012-06-08 11:00:53]  ...

  6. Java调用 新浪微博API 接口发微博,逐条讲解,绝对清晰

    最近要做个课程设计,使用微博控制树莓派,树莓派再控制发光二极管的亮和灭,主要设计分两层,上层是用Java调用新浪微博API来实现对微博旳监听,当我的微博被回复时能够自动读取评论内容,并根据评论的指令内 ...

  7. pythonurllib新浪微博_Python代码登录新浪微博并自动发微博

    前言 对于很少玩微博@張行之_的我来说,微博内容少的可怜.所以本人就想:能不能写个成功程序来帮我发微博.这个程序要满足以下要求: 自动化,自动登录微博,自动发微博. 微博内容要有意义,不能是随机生成的 ...

  8. 最新JAVA调用新浪微博API之发微博(转)

    最近有个项目中需要调用微博的api发新微博,网上找了很多相关教程,遇到了很多坑.后来给官方发邮件询问才知道微博官方早在2017年3月份就调整了相关接口,取消了网上现有教程中的发送微博的接口(updat ...

  9. Python代码登录新浪微博并自动发微博

    前言 对于很少玩微博@張行之_的我来说,微博内容少的可怜.所以本人就想:能不能写个成功程序来帮我发微博.这个程序要满足以下要求: 自动化,自动登录微博,自动发微博. 微博内容要有意义,不能是随机生成的 ...

最新文章

  1. 有关“优秀工作流引擎”的评价
  2. 安装hive出现的各种问题(这些问题出现在spark连接mysql的时候)
  3. 按照前序遍历和中序遍历构建二叉树
  4. 使用JDBC来实现一个简单的增删改查
  5. 解决谷歌浏览器重复上传同一文件失败的问题
  6. python input函数无法输入字符串_python input输入函数
  7. Linux经常使用到的操作
  8. 掌握好数据分析,99%的企业都不会拒绝你
  9. 关于静态事件 static event 的二三事
  10. 开源免费的录屏gif工具
  11. 《黑客X档案》2006年-2012年全集(PDF格式)
  12. excel制作跨职能流程图_一款在线版流程图工具亿图图示
  13. 全志A40I tina系统蓝牙wifi调试方法
  14. adventure项目案例分析
  15. 安装、选择-如何制作U盘系统盘以及U盘安装操作系统的方法 -by小雨
  16. 雷总:我也想做高级工程师 !
  17. 一缕黑暗中的火光-----------协作图--------------优雅的建模语言
  18. 域服务器禁用无线,无线域服务常见问题
  19. MS08-067利用
  20. Learning to Sample

热门文章

  1. 导航栏的返回文字修改
  2. 二、信息安全之网络安全体系(由浅入深的笔记整理)
  3. 《预训练周刊》第23期:Smart Bird:解决变换器性能瓶颈的新方法
  4. Idea 遇到:com.sun.istack.internal不存在和程序包com.sun.image.codec.jpeg不存在
  5. 软件工程就业方向及前景
  6. FreeBSD 配置经验
  7. 单细胞基因可视化之热图改造修饰1
  8. python项目开发实战第2版pdf_《树莓派开发实战++第2版》.pdf
  9. 【开源】SixChat WebApp 仿微信朋友圈 PHP OR JSP
  10. 宝宝喜欢爬窗户怎么办?