当前位置:   article > 正文

通过libcurl实现https访问服务器_http.sys libcurl

http.sys libcurl

   libcurl支持http、https、ftp、gopher、telnet、dict、file和ldap协议。libcurl同时也支持HTTPS认证、HTTP POST、HTTP PUT、 FTP 上传(这个也能通过PHP的FTP扩展完成)、HTTP 基于表单的上传、代理、cookies和用户名+密码的认证。本文通过一个示例Demo介绍通过libcurl实现https访问服务器。

对libcurl 库的封装类示例如下,

h文件

  1. #pragma once
  2. #include "stdafx.h"
  3. #include <string>
  4. #include <vector>
  5. #include "curl/include/curl.h"
  6. #include "curl/include/easy.h"
  7. #pragma comment(lib,"curl/lib/libcurl.lib")
  8. /************************************************************************/
  9. /* libcurl库封装 sh 2019年7月32日 13:17:11 */
  10. /************************************************************************/
  11. //表单key对应的类型
  12. enum E_KEY_TYPE {
  13. e_key_text, //文本类型
  14. e_key_iamge //图片类型
  15. };
  16. //表单信息结构
  17. typedef struct
  18. {
  19. std::string strKey;
  20. std::string strVal;
  21. E_KEY_TYPE eKeyType;
  22. void Set(std::string key, std::string val, E_KEY_TYPE eType)
  23. {
  24. strKey = key;
  25. strVal = val;
  26. eKeyType = eType;
  27. }
  28. }POST_LIST, *LPPOST_LIST;
  29. //表单数据
  30. #define _POST_LIST_DATA_ std::vector<POST_LIST>
  31. class CTools
  32. {
  33. public:
  34. static std::string replace(const char *pszSrc, const char *pszOld, const char *pszNew);
  35. static const char * getAppPath();
  36. };
  37. class CUrlHttp
  38. {
  39. public:
  40. CUrlHttp(void);
  41. ~CUrlHttp(void);
  42. static int Request(std::string strRequestType,
  43. std::string strUrl,
  44. std::string &strReport,
  45. std::vector<std::string> vecHeader,
  46. std::string strParam="",
  47. std::string strCookie="",
  48. std::string strCaPath="",
  49. int nTimeOut=0);
  50. //有图片建议使用表单提交比较方便
  51. static int RequestSSL(std::string strUrl,
  52. std::string &strReport,
  53. _POST_LIST_DATA_ listParam,
  54. std::vector<std::string> vecHeader,
  55. std::string strCookie="",
  56. std::string strCaPath="",
  57. int nTimeOut=0);
  58. };
  59. class CUrlFtp
  60. {
  61. public:
  62. CUrlFtp();
  63. ~CUrlFtp();
  64. typedef struct
  65. {
  66. size_t type; //0:文件夹 1:文件
  67. std::string name; //名称
  68. std::string permissions; //权限
  69. }FILE_INFO, *LPFILE_INFO;
  70. public:
  71. int connect(const char *user, const char *password, const char * ip, short port=21);
  72. void close();
  73. int download(const char * remoteFile, const char * localFile, size_t timeOut=0);
  74. int upload(const char * remoteFile, const char * localFile, size_t timeOut=0);
  75. int dirlist(const char * remote, std::vector<FILE_INFO> &vecFileInfo);
  76. const char * getLastError();
  77. private:
  78. CURL *curl;
  79. std::string m_ip;
  80. std::string m_user;
  81. std::string m_password;
  82. short m_port;
  83. std::string m_lastError;
  84. };

