POCO库下访问http获取json串

1.首先需要去官网下载POCO库,地址点击打开链接

2.根据不同的VS版本编译POCO库,将生成的incude头文件、bin文件和lib文件拷到VS目录下就可进行编译

(这是官网的文档,可参考下点击打开链接)

下面是具体的代码(包括数据的获取和解析):

#include "stdafx.h"
#include 
#include "Poco/Net/HTMLForm.h"
#include "Poco/URI.h"
#include "Poco/Net/HTTPClientSession.h"
#include "Poco/Net/HTTPRequest.h"
#include "Poco/Net/HTTPResponse.h"
#include "Poco/StreamCopier.h"
#include "Poco/Net/NetException.h"

#include "Poco/JSON/Object.h"
#include "Poco/JSON/Parser.h"
#include "Poco/Dynamic/Var.h"

#include "Poco/ASCIIEncoding.h"
#include "Poco/UTF8Encoding.h"
#include "Poco/UTF16Encoding.h"
#include "Poco/TextConverter.h"

#include 
#include 

using namespace::Poco::JSON;

int _tmain(int argc, _TCHAR* argv[])
{
	Poco::URI purl("");//输入要访问的Url

	try
	{
		Poco::Net::HTTPClientSession session(purl.getHost(), purl.getPort());
		Poco::Net::HTTPRequest req(Poco::Net::HTTPRequest::HTTP_GET, purl.getPath(), Poco::Net::HTTPMessage::HTTP_1_1);
		Poco::Net::HTMLForm form;//创建一个表单

		//form.add("channel", "cctv1");
		
		// Send the request.
		form.prepareSubmit(req);
		std::ostream& ostr = session.sendRequest(req);
		form.write(ostr);//提交post的键值信息

		Poco::Net::HTTPResponse res;

		std::istream& istr = session.receiveResponse(res);
		//上句接收网站回应的信息 返回输入流 并copy到标准控制台输出流
		//Poco::StreamCopier::copyStream(istr, std::cout);

		std::string temp;
		Poco::StreamCopier::copyToString(istr, temp);
		std::cout << temp << std::endl; //将返回结果输出

		//解析字符串,下面的data和title要根据JSON数据选择
		Parser parser;
		Poco::Dynamic::Var result = parser.parse(temp);
		Poco::JSON::Object::Ptr object = result.extract();

		Poco::Dynamic::Var test = object->get("data"); 
		Object::Ptr secobject = test.extract();

		Poco::Dynamic::Var name = secobject->get("title");

		const std::string nameStr = name.toString();

		std::cout << nameStr << std::endl;

	}
	catch (Poco::Net::NetException& ex)
	{
		std::cout << "post wrong: " << ex.displayText();
	}

	system("PAUSE");


	return 0;
}






 
  

 
  




你可能感兴趣的:(poco库)