C++实现http客户端连接服务端及客户端json数据的解析

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hfuu1504011020/article/details/88785532

上一篇中说到Unicode转utf8格式的过程,其中谈及到http以及json数据的解析,json解析其实也没啥说的,网上一大推,后面大概介绍下使用,本文着重介绍下c++客户端实现的http连接服务端并返回json数据的过程。

(重点)这里http的连接以及获取json数据过程使用的是多字节编码实现的,直接可以将其转为utf8编码存入mysql中。之前我因为使用的是Unicode编码,在本文代码的基础上再加入上一篇的编码转换也是可以实现Unicode转utf8格式过程。

我们看下http头文件所包含的参数以及函数

//////////////////////////////////// HttpClient.h
#ifndef HTTPCLIENT_H
#define HTTPCLIENT_H

#include <afxinet.h>
#include <string>
using namespace std;

#define  IE_AGENT  _T("Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)")

// 操作成功
#define SUCCESS        0
// 操作失败
#define FAILURE        1
// 操作超时 www.it165.net
#define OUTTIME        2

class CHttpClient
{
public:
	CHttpClient(LPCTSTR strAgent = IE_AGENT);
	virtual ~CHttpClient(void);

	/*static wchar_t* ANSIToUnicode(const char* str);
	static char* UnicodeToANSI(const wchar_t* str);
	static char* UnicodeToUTF8(const wchar_t* str);
    */ //在下面的ExecuteRequest函数中处理了多字节转utf8的方法,不需要再使用这三个函数,这里注释 
      //  的三句转码总觉得在使用时有问题,代码我一并贴出,供大家查找问题

	int HttpGet(LPCTSTR strUrl, LPCTSTR strPostData, string &strResponse);
	int HttpPost(LPCTSTR strUrl, LPCTSTR strPostData, string &strResponse);

private:
	int ExecuteRequest(LPCTSTR strMethod, LPCTSTR strUrl, LPCTSTR strPostData, string &strResponse);
	void Clear();

private:
	CInternetSession *m_pSession;
	CHttpConnection *m_pConnection;
	CHttpFile *m_pFile;
};

#endif // HTTPCLIENT_H

以上是http实现的头文件,以下为.cpp中代码实现过程,内容有点多,若只是使用的话粘贴复制即可

猜你喜欢

转载自blog.csdn.net/hfuu1504011020/article/details/88785532