cpp源文件

  1. #include "stdafx.h"
  2. #include "HttpsPost.h"
  3. #include <sys/types.h>
  4. #include <sys/stat.h>
  5. #include <fcntl.h>
  6. #include <errno.h>
  7. #ifdef WIN32
  8. #include <io.h>
  9. #else
  10. #include <unistd.h>
  11. #endif
  12. //参数文档地址:https://curl.haxx.se/libcurl/c/libcurl-tutorial.html
  13. namespace _CURL_
  14. {
  15. /**
  16. * buf: 从服务器返回的buffer
  17. * unit: buufer的单位
  18. * bufSize: buffer的大小
  19. * data: 保存从服务器返回的内容
  20. * 注意这个函数会被调用多次
  21. */
  22. static size_t write_data(void *buf, size_t unit, size_t bufSize, std::string * data)
  23. {
  24. int size = unit * bufSize;
  25. char * tmp = (char*)malloc(size + 1);
  26. memcpy(tmp, buf, size);
  27. tmp[size] = '\0';
  28. data->append(tmp);
  29. free(tmp);
  30. return size;
  31. }
  32. static size_t ftp_read(void *ptr, size_t size, size_t nmemb, void *stream)
  33. {
  34. curl_off_t nread;
  35. size_t retcode = fread(ptr, size, nmemb, (FILE *)stream);
  36. nread = (curl_off_t)retcode;
  37. return retcode;
  38. }
  39. //ftp 文件结构
  40. typedef struct FtpFile
  41. {
  42. char filename[512]; //文件名称
  43. FILE *stream; //文件操作指针
  44. }FTP_FILE, *LPFTP_FILE;
  45. static size_t ftp_write(void *buffer, size_t size, size_t nmemb,void *stream)
  46. {
  47. struct FtpFile *out = (struct FtpFile *)stream;
  48. if(out && !out->stream) {
  49. out->stream = fopen(out->filename, "wb");
  50. if(!out->stream)
  51. return -1;
  52. }
  53. return fwrite(buffer, size, nmemb, out->stream);
  54. }
  55. //智能初始化curl库和释放curl库
  56. class CurlIntelligence
  57. {
  58. public:
  59. CurlIntelligence()
  60. {
  61. curl_global_init(CURL_GLOBAL_ALL);
  62. }
  63. ~CurlIntelligence()
  64. {
  65. curl_global_cleanup();
  66. }
  67. };
  68. }
  69. _CURL_::CurlIntelligence g_curl;
  70. /*
  71. * 函数:
  72. * replace(替换字符串)
  73. * 参数:
  74. * pszSrc:源字符串
  75. * pszOld:需要替换的字符串
  76. * pszNew:新字符串
  77. * 返回值:
  78. * 返回替换后的字符串
  79. */
  80. std::string CTools::replace(const char *pszSrc, const char *pszOld, const char *pszNew)
  81. {
  82. std::string strContent, strTemp;
  83. strContent.assign( pszSrc );
  84. std::string::size_type nPos = 0;
  85. while( true )
  86. {
  87. nPos = strContent.find(pszOld, nPos);
  88. if ( nPos == std::string::npos )
  89. {
  90. break;
  91. }
  92. strTemp = strContent.substr(nPos+strlen(pszOld), strContent.length());
  93. strContent.replace(nPos,strContent.length(), pszNew );
  94. strContent.append(strTemp);
  95. nPos +=strlen(pszNew) - strlen(pszOld)+1; //防止重复替换 避免死循环
  96. }
  97. return strContent;
  98. }
  99. const char * CTools::getAppPath()
  100. {
  101. static std::string appPath;
  102. if ( appPath.empty() )
  103. {
  104. char szBuf[1024];
  105. memset(szBuf, '\0', 1024);
  106. #ifdef _WIN32
  107. GetModuleFileName(NULL, szBuf, 1024);
  108. std::string temp = szBuf;
  109. std::string::size_type pos = temp.find_last_of("\\")+1;
  110. appPath = temp.substr(0, pos);
  111. #else
  112. getcwd(szBuf, 1024);
  113. appPath.assign(szBuf);
  114. appPath.append("/");
  115. #endif
  116. }
  117. return appPath.c_str();
  118. }
  119. CUrlHttp::CUrlHttp(void)
  120. {
  121. }
  122. CUrlHttp::~CUrlHttp(void)
  123. {
  124. }
  125. /*
  126. * 函数:
  127. * Request(请求函数)
  128. * 参数:
  129. * strRequestType:请求类型(get,post)
  130. * strUrl:请求url地址
  131. * strReport:回执信息
  132. * strHeader:请求头
  133. * strCookie:cookie信息
  134. * strCaPath:ca转成pem证书路径
  135. * strParam:请求参数(get的时候此参数填空)
  136. * nTimeOut:超时设置默认是0秒 是无限等待
  137. * 返回值:
  138. * 0表示成功 非0表示错误代码
  139. */
  140. int CUrlHttp::Request(std::string strRequestType,
  141. std::string strUrl,
  142. std::string &strReport,
  143. std::vector<std::string> vecHeader,
  144. std::string strParam/* ="" */,
  145. std::string strCookie/* ="" */,
  146. std::string strCaPath/* ="" */,
  147. int nTimeOut/* =0 */)
  148. {
  149. CURL * curl;
  150. curl = curl_easy_init();
  151. curl_easy_setopt(curl, CURLOPT_URL, strUrl.c_str());
  152. //设置http头
  153. curl_slist * headers = NULL;
  154. for ( int i=0; i<vecHeader.size(); i++ )
  155. {
  156. if (!vecHeader.at(i).empty())
  157. {
  158. headers = curl_slist_append(headers, vecHeader.at(i).c_str());
  159. }
  160. }
  161. //设置http头
  162. if (headers != NULL)
  163. {
  164. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  165. }
  166. curl_easy_setopt(curl,CURLOPT_SSLVERSION,1);
  167. //判断是否有证书
  168. if(strCaPath.empty())
  169. {
  170. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);
  171. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, false);
  172. }
  173. else
  174. {
  175. //缺省情况就是PEM,所以无需设置,另外支持DER
  176. //curl_easy_setopt(curl,CURLOPT_SSLCERTTYPE,"PEM");
  177. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, true);
  178. curl_easy_setopt(curl, CURLOPT_CAINFO, strCaPath.c_str());
  179. }
  180. if ( strRequestType.compare("post")==0 || strRequestType.compare("POST") == 0 )
  181. {
  182. curl_easy_setopt(curl, CURLOPT_POST, 1);
  183. curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, strlen(strParam.c_str()));//post内容长度
  184. curl_easy_setopt(curl, CURLOPT_POSTFIELDS, strParam.c_str());
  185. }
  186. else
  187. {
  188. curl_easy_setopt(curl, CURLOPT_POST, 0);//get请求
  189. }
  190. std::string strReportHeader;//回执回来的头数据
  191. //Web服务器一般会重定向链接,比如访问http:/xxx/x1.do自动转到http:/xxx/x2.do
  192. //所以一定要设置CURLOPT_FOLLOWLOCATION为1,否则重定向后的数据不会返回。
  193. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION,1);
  194. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1); //可以看到调试信息
  195. //接受服务器的ssl证书而不管合不合法 (相当于命令行中的--insecure)
  196. curl_easy_setopt(curl,CURLOPT_HEADERFUNCTION,_CURL_::write_data);
  197. curl_easy_setopt(curl, CURLOPT_WRITEHEADER, &strReportHeader);
  198. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, _CURL_::write_data);
  199. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &strReport);
  200. if ( nTimeOut > 0 )
  201. {
  202. curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, nTimeOut);
  203. curl_easy_setopt(curl, CURLOPT_TIMEOUT, nTimeOut);
  204. }
  205. //
  206. if (!strCookie.empty())
  207. {
  208. curl_easy_setopt(curl, CURLOPT_COOKIEFILE, strCookie.c_str());
  209. }
  210. CURLcode code = curl_easy_perform(curl);
  211. if(code != CURLE_OK)
  212. {
  213. printf("curl_wasy_perform error = %s",curl_easy_strerror(code));
  214. }
  215. if ( headers != NULL )
  216. {
  217. curl_slist_free_all(headers);
  218. }
  219. curl_easy_cleanup(curl);
  220. 打印出来
  221. //std::string strReportData;
  222. //strReportData.append(strReportHeader);
  223. //strReportData.append(strReport);
  224. //TRACE("request:%s url:%s report:%s", strRequestType.c_str(), strUrl.c_str(), strReportData.c_str());
  225. return code;
  226. }
  227. /*
  228. * 函数:
  229. * RequestSSL(表单提交)
  230. * 参数:
  231. * strUrl:请求url地址
  232. * strReport:回执信息
  233. * vecHeader:请求头
  234. * strCookie:cookie信息
  235. * listParam:表单列表
  236. * strCaPath:ca转成pem证书路径
  237. * nTimeOut:超时设置默认是0秒 是无限等待:
  238. * 返回值:
  239. * 0表示成功 非0表示错误代码
  240. */
  241. int CUrlHttp::RequestSSL(std::string strUrl,
  242. std::string &strReport,
  243. _POST_LIST_DATA_ listParam,
  244. std::vector<std::string> vecHeader,
  245. std::string strCookie/* ="" */,
  246. std::string strCaPath/* ="" */,
  247. int nTimeOut/* =0 */)
  248. {
  249. CURLcode code;
  250. CURL * curl;
  251. curl = curl_easy_init();
  252. curl_easy_setopt(curl, CURLOPT_POST, 1);
  253. curl_easy_setopt(curl, CURLOPT_URL, strUrl.c_str());
  254. //err = curl_easy_setopt(hCurl, CURLOPT_HTTPHEADER, "dfsdf");
  255. //设置http头
  256. curl_slist * headers = NULL;
  257. for ( int i=0; i<vecHeader.size(); i++ )
  258. {
  259. if (!vecHeader.at(i).empty())
  260. {
  261. headers = curl_slist_append(headers, vecHeader.at(i).c_str());
  262. }
  263. }
  264. if (headers != NULL)
  265. {
  266. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  267. }
  268. struct curl_httppost *post=NULL;
  269. struct curl_httppost *last=NULL;
  270. CURLFORMcode errf;
  271. for ( int i=0; i<listParam.size(); i++ )
  272. {
  273. POST_LIST post_list = listParam.at(i);
  274. if (post_list.eKeyType == e_key_iamge ) //图片类型 直接提交图片路径
  275. {
  276. errf = curl_formadd(&post, &last, CURLFORM_COPYNAME, post_list.strKey.c_str(),
  277. CURLFORM_FILE,post_list.strVal.c_str(),CURLFORM_CONTENTTYPE, "image/jpeg",CURLFORM_END);
  278. }
  279. else
  280. {
  281. errf = curl_formadd(&post, &last, CURLFORM_COPYNAME, post_list.strKey.c_str(),
  282. CURLFORM_COPYCONTENTS, post_list.strVal.c_str(),CURLFORM_END);
  283. }
  284. }
  285. curl_easy_setopt(curl, CURLOPT_READFUNCTION, NULL);
  286. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, _CURL_::write_data);
  287. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &strReport);
  288. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
  289. //判断是否有证书
  290. if(strCaPath.empty())
  291. {
  292. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);
  293. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, false);
  294. }
  295. else
  296. {
  297. //缺省情况就是PEM,所以无需设置,另外支持DER
  298. //curl_easy_setopt(curl,CURLOPT_SSLCERTTYPE,"PEM");
  299. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, true);
  300. curl_easy_setopt(curl, CURLOPT_CAINFO, strCaPath.c_str());
  301. }
  302. //设置超时时间
  303. if ( nTimeOut > 0 )
  304. {
  305. curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, nTimeOut);
  306. curl_easy_setopt(curl, CURLOPT_TIMEOUT, nTimeOut);
  307. }
  308. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION,1); //是否抓取跳转后的页面
  309. /* Set the form info */
  310. curl_easy_setopt(curl, CURLOPT_HTTPPOST, post); //
  311. curl_easy_setopt(curl, CURLOPT_HEADER, 0); //不读取返回头的数据
  312. //设置http cookie
  313. if (!strCookie.empty())
  314. {
  315. curl_easy_setopt(curl, CURLOPT_COOKIEFILE, strCookie.c_str());
  316. }
  317. code = curl_easy_perform(curl); /* post away! */
  318. //获取请求返回的值 如:200
  319. //code = curl_easy_getinfo(curl,CURLINFO_RESPONSE_CODE, &RESPONSE_CODE);
  320. /* free the post data again */
  321. if ( headers != NULL )
  322. {
  323. curl_slist_free_all(headers);
  324. }
  325. curl_formfree(post);
  326. curl_easy_cleanup(curl);
  327. return code;
  328. }
  329. /********************************************************************************************
  330. * curl FTP 类封装 *
  331. *
  332. *
  333. *********************************************************************************************/
  334. CUrlFtp::CUrlFtp()
  335. {
  336. curl = NULL;
  337. }
  338. CUrlFtp::~CUrlFtp()
  339. {
  340. close();
  341. }
  342. /*
  343. * 函数:
  344. * connect(ftp连接)
  345. * 参数:
  346. * user:ftp帐号
  347. * password:ftp密码
  348. * ip:ftpip
  349. * port:ftp端口
  350. * 返回值:
  351. * 成功返回0 失败返回-1
  352. *
  353. */
  354. int CUrlFtp::connect( const char *user, const char *password, const char * ip, short port /*=21*/)
  355. {
  356. curl = curl_easy_init();
  357. if ( curl == NULL )
  358. {
  359. m_lastError.assign("curl initialization failure!");
  360. printf("curl initialization failure!\n");
  361. return -1;
  362. }
  363. //设置登录帐号和密码
  364. std::string spider;
  365. spider.append(user);
  366. spider.append(":");
  367. spider.append(password);
  368. curl_easy_setopt(curl, CURLOPT_USERPWD, spider.c_str());
  369. std::string url;
  370. url.append("ftp://");;
  371. url.append(ip);
  372. if ( port != 0 )
  373. {
  374. url.append(":");
  375. char szPort[10];
  376. sprintf(szPort, "%d", port);
  377. url.append(szPort);
  378. }
  379. curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
  380. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
  381. CURLcode code = curl_easy_perform(curl);
  382. if ( code != CURLE_OK )
  383. {
  384. m_lastError = curl_easy_strerror( code );
  385. printf("ftp connect failure: %s!\n", m_lastError.c_str());
  386. close();
  387. return -1;
  388. }
  389. m_ip.assign(ip);
  390. m_user.assign(user);
  391. m_password.assign(password);
  392. m_port = port;
  393. m_lastError.assign("ftp connect success!");
  394. printf("ftp connect success!\n");
  395. return 0;
  396. }
  397. /*
  398. * 函数:
  399. * close(ftp关闭)
  400. * 参数:
  401. * 无
  402. * 返回值:
  403. * 无
  404. *
  405. */
  406. void CUrlFtp::close()
  407. {
  408. if ( curl != NULL )
  409. {
  410. curl_easy_cleanup(curl);
  411. curl = NULL;
  412. }
  413. }
  414. /*
  415. * 函数:
  416. * download(ftp文件下载)
  417. * 参数:
  418. * remoteFile:远端文件路径
  419. * localFile:本地文件路径
  420. * timeOut:超时时间 单位秒
  421. * 返回值:
  422. * 成功返回0 失败返回-1
  423. *
  424. */
  425. int CUrlFtp::download(const char * remoteFile, const char * localFile, size_t timeOut /*= 0*/)
  426. {
  427. if ( curl == NULL )
  428. {
  429. m_lastError.assign("ftp disconnect!");
  430. printf("ftp disconnect!");
  431. return -1;
  432. }
  433. std::string newRemotePath = CTools::replace(remoteFile, "\\", "/" );
  434. std::string newLocalPath = CTools::replace(localFile, "\\", "/" );
  435. _CURL_::FTP_FILE ftpfile;
  436. sprintf(ftpfile.filename, "%s",newLocalPath.c_str());
  437. ftpfile.stream = NULL;
  438. std::string url;
  439. url.append("ftp://");;
  440. url.append(m_ip);
  441. url.append(":");
  442. char szPort[10];
  443. sprintf(szPort, "%d", m_port);
  444. url.append(szPort);
  445. url.append("/");
  446. url.append(newRemotePath);
  447. curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
  448. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, _CURL_::ftp_write);
  449. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &ftpfile);
  450. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
  451. if ( timeOut > 0 )
  452. {
  453. curl_easy_setopt(curl, CURLOPT_FTP_RESPONSE_TIMEOUT, timeOut);
  454. }
  455. CURLcode code = curl_easy_perform(curl);
  456. if ( code != CURLE_OK )
  457. {
  458. m_lastError = curl_easy_strerror( code );
  459. printf("ftp download failure: %s!\n", m_lastError.c_str());
  460. return -1;
  461. }
  462. if (ftpfile.stream != NULL )
  463. {
  464. fclose(ftpfile.stream);
  465. ftpfile.stream = NULL;
  466. }
  467. m_lastError.assign("ftp upload success!");
  468. return 0;
  469. }
  470. /*
  471. * 函数:
  472. * upload(ftp文件上传)
  473. * 参数:
  474. * remoteFile:远端文件路径
  475. * localFile:本地文件路径
  476. * timeOut:超时时间 单位秒
  477. * 返回值:
  478. * 成功返回0 失败返回-1
  479. *
  480. */
  481. int CUrlFtp::upload(const char * remoteFile, const char * localFile, size_t timeOut/*=0*/)
  482. {
  483. if ( curl == NULL )
  484. {
  485. m_lastError.assign("ftp disconnect!");
  486. printf("ftp disconnect!");
  487. return -1;
  488. }
  489. std::string newRemotePath = CTools::replace(remoteFile, "\\", "/" );
  490. std::string newLocalPath = CTools::replace(localFile, "\\", "/" );
  491. CURLcode code;
  492. FILE *hd_src;
  493. struct stat file_info;
  494. curl_off_t fsize;
  495. std::size_t nItem = newRemotePath.find_last_of("/");
  496. std::string remoteFileName = newRemotePath.substr(nItem+1);//文件名称
  497. std::string remotePath = newRemotePath.substr(0, nItem);//远端路径
  498. struct curl_slist *headerlist = NULL;
  499. char buf_1 [256] = "RNFR while-uploading";
  500. char buf_2 [256]; //远端文件名称
  501. sprintf(buf_2,"RNTO %s", remoteFileName.c_str());
  502. if(stat(newLocalPath.c_str(), &file_info))
  503. {
  504. m_lastError.assign("the uploaded file does not exist!");
  505. printf("the uploaded file does not exist(%s)!\n", localFile);
  506. return -1;
  507. }
  508. fsize = (curl_off_t)file_info.st_size;
  509. hd_src = fopen(newLocalPath.c_str(), "rb");
  510. if ( hd_src == NULL )
  511. {
  512. m_lastError.assign("file open failed!");
  513. printf("file open failed(%s)!\n", localFile);
  514. return -1;
  515. }
  516. headerlist = curl_slist_append(headerlist, buf_1);
  517. headerlist = curl_slist_append(headerlist, buf_2);
  518. curl_easy_setopt(curl, CURLOPT_READFUNCTION, _CURL_::ftp_read);
  519. curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);
  520. //设置ftp url
  521. std::string url = "ftp://";
  522. url.append(m_ip);
  523. url.append(":");
  524. char szPort[10];
  525. sprintf(szPort, "%d", m_port);
  526. url.append(szPort);
  527. url.append("/");
  528. url.append(remotePath);
  529. url.append("/");
  530. url.append("while-uploading");
  531. curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
  532. curl_easy_setopt(curl, CURLOPT_POSTQUOTE, headerlist);
  533. curl_easy_setopt(curl, CURLOPT_READDATA, hd_src);
  534. curl_easy_setopt(curl, CURLOPT_INFILESIZE_LARGE,(curl_off_t)fsize);
  535. if ( timeOut > 0 )
  536. {
  537. curl_easy_setopt(curl, CURLOPT_FTP_RESPONSE_TIMEOUT, timeOut);
  538. }
  539. code = curl_easy_perform(curl);
  540. curl_slist_free_all(headerlist);
  541. if ( code != CURLE_OK )
  542. {
  543. fclose(hd_src);
  544. m_lastError = curl_easy_strerror( code );
  545. printf("ftp upload failure: %s!\n", m_lastError.c_str());
  546. return -1;
  547. }
  548. fclose(hd_src);
  549. m_lastError.assign("ftp upload success!");
  550. return code;
  551. }
  552. /*
  553. * 函数:
  554. * dirlist(远端目录列表获取)
  555. * 参数:
  556. * remote:远端目录路径
  557. * vecFileInfo:输出遍历得到的文件夹和文件
  558. * 返回值:
  559. * 成功返回0 失败返回-1
  560. *
  561. */
  562. int CUrlFtp::dirlist(const char * remote, std::vector<FILE_INFO> &vecFileInfo)
  563. {
  564. if ( curl == NULL )
  565. {
  566. m_lastError.assign("ftp disconnect!");
  567. printf("ftp disconnect!");
  568. return -1;
  569. }
  570. std::string remotePath = CTools::replace(remote, "\\", "/" );
  571. if ( remotePath.size() == 0 )
  572. {
  573. remotePath.append("/");
  574. }
  575. if ( remotePath[remotePath.length()-1] != '/')
  576. {
  577. remotePath.append("/");
  578. }
  579. std::string url;
  580. url.append("ftp://");;
  581. url.append(m_ip);
  582. url.append(":");
  583. char szPort[10];
  584. sprintf(szPort, "%d", m_port);
  585. url.append(szPort);
  586. url.append("/");
  587. url.append(remotePath);
  588. std::string response;
  589. curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
  590. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
  591. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, _CURL_::write_data);
  592. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
  593. CURLcode code = curl_easy_perform(curl);
  594. if ( code != CURLE_OK )
  595. {
  596. m_lastError = curl_easy_strerror( code );
  597. printf("ftp connect failure: %s!\n", m_lastError.c_str());
  598. return -1;
  599. }
  600. //解析ftp数据得到文件和文件夹属性
  601. std::string::size_type pos=0, index=0, len=0;
  602. while( true )
  603. {
  604. std::string row= "";
  605. pos = response.find("\r\n", pos)+2;
  606. if ( pos < index )
  607. {
  608. break;
  609. }
  610. len = pos - index;//需要截取的字符串长度
  611. row = response.substr(index, len); //得到每行数据
  612. index = pos;
  613. std::string::size_type rowPos=0, rowIndex=0, rowLen=0;
  614. //得到名称
  615. FILE_INFO fileInfo;
  616. rowPos = row.find_last_of(' ')+1;
  617. std::string name = row.substr(rowPos, row.length());
  618. if ( name.size() == 0 || name[0] == '.')
  619. {
  620. continue;
  621. }
  622. fileInfo.name = name;
  623. //得到文件权限和文件类型
  624. rowPos = row.find_first_of(' ');
  625. std::string data = row.substr(0,rowPos);
  626. if ( data.size() != 0 )
  627. {
  628. if (data[0] == 'd')
  629. {
  630. //文件夹
  631. fileInfo.type = 0;
  632. fileInfo.permissions = data.substr(1, data.length());
  633. }
  634. else
  635. {
  636. //文件
  637. fileInfo.type = 1;
  638. fileInfo.permissions = data.substr(1, data.length());
  639. }
  640. }
  641. vecFileInfo.push_back(fileInfo);
  642. }
  643. m_lastError.assign("");
  644. return 0;
  645. }
  646. /*
  647. * 函数:
  648. * getLastError(最后错误信息)
  649. * 参数:
  650. * 无
  651. * 返回值:
  652. * 对应的错误信息
  653. *
  654. */
  655. const char * CUrlFtp::getLastError()
  656. {
  657. return m_lastError.c_str();
  658. }

