不说废话,直接先上代码吧。
#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的类。需要初始化CWinApp app((LPCTSTR)argv[0]);
app.InitApplication();
AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0);
详细参考:http://blog.youkuaiyun.com/dotneterbj/article/details/18778449
2 就是使用 file->ReadString 获取 url上的数据时,可能会出现乱码情况。解决方法已经给出了。参考:http://blog.sina.com.cn/s/blog_69ebf25c0100mbdx.html
3 编译时,发生Building MFC application with /MD[d] (CRT dll version) requires MFC shared dll version 错误解决
参考:http://blog.163.com/zhengjiu_520/blog/static/35598306201004104633952/
4 感谢boost库的伟大,让我们不需要下载其他的lib或者头文件什么的,可以直接解析jason字符串。