出发点: 微博应该在合适的时间发出去才会有更多的受众看到,比如晚上把微博内容写好,设置早上8点开始逐条发送,基于腾讯微博和新浪微博SDK实现的微博机
实践过程:
1. 发送新浪微博的C++封装
头文件
#pragma once
#define RET_UNKNOW -1
#define RET_OK 0
#define RET_USERID_NULL 1
#define RET_WEIBOID_NULL 2
#define RET_LISTID_NULL 3
#define RET_TAGID_NULL 4
#define RET_TEXT_NULL 5
#define RET_PASSWORD_NULL 6
#define RET_SOURCE_NULL 7///< App key or app secret is null.
#define RET_TOKEN_NULL 8///< Access token or access secret is null.
#define RET_FILEPATH_NULL 9///< File path is null.
#define RET_NOT_IMPL 10///<
#define RET_INVALIDE_PARAM 11
#define RET_INTERNAL_ERROR 12///< Internal error.
#define RET_TASK_EXIST 13///< Already has this task.
class SinaWeiBo
{
public:
SinaWeiBo(void);
~SinaWeiBo(void);
int Init(void);
void UnInit(void);
int SetAccout(char * user, char * password);
void GetUserInfo(char *userId);
int SendWeibo(char * strContent,void *pUserData =0);
int SendWeiboWithImage(char * imgPath, char * strContent,void *pUserData =0);
int GeWeiboByUser(CString strUser,void *pUserData =0);
int RePostWeibo(CString weiboId, CString strComment);
};
CPP文件
#include "StdAfx.h"
#include "SinaWeiBo.h"
#include "make_shared.hpp"
#include <IWeiboDef.hxx>
#include <IWeiboMethod.hxx>
#include "ParsingDefine.hxx"
#include "ParsingDataStruct.h"
#include "AppKey.h"
#include "Browser.h"
#include "CodeLib.h"
//#include <IWeibo.hxx>
//#include <IWeiboMethod.hxx>
//#include <ParsingObject.hxx>
#define LOG_SUPPORT
#ifdef WIN32
#include <windows.h>
#else
#include <iostream>
#endif
using namespace weibo;
#ifdef LOG_SUPPORT
#define DEFAULT_SUBSYSTEM "WeiboSDK_UnitTest"
#include <util/log/Logger.hxx>
#else
#define CerrLog(args_) std::cout
#define StackLog(args_) std::cout
#define DebugLog(args_) std::cout
#define InfoLog(args_) std::cout
#define WarningLog(args_) std::cout
#define ErrLog(args_) std::cout
#define CritLog(args_) std::cout
#endif
struct IDDebugHelper
{
unsigned int optionId;
char *optionIdName;
};
#define HELPER_UNIT(option) { option, #option }
const IDDebugHelper gDebugHelperArray[] =
{
HELPER_UNIT(WBOPT_OAUTH2_ACCESS_TOKEN),
HELPER_UNIT(WBOPT_GET_STATUSES_PUBLIC_TIMELINE),//获取最新更新的公共微博消息
HELPER_UNIT(WBOPT_GET_STATUSES_FRIENDS_TIMELINE),//获取当前用户所关注用户的最新微博信息 (别名: statuses/home_timeline)
HELPER_UNIT(WBOPT_GET_STATUSES_HOME_TIMELINE),//获取当前登录用户及其所关注用户的最新微博消息
HELPER_UNIT(WBOPT_GET_STATUSES_USER_TIMELINE),//获取用户发布的微博信息列表
HELPER_UNIT(WBOPT_GET_STATUSES_TIMELINE_BATCH),//批量获得指定的某一批用户的timeline
HELPER_UNIT(WBOPT_GET_STATUSES_REPOST_TIMELINE),//返回一条微博的最新n条转发微博信息
HELPER_UNIT(WBOPT_GET_STATUSES_REPOST_BYME),//返回用户转发的最新n条微博信息
HELPER_UNIT(WBOPT_GET_STATUSES_MENTIONS),//获取@当前用户的微博列表
HELPER_UNIT(WBOPT_GET_STATUSES_SHOW),//根据ID获取单条微博信息
HELPER_UNIT(WBOPT_GET_STATUSES_SHOW_BATCH),//批量获取微博信息
HELPER_UNIT(WBOPT_GET_STATUSES_QUERYMID),//通过id获取mid
HELPER_UNIT(WBOPT_GET_STATUSES_QUERYID),//通过mid获取id
HELPER_UNIT(WBOPT_GET_STATUSES_REPOST_DAILY),//按天返回热门转发榜
HELPER_UNIT(WBOPT_GET_STATUSES_REPOST_WEEKLY),//按周返回热门转发榜
HELPER_UNIT(WBOPT_GET_STATUSES_HOT_COMMENTS_DAILY),//按天返回热门评论榜
HELPER_UNIT(WBOPT_GET_STATUSES_HOT_COMMENTS_WEEKLY),//按周返回热门评论榜
HELPER_UNIT(WBOPT_POST_STATUSES_REPOST),//转发一条微博信息
HELPER_UNIT(WBOPT_POST_STATUSES_DESTROY),//删除微博评论信息
HELPER_UNIT(WBOPT_POST_STATUSES_UPDATE),//发布一条微博信息
HELPER_UNIT(WBOPT_POST_STATUSES_UPLOAD_URL_TEXT),//发布一条微博,同时指定上传的图片或图片url
HELPER_UNIT(WBOPT_POST_STATUSES_UPLOAD),//发布一条微博,上传图片并发布一条微博信息
HELPER_UNIT(WBOPT_GET_COMMENTS_SHOW),//获取某条微博的评论列表
HELPER_UNIT(WBOPT_GET_COMMENTS_BYME),//我发出的评论列表
HELPER_UNIT(WBOPT_GET_COMMENTS_TOME),//我收到的评论列表
HELPER_UNIT(WBOPT_GET_COMMENTS_TIMELINE),//获取当前用户发送及收到的评论列表
HELPER_UNIT(WBOPT_GET_COMMENTS_MENTIONS),//@到我的评论
HELPER_UNIT(WBOPT_GET_COMMENTS_SHOWBATCH),//@批量获取评论内容
HELPER_UNIT(WBOPT_POST_COMMENTS_CREATE),//评论一条微博
HELPER_UNIT(WBOPT_POST_COMMENTS_DESTROY),//删除一条评论
HELPER_UNIT(WBOPT_POST_COMMENTS_DESTROY_BATCH ),//批量删除评论
HELPER_UNIT(WBOPT_POST_COMMENTS_REPLY),//回复一条评论
HELPER_UNIT(WBOPT_GET_DIRECTMESSAGES),//获取当前用户最新私信列表
HELPER_UNIT(WBOPT_GET_DIRECTMESSAGES_SENT),//获取当前用户发送的最新私信列表
HELPER_UNIT(WBOPT_GET_DIRECTMESSAGES_USER_LIST),//获取私信往来用户列表
HELPER_UNIT(WBOPT_GET_DIRECTMESSAGES_CONVERSATION),//获取与指定用户的往来私信列表
HELPER_UNIT(WBOPT_GET_DIRECTMESSAGES_SHOW_BATCH),//批量获取私信内容
HELPER_UNIT(WBOPT_GET_DIRECTMESSAGES_IS_CAPABLE),//判断是否可以给对方发私信
HELPER_UNIT(WBOPT_POST_DIRECTMESSAGES_NEW),//发送一条私信
HELPER_UNIT(WBOPT_POST_DIRECTMESSAGES_DESTORY),//删除一条私信
HELPER_UNIT(WBOPT_POST_DIRECTMESSAGES_DESTORY_BATCH),//批量删除私信
HELPER_UNIT(WBOPT_GET_USERS_SHOW),//获取用户资料
HELPER_UNIT(WBOPT_GET_USERS_DOMAIN_SHOW),//通过个性域名获取用户信息
HELPER_UNIT(WBOPT_GET_USERS_SHOW_BATCH),//批量获取用户信息
HELPER_UNIT(WBOPT_GET_ACCOUNT_PROFILE_BASIC), //获取用户基本信息
HELPER_UNIT(WBOPT_GET_ACCOUNT_PROFILE_EDUCATION), //获取教育信息
HELPER_UNIT(WBOPT_GET_ACCOUNT_PROFILE_EDUCATION_BATCH), //批量获取教育信息
HELPER_UNIT(WBOPT_GET_ACCOUNT_PROFILE_CAREER), //获取职业信息
HELPER_UNIT(WBOPT_GET_ACCOUNT_PROFILE_CAREER_BATCH), //批量获取职业信息
HELPER_UNIT(WBOPT_GET_ACCOUNT_GET_PRIVACY), //获取隐私设置信息
HELPER_UNIT(WBOPT_GET_ACCOUNT_PROFILE_SCHOOL_LIST), //获取所有学校列表
HELPER_UNIT(WBOPT_GET_ACCOUNT_RATE_LIMIT_STATUS), //获取当前用户API访问频率限制
HELPER_UNIT(WBOPT_GET_ACCOUNT_GET_UID), //OAuth授权之后获取用户UID(作用相当于旧版接口的account/verify_credentials)
HELPER_UNIT(WBOPT_POST_ACCOUNT_PROFILE_BASIC_UPDATE), // 更新用户基本信息
HELPER_UNIT(WBOPT_POST_ACCOUNT_PROFILE_EDU_UPDATE), // 更新用户教育信息
HELPER_UNIT(WBOPT_POST_ACCOUNT_PROFILE_EDU_DESTROY), // 删除用户教育信息
HELPER_UNIT(WBOPT_POST_ACCOUNT_PROFILE_CAR_UPDATE), // 更新用户职业信息
HELPER_UNIT(WBOPT_POST_ACCOUNT_PROFILE_CAR_DESTROY), // 删除用户职业信息
HELPER_UNIT(WBOPT_POST_ACCOUNT_AVATAR_UPLOAD), // 上传头像
HELPER_UNIT(WBOPT_POST_ACCOUNT_UPDATE_PRIVACY), // 更新隐私设置
HELPER_UNIT(WBOPT_GET_FRIENDSHIPS_FRIENDS),//获取用户的关注列表
HELPER_UNIT(WBOPT_GET_FRIENDSHIPS_IN_COMMON),//获取共同关注人列表接口
HELPER_UNIT(WBOPT_GET_FRIENDSHIPS_BILATERAL),//获取双向关注列表
HELPER_UNIT(WBOPT_GET_FRIENDSHIPS_BILATERAL_IDS),//获取双向关注ID列表
HELPER_UNIT(WBOPT_GET_FRIENDSHIPS_FRIENDS_IDS),//获取用户关注对象uid列表
HELPER_UNIT(WBOPT_GET_FRIENDSHIPS_FRIENDS_REMARK_BATCH),//批量获取备注
HELPER_UNIT(WBOPT_GET_FRIENDSHIPS_FRIENDS_FOLLOWERS),//获取用户粉丝列表及每个粉丝的最新一条微博
HELPER_UNIT(WBOPT_GET_FRIENDSHIPS_FRIENDS_FOLLOWERS_IDS),//获取用户粉丝对象uid列表
HELPER_UNIT(WBOPT_GET_FRIENDSHIPS_FRIENDS_FOLLOWERS_ACTIVE),//获取用户优质粉丝列表关系链
HELPER_UNIT(WBOPT_GET_FRIENDSHIPS_CHAIN_FOLLOWERS),//获取我的关注人中关注了指定用户的分组
HELPER_UNIT(WBOPT_GET_FRIENDSHIPS_SHOW),//获取两个用户关系的详细情况
HELPER_UNIT(WBOPT_POST_FRIENDSHIPS_CREATE),//关注某用户
HELPER_UNIT(WBOPT_POST_FRIENDSHIPS_CREATE_BATCH),//批量关注用户
HELPER_UNIT(WBOPT_POST_FRIENDSHIPS_DESTROY),//取消关注某用户
HELPER_UNIT(WBOPT_POST_FRIENDSHIPS_FOLLOWERS_DESTORY),//移除粉丝
HELPER_UNIT(WBOPT_POST_FRIENDSHIPS_REMARK_UPDATE),//更新关注人备注
HELPER_UNIT(WBOPT_GET_FAVORITES),//获取当前登录用户的收藏列表
HELPER_UNIT(WBOPT_GET_FAVORITES_SHOW),//获取单条收藏信息
HELPER_UNIT(WBOPT_GET_FAVORITES_BY_TAGS),//获取当前用户某个标签下的收藏列表
HELPER_UNIT(WBOPT_GET_FAVORITES_TAGS),//当前登录用户的收藏标签列表
HELPER_UNIT(WBOPT_POST_FAVORITES_CREATE),//添加收藏
HELPER_UNIT(WBOPT_POST_FAVORITES_DESTROY),//删除收藏
HELPER_UNIT(WBOPT_POST_FAVORITES_DESTROY_BATCH),//批量删除收藏
HELPER_UNIT(WBOPT_POST_FAVORITES_TAGS_UPDATE),//更新收藏标签
HELPER_UNIT(WBOPT_POST_FAVORITES_TAGS_UPDATE_BATCH),//更新当前用户所有收藏下的指定标签
HELPER_UNIT(WBOPT_POST_FAVORITES_TAGS_DESTROY_BATCH),//删除当前用户所有收藏下的指定标签
HELPER_UNIT(WBOPT_GET_TRENDS),//获取某人话题
HELPER_UNIT(WBOPT_GET_TRENDS_STATUSES),//获取某一话题下的微博
HELPER_UNIT(WBOPT_GET_TRENDS_HOURLY),//返回最近一小时内的热门话题
HELPER_UNIT(WBOPT_GET_TRENDS_DAILY),//返回最近一天内的热门话题
HELPER_UNIT(WBOPT_GET_TRENDS_WEEKLY),//返回最近一周内的热门话题
HELPER_UNIT(WBOPT_POST_TRENDS_FOLLOW),//关注某话题
HELPER_UNIT(WBOPT_POST_TRENDS_DESTROY),//取消关注的某一个话题
HELPER_UNIT(WBOPT_GET_TAGS),//返回指定用户的标签列表
HELPER_UNIT(WBOPT_GET_TAGS_TAGS_BATCH),//批量获取用户标签
HELPER_UNIT(WBOPT_GET_TAGS_SUGGESTIONS),//返回系统推荐的标签列表
HELPER_UNIT(WBOPT_POST_TAGS_CREATE),//添加用户标签
HELPER_UNIT(WBOPT_POST_TAGS_DESTROY),//删除用户标签
HELPER_UNIT(WBOPT_POST_TAGS_DESTROY_BATCH),//批量删除用户标签
HELPER_UNIT(WBOPT_GET_SEARCH_SUGGESTIONS_USERS),//搜用户搜索建议
HELPER_UNIT(WBOPT_GET_SEARCH_SUGGESTIONS_STATUSES),//搜微博搜索建议
HELPER_UNIT(WBOPT_GET_SEARCH_SUGGESTIONS_SCHOOLS),//搜学校搜索建议
HELPER_UNIT(WBOPT_GET_SEARCH_SUGGESTIONS_COMPANIES), //搜公司搜索建议
HELPER_UNIT(WBOPT_GET_SEARCH_SUGGESTIONS_APPS),//搜应用搜索建议
HELPER_UNIT(WBOPT_GET_SEARCH_SUGGESTIONS_AT_USERS), //@联想搜索
HELPER_UNIT(WBOPT_GET_SEARCH_SUGGESTIONS_INTEGRATE), //综合联想搜索
HELPER_UNIT(WBOPT_GET_SEARCH_STATUSES),//微博搜索
HELPER_UNIT(WBOPT_GET_SEARCH_GEO_STATUSES), //搜索指定范围内的微博
HELPER_UNIT(WBOPT_GET_SEARCH_USERS),//搜索用户
HELPER_UNIT(WBOPT_GET_SUGGESTIONS_FAVORITES_HOT),//热门收藏
HELPER_UNIT(WBOPT_GET_SUGGESTIONS_USERS_HOT),//获取系统推荐用户
HELPER_UNIT(WBOPT_GET_SUGGESTIONS_USERS_MAY_INTERESTED),//获取用户可能感兴趣的人
HELPER_UNIT(WBOPT_POST_SUGGESTIONS_USERS_NOT_INTERESTED),//不感兴趣的人
HELPER_UNIT(WBOPT_GET_SUGGESTIONS_USERS_BY_STATUS),//根据微博内容推荐用户
HELPER_UNIT(WBOPT_GET_SHORT_URL_SHORTEN), //将一个或多个长链接转换成短链接
HELPER_UNIT(WBOPT_GET_SHORT_URL_EXPAND), //将一个或多个短链接还原成原始的长链接
HELPER_UNIT(WBOPT_GET_SHORT_URL_SHARE_COUNTS), //取得一个短链接在微博上的微博分享数(包含原创和转发的微博)
HELPER_UNIT(WBOPT_GET_SHORT_URL_SHARE_STATUSES), //取得包含指定单个短链接的最新微博内容
HELPER_UNIT(WBOPT_GET_SHORT_URL_COMMENT_COUNTS), //取得一个短链接在微博上的微博评论数
HELPER_UNIT(WBOPT_GET_SHORT_URL_COMMENT_COMMENTS), //取得包含指定单个短链接的最新微博评论内容
};
const char* getOptionName(unsigned int optionId)
{
const int size = sizeof(gDebugHelperArray)/sizeof(gDebugHelperArray[0]);
if (optionId < size)
{
for (int i = 0; i < size; ++ i)
{
if (optionId == gDebugHelperArray[i].optionId)
{
return gDebugHelperArray[i].optionIdName;
}
}
}
static char buf[10] = { 0 };
memset(buf, sizeof(char), 10);
snprintf(buf, 10, "%d", optionId);
return buf;
}
//using namespace weibo;
//
//boost::shared_ptr<weibo::IWeibo> weiboPtr;
//
//static bool logined = false;
//
//void OnDelegateComplated(unsigned int methodOption, const char* httpHeader,
// ParsingObject* result, const UserTaskInfo* pTask);
//void OnDelegateErrored(unsigned int methodOption, const int errCode, const int subErrCode,
// ParsingObject* result, const UserTaskInfo* pTask);
//void OnDelegateWillRelease(unsigned int methodOption, const UserTaskInfo* pTask);
//
//
//
//
//void OnDelegateComplated(unsigned int methodOption, const char* httpHeader,
// ParsingObject* result, const UserTaskInfo* pTask)
//{
//if (methodOption == WBOPT_OAUTH2_ACCESS_TOKEN)
//{
//if (result->isUseable())
//{
//logined = true;
//std::string access_token = result->getSubStringByKey("access_token");
//
// Note: Must set acess token to sdk!
//weiboPtr->setOption(WOPT_ACCESS_TOKEN, access_token.c_str());
//}
//}
//else if (methodOption == WBOPT_POST_STATUSES_UPDATE)
//{
// Send weibo successed!
// ...
//}
//DebugLog(<< __FUNCTION__ << "| Option Id: " << getOptionName(optionId));
//
//onResponseProcess(optionId, result, 0, 0, true);
//}
//
//void OnDelegateErrored(unsigned int methodOption, const int errCode, const int subErrCode,
// ParsingObject* result, const UserTaskInfo* pTask)
//{
// Please reference http://open.weibo.com/wiki/Help/error
//if (methodOption == WBOPT_OAUTH2_ACCESS_TOKEN)
//{
//if (result && result->isUseable())
//{
//std::string error_code = result->getSubStringByKey("error_code");
//std::string request = result->getSubStringByKey("request");
//std::string error = result->getSubStringByKey("error");
//}
//}
//else if (methodOption == WBOPT_POST_STATUSES_UPDATE)
//{
// Send weibo failed!
// ...
//}
//}
//
//void OnDelegateWillRelease(unsigned int methodOption, const UserTaskInfo* pTask)
//{
//
//}
SinaWeiBo::SinaWeiBo(void)
{
Init();
}
SinaWeiBo::~SinaWeiBo(void)
{
UnInit();
}
int SinaWeiBo::Init(void)
{
/*weiboPtr = weibo::WeiboFactory::getWeibo();
weiboPtr->startup();
weiboPtr->setOption(weibo::WOPT_CONSUMER, "2106534996", "cb313cf5e0467f146f7ad7ccb496afde");*/
mWeiboPtr = weibo::WeiboFactory::getWeibo();
mWeiboPtr->startup();
//mWeiboPtr->setOption(weibo::WOPT_CONSUMER, SINA_APP_KEY, SINA_SECRET_KEY);
//
//std::string url("https://api.weibo.com/oauth2/authorize?client_id=");
//url += SINA_APP_KEY;
//url += "&redirect_uri=";
//url += REDIRECT_URL;
//url += "&response_type=code";
//
//#ifdef _WIN32
//ShellExecuteA(NULL, "open", url.c_str(), NULL, NULL, SW_SHOWNORMAL);
//#else
//std::cout << url << std::endl;
//#endif
mWeiboPtr->OnDelegateComplated += std::make_pair(this, &SinaWeiBo::onWeiboRespComplated);
mWeiboPtr->OnDelegateErrored += std::make_pair(this, &SinaWeiBo::onWeiboRespErrored);
mWeiboPtr->OnDelegateWillRelease += std::make_pair(this, &SinaWeiBo::onWeiboRespStoped);
//#if defined(LOG_SUPPORT) && defined(_WIN32)
//std::wstring logfile = getAppModulePathW();
//logfile += L"UNIT_LOG.log";
//Util::Log::initialize(Util::Log::File | Util::Log::VSDebugWindow,
//Util::Log::Debug, "WeiboSDK_UnitTest", logfile.c_str());
//#endif //LOG_SUPPORT
return 0;
}
void SinaWeiBo::UnInit(void)
{
//if(weiboPtr){
//weiboPtr->stopAll();
//weiboPtr->shutdown();
//}
if(mWeiboPtr){
mWeiboPtr->OnDelegateComplated -= std::make_pair(this, &SinaWeiBo::onWeiboRespComplated);
mWeiboPtr->OnDelegateErrored -= std::make_pair(this, &SinaWeiBo::onWeiboRespErrored);
mWeiboPtr->OnDelegateWillRelease -= std::make_pair(this, &SinaWeiBo::onWeiboRespStoped);
mWeiboPtr->shutdown();
}
}
//int SinaWeiBo::SetAccout(char * user, char * password)
//{
//mWeiboPtr->setOption(weibo::WOPT_CONSUMER, SINA_APP_KEY, SINA_SECRET_KEY);
//
//std::string url("https://api.weibo.com/oauth2/authorize?client_id=");
//url += SINA_APP_KEY;
//url += "&redirect_uri=";
//url += REDIRECT_URL;
//url += "&response_type=code";
//
////#ifdef _WIN32
////ShellExecuteA(NULL, "open", url.c_str(), NULL, NULL, SW_SHOWNORMAL);
////#else
////std::cout << url << std::endl;
////#endif
///*CBrowser browser(this);
//browser.SetUrl(url.c_str());
//browser.DoModal();*/
//
//return 0;
//}
void SinaWeiBo::GetUserInfo(char *userId)
{
}
int SinaWeiBo::SendWeibo(CString strContent,UserTaskInfo* pUserData)
{
CCodeLib::ConvertGBKToUtf8(strContent);
/*UserTaskInfo * task = NULL;
if(pUserData){
task = new UserTaskInfo;
task->mUsrData = pUserData;
}*/
return mWeiboPtr->getMethod()->postStatusesUpdate((LPTSTR)(LPCTSTR)strContent,NULL,pUserData);
}
int SinaWeiBo::SendWeiboWithImage(CString imgPath, CString strContent,UserTaskInfo *pUserData)
{
CCodeLib::ConvertGBKToUtf8(strContent);
CCodeLib::ConvertGBKToUtf8(imgPath);
/*UserTaskInfo * task = NULL;
if(pUserData){
task = new UserTaskInfo;
task->mUsrData = pUserData;
}*/
return mWeiboPtr->getMethod()->postStatusesUpload((LPTSTR)(LPCTSTR)strContent,(LPTSTR)(LPCTSTR)imgPath,NULL,pUserData);
}
int SinaWeiBo::GeWeiboByUser(CString strUser,void*pUserData)
{
return 0;
}
int SinaWeiBo::RePostWeibo(CString weiboId, CString strComment)
{
return 0;
}
/********************sina 2.0 api******************************/
void SinaWeiBo::onResponseProcess(unsigned int optionId, weibo::ParsingObject* resultObj, const int errCode, const int errSubCode, bool isComplated)
{
if (resultObj)
{
ParsingObject* tempObject = new ParsingObject(*resultObj);
ParsingObjectPtr objPtr(tempObject);
switch(optionId)
{
case WBOPT_OAUTH2_ACCESS_TOKEN:
{
ParsingOauthRet ret;
ret.doParse(objPtr);
mWeiboPtr->setOption(WOPT_ACCESS_TOKEN, ret.access_token.c_str());
mMYID = ret.uid;
}
break;
default:
break;
}
}
}
void SinaWeiBo::onWeiboRespComplated(unsigned int optionId, const char* httpHeader, ParsingObject* result, const weibo::UserTaskInfo* pTask)
{
DebugLog(<< __FUNCTION__ << "| Option Id: " << getOptionName(optionId));
onResponseProcess(optionId, result, 0, 0, true);
if(pTask && pTask->mUsrData){
CMaiBoDlg *dlg = (CMaiBoDlg*)pTask->mUsrData;
CString strRet;
if(result){
strRet = result->getSource().c_str();
}
dlg->HandleResponse(optionId,WERR_OK,strRet);
}
}
void SinaWeiBo::onWeiboRespErrored(unsigned int optionId, const int errCode, const int errSubCode, ParsingObject* result, const weibo::UserTaskInfo* pTask)
{
DebugLog(<< __FUNCTION__ << "| Option Id: " << getOptionName(optionId) << " | error code: " << errCode << " | sub error Code: " << errSubCode);
onResponseProcess(optionId, result, errCode, errSubCode, false);
if(pTask && pTask->mUsrData){
CMaiBoDlg *dlg = (CMaiBoDlg*)pTask->mUsrData;
CString strRet;
if(result){
strRet = result->getSource().c_str();
}
dlg->HandleResponse(optionId,errCode,strRet);
}
}
void SinaWeiBo::onWeiboRespStoped(unsigned int optionId, const weibo::UserTaskInfo* pTask)
{
DebugLog(<< __FUNCTION__ << "| Option Id: " << getOptionName(optionId));
// Do noting!
}
int SinaWeiBo::authCode(const char * code, void * userData)
{
if(mWeiboPtr){
return mWeiboPtr->getMethod()->oauth2Code(code, REDIRECT_URL, NULL);
}
return WRC_UNKNOW;
}
CString SinaWeiBo::GetAuthorizationUrl(void)
{
mWeiboPtr->setOption(weibo::WOPT_CONSUMER, SINA_APP_KEY, SINA_SECRET_KEY);
CString url("https://api.weibo.com/oauth2/authorize?client_id=");
url += SINA_APP_KEY;
url += "&redirect_uri=";
url += REDIRECT_URL;
url += "&response_type=code";
return url;
}
int SinaWeiBo::GetSearchUser(CString tag,UserTaskInfo *pUserData)
{
CCodeLib::ConvertGBKToUtf8(tag);
return mWeiboPtr->getMethod()->getSearchUsers((LPTSTR)(LPCTSTR)tag,0,0,0,0,0,0,0,0,0,0,0,0,pUserData);
}
2.腾讯微博C++封装
头文件:
<pre name="code" class="cpp">#pragma once#include "WeiboApi.h"typedef enum {e_None=-1,e_Login,e_SendWeibo,e_SearchUserByTag,e_SendWeiboWithImage, e_SearchWeiboByUser,e_TransferWeibo,e_PrivateAdd,}txOperation;class TxWeiBo{public:TxWeiBo(void);~TxWeiBo(void);void Init(void);void UnInit(void);//virtual void OnRequestComplete(HTTP_RESULTCODE eHttpRetCode,const char* pReqUrl, CWeiboParam oParam, //const char*pData,int nLen);BOOL GetToken(void);std::string m_sstrAppKey;// AppSecretstd::string m_sstrAppSecret;// AccessKeystd::string m_sstrAccessKey;// AccessSecretstd::string m_sstrAccessSecret;std::string m_ssOauth_Verify;int SetWeiboAccount(CString user, CString pwd);protected:std::string m_sstrTokenKey;std::string m_sstrTokenSecrect;std::string m_strVerify;public:BOOL GetAccessKey(void);CString m_strConfigPath;void SetConfigPath(CString path);int SendWeibo(CString strContent,VWeiboCallback *pCallBack);int SendWeibo(CString strContent,CString imgUrl,VWeiboCallback *pCallBack);int SearchUserByTag(CString keyTag , VWeiboCallback * pCallBack);int SearchUserByTag(CString keyTag , int pageNum,VWeiboCallback * pCallBack);static txOperation GetOperation(const char* reqUrl);int SearchWeiboByUser(CString userId, VWeiboCallback* pCallback);int TransferWeibo(CString content , CString weiboId , VWeiboCallback * pCallback);int TxWeiBo::SendPrivateMessage(CString name , CString content , VWeiboCallback * pCallback);};CPP文件:
<pre name="code" class="cpp">#include "StdAfx.h"
#include "TxWeiBo.h"
#include "WeiboParam.h"
#include "AppKey.h"
#include "VerifyDlg.h"
#include "Util.h"
//#define CONFIG_PATH (GetModulePath() + "\\TxWeibo.ini")
TxWeiBo::TxWeiBo(void)
: m_strConfigPath(_T(""))
{
Init();
}
TxWeiBo::~TxWeiBo(void)
{
UnInit();
}
void TxWeiBo::Init(void)
{
m_sstrAppKey=TENCENT_APP_KEY;
m_sstrAppSecret = TENCENT_SECRET_KEY;
//m_strVerify = "http://open.t.qq.com/cgi-bin/authorize?oauth_token=";
}
void TxWeiBo::UnInit(void)
{
}
// CTXAPIToolDlg 对话框
#define HIDE_PADDING 50
BOOL TxWeiBo::GetToken(void)
{
string strCallbackUrl = "http://www.qq.com";
CWeiboParam oParam;
std::string c_strCustomKey= TXWeibo::Param::strCustomKey;
std::string c_strCustomSecrect= TXWeibo::Param::strCustomSecrect;
std::string c_oauthCallback= TXWeibo::Param::strCallbackUrl;
oParam.AddParam(c_strCustomKey.c_str(), m_sstrAppKey.c_str());
oParam.AddParam(c_strCustomSecrect.c_str(), m_sstrAppSecret.c_str());
oParam.AddParam(c_oauthCallback.c_str(), strCallbackUrl.c_str());
string strUrl = "https://open.t.qq.com/cgi-bin/request_token";
char* pRetData = NULL;
int nLen = 0;
HTTP_RESULTCODE eErrorCode = SyncRequest(strUrl.c_str(), EHttpMethod_Get, oParam, pRetData,nLen);
if(eErrorCode != HTTPRESULT_OK || pRetData == NULL)
{
return FALSE;
}
string strResult = pRetData;
ReleaseData(pRetData);
string strMark1 = "oauth_token=";
string strMark2 = "&oauth_token_secret=";
string strMark3 = "&oauth_callback_confirmed=";
string::size_type nTokenPos = strResult.find(strMark1);
if (nTokenPos == 0)
{
string::size_type nSecrectPos = strResult.find(strMark2);
if ((nSecrectPos != string::npos) && (nSecrectPos > nTokenPos))
{
m_sstrTokenKey = strResult.substr(strMark1.length(), nSecrectPos - strMark1.length());
string::size_type nCallbackPos = strResult.find(strMark3);
if (nTokenPos != string::npos)
{
m_sstrTokenSecrect = strResult.substr(nSecrectPos + strMark2.length(), nCallbackPos - (nSecrectPos + strMark2.length()));
}
}
}
if (!m_sstrTokenKey.empty())
{
//string strVerify = "http://open.t.qq.com/cgi-bin/authorize?oauth_token=";
//m_strVerify = "http://open.t.qq.com/cgi-bin/authorize?oauth_token=";
//strVerify += "?oauth_token=";
/*if(m_sstrTokenKey.length()>0){
AfxMessageBox(m_sstrTokenKey.c_str());
}*/
//m_strVerify += m_sstrTokenKey;
CString strUrl;
strUrl.Format(_T("http://open.t.qq.com/cgi-bin/authorize?oauth_token=%s"),m_sstrTokenKey.c_str());
//AfxMessageBox(m_sstrTokenKey.c_str());
//AfxMessageBox(strUrl);
ShellExecuteA( NULL, _T("open"), strUrl, NULL, NULL, SW_SHOWNORMAL);
return TRUE;
}
return FALSE;
}
int TxWeiBo::SetWeiboAccount(CString user, CString pwd)
{
char szConfig[1024];
ZeroMemory(szConfig,1024*sizeof(char));
::GetPrivateProfileString(_T("Config"),_T("AccessKey"),_T(""),szConfig,1024,m_strConfigPath);
m_sstrAccessKey = szConfig;
ZeroMemory(szConfig,1024*sizeof(char));
::GetPrivateProfileString(_T("Config"),_T("AccessSecret"),_T(""),szConfig,1024,m_strConfigPath);
m_sstrAccessSecret = szConfig;
if(m_sstrAccessKey.empty() || m_sstrAccessSecret.empty())
{
//获取tokenkey跳网页
if(GetToken() == FALSE)
{
AfxMessageBox("获取token key出错");
return -1;
}
}
if(m_sstrAccessKey.empty() || m_sstrAccessSecret.empty())
{
CVerifyDlg dlg;//拿到oauth_verifier
if(dlg.DoModal() != IDOK)
{
return -1;
}
m_ssOauth_Verify = dlg.m_strInput.GetString();//Unicode2Mbcs(dlg.m_strInput.GetString());
//根据oauth_verifier拿accessKey和accessSecret,这两个参数永久有效
if(GetAccessKey() != TRUE)
{
AfxMessageBox(_T("获取access key出错"));
return -1;
}
}
::WritePrivateProfileString(_T("Config"),_T("AccessKey"),m_sstrAccessKey.c_str(),m_strConfigPath);
::WritePrivateProfileString(_T("Config"),_T("AccessSecret"),m_sstrAccessSecret.c_str(),m_strConfigPath);
return 0;
}
BOOL TxWeiBo::GetAccessKey(void)
{
CWeiboParam oParam;
std::string c_strCustomKey= TXWeibo::Param::strCustomKey;
std::string c_strCustomSecrect= TXWeibo::Param::strCustomSecrect;
std::string c_strTokenKey= TXWeibo::Param::strTokenKey;
std::string c_strTokenSecrect= TXWeibo::Param::strTokenSecrect;
oParam.AddParam(c_strCustomKey.c_str(), m_sstrAppKey.c_str());
oParam.AddParam(c_strCustomSecrect.c_str(), m_sstrAppSecret.c_str());
oParam.AddParam(c_strTokenKey.c_str(), m_sstrTokenKey.c_str());
oParam.AddParam(c_strTokenSecrect.c_str(), m_sstrTokenSecrect.c_str());
size_t nSizeReturn = 0;
oParam.AddParam("oauth_verifier", m_ssOauth_Verify.c_str());
string strUrl = "https://open.t.qq.com/cgi-bin/access_token";
char* pRetData = NULL;
int nLen = 0;
HTTP_RESULTCODE eHttpCode = SyncRequest(strUrl.c_str(), EHttpMethod_Get, oParam, pRetData,nLen);
if(eHttpCode != HTTPRESULT_OK || pRetData == NULL)
{
return FALSE;
}
string strResult = pRetData;
ReleaseData(pRetData);
string strMark1 = "oauth_token=";
string strMark2 = "&oauth_token_secret=";
string strMark3 = "&name=";
string::size_type nTokenPos = strResult.find(strMark1);
if (nTokenPos == 0)
{
string::size_type nSecrectPos = strResult.find(strMark2);
if ((nSecrectPos != string::npos) && (nSecrectPos > nTokenPos))
{
m_sstrAccessKey = strResult.substr(strMark1.length(), nSecrectPos - strMark1.length());
string::size_type nCallbackPos = strResult.find(strMark3);
if (nTokenPos != string::npos)
{
m_sstrAccessSecret = strResult.substr(nSecrectPos + strMark2.length(), nCallbackPos - (nSecrectPos + strMark2.length()));
}
}
return TRUE;
}
return FALSE;
}
void TxWeiBo::SetConfigPath(CString path)
{
m_strConfigPath=path;
}
int TxWeiBo::SendWeibo(CString strContent,VWeiboCallback *pCallBack)
{
//获取类型
Txwb_api_option option = TXWB_T_ADD;
CWeiboParam oParam;
//以下四个参数在每次请求必须带上
std::string c_strCustomKey= TXWeibo::Param::strCustomKey;
std::string c_strCustomSecrect= TXWeibo::Param::strCustomSecrect;
std::string c_strTokenKey= TXWeibo::Param::strTokenKey;
std::string c_strTokenSecrect= TXWeibo::Param::strTokenSecrect;
oParam.AddParam(c_strCustomKey.c_str(), m_sstrAppKey.c_str());
oParam.AddParam(c_strCustomSecrect.c_str(), m_sstrAppSecret.c_str());
oParam.AddParam(c_strTokenKey.c_str(),m_sstrAccessKey.c_str());
oParam.AddParam(c_strTokenSecrect.c_str(),m_sstrAccessSecret.c_str());
if(option <= TXWB_BASE || option >=TXWB_MAX)
{
AfxMessageBox("api 类型超出范围");
return -1;
}
oParam.AddParam("format","json");
oParam.AddParam("content",(LPTSTR)(LPCTSTR)strContent);
oParam.AddParam("clientip","127.0.0.1");
//oParam.AddParam("jing","");
//oParam.AddParam("wei","");
if(AsyncRequestByOption(option, oParam, pCallBack))
{
return 0;
}
else
{
return -1;
}
}
int TxWeiBo::SendWeibo(CString strContent,CString imgUrl,VWeiboCallback *pCallBack)
{
//获取类型
Txwb_api_option option = TXWB_T_ADD_PIC;
CWeiboParam oParam;
//以下四个参数在每次请求必须带上
std::string c_strCustomKey= TXWeibo::Param::strCustomKey;
std::string c_strCustomSecrect= TXWeibo::Param::strCustomSecrect;
std::string c_strTokenKey= TXWeibo::Param::strTokenKey;
std::string c_strTokenSecrect= TXWeibo::Param::strTokenSecrect;
oParam.AddParam(c_strCustomKey.c_str(), m_sstrAppKey.c_str());
oParam.AddParam(c_strCustomSecrect.c_str(), m_sstrAppSecret.c_str());
oParam.AddParam(c_strTokenKey.c_str(),m_sstrAccessKey.c_str());
oParam.AddParam(c_strTokenSecrect.c_str(),m_sstrAccessSecret.c_str());
if(option <= TXWB_BASE || option >=TXWB_MAX)
{
AfxMessageBox("api 类型超出范围");
return -1;
}
oParam.AddParam("format","json");
oParam.AddParam("content",(LPTSTR)(LPCTSTR)strContent);
oParam.AddParam("clientip","127.0.0.1");
//oParam.AddParam("jing","");
//oParam.AddParam("wei","");
oParam.AddPicNameParam("pic",(LPTSTR)(LPCTSTR)imgUrl);
if(AsyncRequestByOption(option, oParam, pCallBack))
{
return 0;
}
else
{
return -1;
}
}
int TxWeiBo::SearchUserByTag(CString keyTag , VWeiboCallback * pCallBack)
{
//获取类型
Txwb_api_option option = TXWB_SEARCH_USER;
CWeiboParam oParam;
//以下四个参数在每次请求必须带上
std::string c_strCustomKey= TXWeibo::Param::strCustomKey;
std::string c_strCustomSecrect= TXWeibo::Param::strCustomSecrect;
std::string c_strTokenKey= TXWeibo::Param::strTokenKey;
std::string c_strTokenSecrect= TXWeibo::Param::strTokenSecrect;
oParam.AddParam(c_strCustomKey.c_str(), m_sstrAppKey.c_str());
oParam.AddParam(c_strCustomSecrect.c_str(), m_sstrAppSecret.c_str());
oParam.AddParam(c_strTokenKey.c_str(),m_sstrAccessKey.c_str());
oParam.AddParam(c_strTokenSecrect.c_str(),m_sstrAccessSecret.c_str());
if(option <= TXWB_BASE || option >=TXWB_MAX)
{
AfxMessageBox("api 类型超出范围");
return -1;
}
oParam.AddParam("format","json");
oParam.AddParam("keyword",(LPTSTR)(LPCTSTR)keyTag);
oParam.AddParam("pageisize","20");
oParam.AddParam("page","1");
//oParam.AddParam("jing","");
//oParam.AddParam("wei","");
if(AsyncRequestByOption(option, oParam, pCallBack))
{
return 0;
}
else
{
return -1;
}
}
int TxWeiBo::SearchUserByTag(CString keyTag ,int pageNum, VWeiboCallback * pCallBack)
{
//获取类型
Txwb_api_option option = TXWB_SEARCH_USER;
CWeiboParam oParam;
//以下四个参数在每次请求必须带上
std::string c_strCustomKey= TXWeibo::Param::strCustomKey;
std::string c_strCustomSecrect= TXWeibo::Param::strCustomSecrect;
std::string c_strTokenKey= TXWeibo::Param::strTokenKey;
std::string c_strTokenSecrect= TXWeibo::Param::strTokenSecrect;
oParam.AddParam(c_strCustomKey.c_str(), m_sstrAppKey.c_str());
oParam.AddParam(c_strCustomSecrect.c_str(), m_sstrAppSecret.c_str());
oParam.AddParam(c_strTokenKey.c_str(),m_sstrAccessKey.c_str());
oParam.AddParam(c_strTokenSecrect.c_str(),m_sstrAccessSecret.c_str());
if(option <= TXWB_BASE || option >=TXWB_MAX)
{
AfxMessageBox("api 类型超出范围");
return -1;
}
CString strPageNum;
strPageNum.Format("%d",pageNum);
oParam.AddParam("format","json");
oParam.AddParam("keyword",(LPTSTR)(LPCTSTR)keyTag);
oParam.AddParam("pageisize","20");
oParam.AddParam("page",(LPTSTR)(LPCTSTR)strPageNum);
//oParam.AddParam("jing","");
//oParam.AddParam("wei","");
if(AsyncRequestByOption(option, oParam, pCallBack))
{
return 0;
}
else
{
return -1;
}
}
txOperation TxWeiBo::GetOperation(const char* reqUrl)
{
if(!reqUrl){
return e_None;
}
if(strcmp(reqUrl,"http://open.t.qq.com/api/search/user") == 0){
return e_SearchUserByTag;
}else if(strcmp(reqUrl,"http://open.t.qq.com/api/t/add") == 0){
return e_SendWeibo;
}else if(strcmp(reqUrl,"http://open.t.qq.com/api/statuses/user_timeline")==0){
return e_SearchWeiboByUser;
}else if(strcmp(reqUrl,"http://open.t.qq.com/api/t/add_pic")==0){
return e_SendWeiboWithImage;
}else if(strcmp(reqUrl,"http://open.t.qq.com/api/t/re_add")==0){
return e_TransferWeibo;
}else if(strcmp(reqUrl,"http://open.t.qq.com/api/private/add")==0){
return e_PrivateAdd;
}
return e_None;
}
int TxWeiBo::SearchWeiboByUser(CString userId, VWeiboCallback* pCallback)
{
Txwb_api_option option = TXWB_STATUSES_USER_TL;
CWeiboParam oParam;
//以下四个参数在每次请求必须带上
std::string c_strCustomKey= TXWeibo::Param::strCustomKey;
std::string c_strCustomSecrect= TXWeibo::Param::strCustomSecrect;
std::string c_strTokenKey= TXWeibo::Param::strTokenKey;
std::string c_strTokenSecrect= TXWeibo::Param::strTokenSecrect;
oParam.AddParam(c_strCustomKey.c_str(), m_sstrAppKey.c_str());
oParam.AddParam(c_strCustomSecrect.c_str(), m_sstrAppSecret.c_str());
oParam.AddParam(c_strTokenKey.c_str(),m_sstrAccessKey.c_str());
oParam.AddParam(c_strTokenSecrect.c_str(),m_sstrAccessSecret.c_str());
if(option <= TXWB_BASE || option >=TXWB_MAX)
{
AfxMessageBox("api 类型超出范围");
return -1;
}
oParam.AddParam("format","json");
oParam.AddParam("pageflag","0");
oParam.AddParam("pagetime","0");
oParam.AddParam("reqnum","20");
oParam.AddParam("lastid","0");
oParam.AddParam("name",(LPTSTR)(LPCTSTR)userId);
//oParam.AddParam("jing","");
//oParam.AddParam("wei","");
if(AsyncRequestByOption(option, oParam, pCallback))
{
return 0;
}
else
{
return -1;
}
}
int TxWeiBo::TransferWeibo(CString content , CString weiboId , VWeiboCallback * pCallback)
{
Txwb_api_option option = TXWB_T_RE_ADD;
CWeiboParam oParam;
//以下四个参数在每次请求必须带上
std::string c_strCustomKey= TXWeibo::Param::strCustomKey;
std::string c_strCustomSecrect= TXWeibo::Param::strCustomSecrect;
std::string c_strTokenKey= TXWeibo::Param::strTokenKey;
std::string c_strTokenSecrect= TXWeibo::Param::strTokenSecrect;
oParam.AddParam(c_strCustomKey.c_str(), m_sstrAppKey.c_str());
oParam.AddParam(c_strCustomSecrect.c_str(), m_sstrAppSecret.c_str());
oParam.AddParam(c_strTokenKey.c_str(),m_sstrAccessKey.c_str());
oParam.AddParam(c_strTokenSecrect.c_str(),m_sstrAccessSecret.c_str());
if(option <= TXWB_BASE || option >=TXWB_MAX)
{
AfxMessageBox("api 类型超出范围");
return -1;
}
oParam.AddParam("format","json");
oParam.AddParam("content",(LPTSTR)(LPCTSTR)content);
oParam.AddParam("clientip","127.0.0.1");
oParam.AddParam("jing","");
oParam.AddParam("wei","");
oParam.AddParam("reid",(LPTSTR)(LPCTSTR)weiboId);
//oParam.AddParam("jing","");
//oParam.AddParam("wei","");
if(AsyncRequestByOption(option, oParam, pCallback))
{
return 0;
}
else
{
return -1;
}
}
int TxWeiBo::SendPrivateMessage(CString name , CString content , VWeiboCallback * pCallback)
{
Txwb_api_option option = TXWB_PRIVATE_ADD;
CWeiboParam oParam;
//以下四个参数在每次请求必须带上
std::string c_strCustomKey= TXWeibo::Param::strCustomKey;
std::string c_strCustomSecrect= TXWeibo::Param::strCustomSecrect;
std::string c_strTokenKey= TXWeibo::Param::strTokenKey;
std::string c_strTokenSecrect= TXWeibo::Param::strTokenSecrect;
oParam.AddParam(c_strCustomKey.c_str(), m_sstrAppKey.c_str());
oParam.AddParam(c_strCustomSecrect.c_str(), m_sstrAppSecret.c_str());
oParam.AddParam(c_strTokenKey.c_str(),m_sstrAccessKey.c_str());
oParam.AddParam(c_strTokenSecrect.c_str(),m_sstrAccessSecret.c_str());
if(option <= TXWB_BASE || option >=TXWB_MAX)
{
AfxMessageBox("api 类型超出范围");
return -1;
}
oParam.AddParam("format","json");
oParam.AddParam("content",(LPTSTR)(LPCTSTR)content);
oParam.AddParam("clientip","127.0.0.1");
oParam.AddParam("jing","");
oParam.AddParam("wei","");
oParam.AddParam("name",(LPTSTR)(LPCTSTR)name);
//oParam.AddParam("jing","");
//oParam.AddParam("wei","");
if(AsyncRequestByOption(option, oParam, pCallback))
{
return 0;
}
else
{
return -1;
}
}
3. 增加一条微博内容
void CMaiBoDlg::OnBnClickedAddItem()
{
// TODO: Add your control notification handler code here
UpdateData(TRUE);
CString content;
CString imgPath;
CString strRepostWeiboId;
int nRepost=0;
m_editContent.GetWindowText(content);
if(m_checkboxRepost.GetCheck()){
m_editWeiboRepost.GetWindowText(strRepostWeiboId);
if(strRepostWeiboId.IsEmpty()){
AfxMessageBox("请输入要转发的微博id");
return;
}
if(((CButton *)GetDlgItem(IDC_RADIO1))->GetCheck()==FALSE && ((CButton *)GetDlgItem(IDC_RADIO2))->GetCheck() == FALSE){
AfxMessageBox("请选择是腾讯还是新浪微博ID");
return;
}
if(((CButton *)GetDlgItem(IDC_RADIO1))->GetCheck()){
nRepost = eSinaRepost;
}else if(((CButton *)GetDlgItem(IDC_RADIO2))->GetCheck()){
nRepost = eTxRepost;
}
}else{
if(content.IsEmpty()){
AfxMessageBox(_T("请输入要发送的微博内容"));
return;
}
}
m_editImgPath.GetWindowText(imgPath);
int row = m_weiboList.GetItemCount();
CString id;
id.Format("%d",row+1);
m_weiboList.InsertItem(row,"");
m_weiboList.SetItemText(row,0,id);
BYTE complete =0;
CString strStatus="";
CString strAtList="";
if(nRepost == eNotRepost){
if(m_bSinaWeiboReady&&m_bTxWeiboReady){
strStatus+=STATUS_SENDING;
strStatus+="\r\n";
strStatus+=STATUS_TX_SENDING;
if(!m_strSinaAccountList.IsEmpty()){
strAtList+="新浪:"+m_strSinaAccountList+"\r\n";
}
if(!m_strTxAccountList.IsEmpty()){
strAtList+="腾讯:"+m_strTxAccountList;
}
}else{
if(m_bSinaWeiboReady){
//complete |=0x01;
strStatus+=STATUS_SENDING;
if(!m_strSinaAccountList.IsEmpty()){
strAtList+="新浪:"+m_strSinaAccountList;
}
}else if(m_bTxWeiboReady){
//complete |= 0x10;
strStatus+=STATUS_TX_SENDING;
if(!m_strTxAccountList.IsEmpty()){
strAtList+="腾讯:"+m_strTxAccountList;
}
}
}
}else{
if(nRepost == eSinaRepost){
strStatus="新浪转发为开始";
complete|=0x0A;
}else if(nRepost == eTxRepost){
complete|=0xA0;
strStatus="腾讯转发为开始";
}
}
m_weiboList.SetItemText(row,1,strStatus);
if(strRepostWeiboId.GetLength()>5 && nRepost!=eNotRepost){
CString str="微博ID=";
str+=strRepostWeiboId;
str+=",评论:";
str+=content;
m_weiboList.SetItemText(row,2,str);
}else{
m_weiboList.SetItemText(row,2,content);
}
m_weiboList.SetItemText(row,3,strAtList);
m_weiboList.SetItemText(row,4,imgPath);
m_weiboList.SetItemData(row,complete);
m_pRs.Open(_T("Weibo"),CADORecordset::openTable);
m_pRs.AddNew();
m_pRs.SetFieldValue("Id",row);
m_pRs.SetFieldValue("Content",content);
m_pRs.SetFieldValue("TxAt",m_strTxAccountList);
m_pRs.SetFieldValue("SinaAt",m_strSinaAccountList);
m_pRs.SetFieldValue("ImgPath",imgPath);
m_pRs.SetFieldValue("Complete",complete);
if(nRepost != eNotRepost){
m_pRs.SetFieldValue("RepostWeiboId",strRepostWeiboId);
}
m_pRs.Update();
}
4.启动微博定时器
<pre name="code" class="cpp">void CMaiBoDlg::OnBnClickedStart(){// TODO: Add your control notification handler code hereint i;for(i=0;i<m_weiboList.GetItemCount();i++){BYTE complete =(BYTE) m_weiboList.GetItemData(i);CString str;str.Format("%d:%d",i,complete);AfxMessageBox(str);}return;int nSelect=m_comboInterval.GetCurSel();int interval=(nSelect+1)*60*1000;if(m_bTimer == FALSE){m_weiboTimerId=SetTimer(SEND_WEIBO_TIMER_ID,interval,NULL);m_bTimer = TRUE;m_btnWeiboTimer.SetWindowText("关闭微博发送定时器");}else{KillTimer(SEND_WEIBO_TIMER_ID);m_bTimer = FALSE;m_btnWeiboTimer.SetWindowText("开启微博发送定时器");}//m_Weibo->SendWeibo(_T("sina 微博API测试"));}
5. 定时发送微博
<pre name="code" class="cpp">void CMaiBoDlg::AutoSendWeibo(void)
{
int i;
for(i=0;i<m_weiboList.GetItemCount();i++){
BYTE complete =(BYTE) m_weiboList.GetItemData(i);
if(complete == 0){
break;
}
}
if(i>=m_weiboList.GetItemCount()){
return;
}
CString strSql;
strSql.Format("Select * from Weibo where Id =%d",i);
if(m_pRs.Open(strSql,CADORecordset::openUnknown)){
//m_nCurWeiboIndex=i;
CString content;
CString imgPath;
CString txAtList;
CString sinaAtList;
m_pRs.GetFieldValue(_T("Content"),content);
m_pRs.GetFieldValue(_T("TxAt"),txAtList);
m_pRs.GetFieldValue(_T("SinaAt"),sinaAtList);
m_pRs.GetFieldValue(_T("ImgPath"),imgPath);
CString strStatus="";
if(m_bSinaWeiboReady && m_bTxWeiboReady){
strStatus="新浪正在发送\r\n腾讯正在发送";
}else{
if(m_bSinaWeiboReady){
strStatus="新浪正在发送";
}else if(m_bTxWeiboReady){
strStatus="腾讯正在发送";
}
}
m_weiboList.SetItemText(i,1,strStatus);
SendWeibo(i,content,imgPath,sinaAtList,txAtList);
}
}
总结一下:
腾讯微博开放的API接口较多,可以根据tag兴趣标签搜索微博用户,发送微博的时候可以@这些群体,增加微博推广的准确度,比如卖体育球鞋,就可以搜索NBA标签的用户进行@后发送