C++使用CInternetSession请求url下载jason数据,并且进行解析。以及注意事项

来源:互联网 发布:淘宝卖家登入 编辑:程序博客网 时间:2024/06/05 16:45
不说废话,直接先上代码吧。
#include "stdafx.h"#include "string"#include <afxinet.h>#include <afxwin.h>#include <atlconv.h>#include <boost/property_tree/ptree.hpp>#include <boost/property_tree/json_parser.hpp>using namespace std;using namespace boost::property_tree;int _tmain(int argc, _TCHAR* argv[]){CWinApp app((LPCTSTR)argv[0]);app.InitApplication();AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0);CInternetSession session;CHttpFile *file=NULL;CString strURL="********************";try{file=(CHttpFile*)session.OpenURL(strURL);}catch(CInternetException * m_pExection){file=NULL;m_pExection->m_dwError;m_pExection->Delete();session.Close();}char urlData[1024];CString result="";if (file!=NULL){//注意:file->ReadString((LPTSTR)urlData,1024) ,可以解决乱码问题。如果直接file->ReadString(CString)就会乱码while (file->ReadString((LPTSTR)urlData,1024)!=NULL){result+=urlData;}}   USES_CONVERSION;string sdata=W2A(result.GetBuffer());ptree pt;stringstream stream;stream<<sdata;read_json<ptree>(stream,pt);int userid=pt.get<int>("userid");return 0;}
注意事项:
1 win32 应用程序使用 mfc的类。需要初始化
<pre name="code" class="html"><span style="white-space:pre"></span>CWinApp app((LPCTSTR)argv[0]);app.InitApplication();AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0);
详细参考:http://blog.csdn.net/dotneterbj/article/details/18778449
2 就是使用  <span style="font-family: Arial, Helvetica, sans-serif;">file->ReadString 获取 url上的数据时,可能会出现乱码情况。解决方法已经给出了。参考:http://blog.sina.com.cn/s/blog_69ebf25c0100mbdx.html</span>
<span style="font-family: Arial, Helvetica, sans-serif;">3 编译时,发生</span><span style="color: rgb(21, 130, 203); font-family: 'Hiragino Sans GB W3', 'Hiragino Sans GB', Arial, Helvetica, simsun, u5b8bu4f53; font-size: 16px; line-height: 28px; text-indent: 32px;">Building MFC application with /MD[d] (CRT dll version) requires MFC shared dll version 错误解决</span>
<span style="color: rgb(21, 130, 203); font-family: 'Hiragino Sans GB W3', 'Hiragino Sans GB', Arial, Helvetica, simsun, u5b8bu4f53; font-size: 16px; line-height: 28px; text-indent: 32px;"> 参考:http://blog.163.com/zhengjiu_520/blog/static/35598306201004104633952/</span>
<span style="color: rgb(21, 130, 203); font-family: 'Hiragino Sans GB W3', 'Hiragino Sans GB', Arial, Helvetica, simsun, u5b8bu4f53; font-size: 16px; line-height: 28px; text-indent: 32px;">4 感谢boost库的伟大,让我们不需要下载其他的lib或者头文件什么的,可以直接解析jason字符串。</span>
                                             
1 0