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

不说废话,直接先上代码吧。

#include "stdafx.h"
#include "string"
#include 
#include 
#include 
#include 
#include 

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<(stream,pt);	
	int userid=pt.get("userid");
	return 0;
}

注意事项:
1 win32 应用程序使用 mfc的类。需要初始化
	CWinApp app((LPCTSTR)argv[0]);
	app.InitApplication();
	AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0);
详细参考:http://blog.csdn.net/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字符串。


你可能感兴趣的:(以备不时之需~!)