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

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

#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
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值