如题
很久不搞C++了,最近应工作要求,在VS2010下开发mfc客户端程序。因为涉及到客户端访问服务端,必须通过账户登录来确保安全性,所以需要客户端登录拿到服务端返回的token,然后客户端后续所有url请求都要携带token去访问。
这块功能用的是httpclient 和 curl库,网上资料很多,这里不做过多叙述,但也给出一个get/post请求函数的写法:
Get()
int CHttpClient::Get(const std::string & strUrl, std::string & strResponse)
{
CURLcode res;
CURL* curl = curl_easy_init();
if(NULL == curl)
{
return CURLE_FAILED_INIT;
}
if(m_bDebug)
{
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, OnDebug);
}
curl_easy_setopt(curl, CURLOPT_URL, strUrl.c_str());
curl_easy_setopt(curl, CURLOPT_READFUNCTION, NULL);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, OnWriteData);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&strResponse);
struct curl_slist *headers = NULL;
headers = curl_slist_append(headers, "Content-type: application/json;charset='utf-8'");
std::string cstrToken ="Authorization:" + GLOBAL_TOKEN;
headers = curl_slist_append(headers, cstrToken.c_str());
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 8);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10);
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
return res;
}
Post()
int CHttpClient::Post(const std::string & strUrl, const std::string & strPost, std::string & strResponse)
{
CURLcode res;
CURL* curl = curl_easy_init();
if(NULL == curl)
{
return CURLE_FAILED_INIT;
}
if(m_bDebug)
{
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, OnDebug);
}
curl_easy_setopt(curl, CURLOPT_URL, strUrl.c_str());
curl_easy_setopt(curl, CURLOPT_POST, 1);
struct curl_slist *headers = NULL;
headers = curl_slist_append(headers, "Content-type: application/json;charset='utf-8'");
std::string cstrToken ="Authorization:" + GLOBAL_TOKEN;
headers = curl_slist_append(headers, cstrToken.c_str());
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, strPost.c_str());
curl_easy_setopt(curl, CURLOPT_READFUNCTION, NULL);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, OnWriteData);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&strResponse);
curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 8);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 30);
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
return res;
}
全局引用变量
一开始,我定义了一个extern GLOBAL_TOKEN变量放在一个公共头文件中,然后在需要引用的地方引用,但是报错:无法解析的外部符号。经过一番查找资料,偶然看到一位老哥的解决方法:
打开类视图管理器,找到 theApp这个变量,因为任何一个mfc程序都会有它,然后照猫画虎,在该文件.cpp中定义好如int var1;,然后在该文件的头文件末尾声明extern int var1; 最后即可在任意地方引用该变量了。