调用

  1. 调用libcurl类库时需引用头文件,
  2. #include <iostream>
  3. #include <XXX.h>
  4. using namespace std;
  5. void main()
  6. {
  7. CUrlHttp *curlhttp = new CUrlHttp();
  8. string strReport;
  9. vector<string> vecHeader;
  10. vecHeader.push_back("Content-Type:application/json;charset=UTF-8");
  11. vecHeader.push_back("\"UserAgent\":\"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36\"");
  12. vecHeader.push_back("\"Connection\":\"Keep-Alive\"");
  13. string strParam="{\"method\":\"ToolManger\",\"ack\":1,\"params\":{\"username\":\"shufac\",\"password\":\"shufac\",\"toolid\":\"8\",\"mac\":\"48:4D:7E:AB:BF:EB\"}}";
  14. //std::string strParam="{\"method\":\"ToolManger\",\"ack\":1,\"params\":{\"username\":\"csf\",\"password\":\"csf\",\"toolid\":\"10\",\"mac\":\"48:4D:7E:AB:BF:EB\"}}";
  15. curlhttp->Request("POST","https://oa.notioni.com/notionSystem/a/sw/tools/access/query",strReport,vecHeader,strParam);
  16. CString str = strReport.c_str();
  17. delete curlhttp;
  18. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/685435
推荐阅读
相关标签
  

闽ICP备14008679号