mongoseオープンソースに基づいてプラットフォームネットワークライブラリにカプセル化されたhttpリクエスト、フェーズレコード.
3231 ワード
#pragma once
#include "mongoose.h"
typedef void(*CB_HTTP)(const char*pData,const unsigned uiDataLen,void*pUserData);
typedef struct StrHttpCallBack
{
CB_HTTP httpThunk;
CB_HTTP httpReply;
}STRHTTPCALLBACK,*pStrHttpCallBack;
class CMongsHttpClient
{
public:
CMongsHttpClient();
~CMongsHttpClient();
const char*szContentType = "Content - Type: application / x - www - form - urlencoded\r
";
public:
void RequestHttp(const char *szUrl, pStrHttpCallBack pCallBackStruct,const char *param = NULL);
private:
void ConnectHttp(const char *szurl, pStrHttpCallBack pCallBackStruct, const char *szContentType, const char *params);
static void ev_handler(struct mg_connection *nc, int ev, void *ev_data, void*pUserData);
public:
static bool m_bExitFlag;
static struct mg_mgr m_MgrHandle;
};
#include "stdafx.h"
#include "MongsHttpClient.h"
#include
using namespace std;
bool CMongsHttpClient::m_bExitFlag = false;
struct mg_mgr CMongsHttpClient::m_MgrHandle;
CMongsHttpClient::CMongsHttpClient()
{
mg_mgr_init(&m_MgrHandle, NULL);
}
CMongsHttpClient::~CMongsHttpClient()
{
}
void CMongsHttpClient::RequestHttp(const char*szUrl, pStrHttpCallBack pCallBackStruct, const char*param /*= NULL*/)
{
ConnectHttp(szUrl, pCallBackStruct, szContentType, param);
mg_mgr_free(&m_MgrHandle);
}
void CMongsHttpClient::ConnectHttp(const char *szurl, pStrHttpCallBack pCallBackStruct,const char *szContentType, const char *params)
{
mg_connect_http(&m_MgrHandle, ev_handler, pCallBackStruct, szurl, szContentType, params);
while (!m_bExitFlag) {
mg_mgr_poll(&m_MgrHandle, 1000);
}
m_bExitFlag = false;
}
void CMongsHttpClient::ev_handler(struct mg_connection *nc, int ev, void *ev_data, void*pUserData)
{
struct http_message *hm = NULL;
pStrHttpCallBack strHttpCB = NULL;
if (pUserData)
{
strHttpCB = (pStrHttpCallBack)pUserData;
}
int len = 0;
switch (ev) {
case MG_EV_CONNECT:
if (*(int *)ev_data != 0) {
/* fprintf(stderr, "connect() failed: %s
", strerror(*(int *)ev_data));*/
m_bExitFlag = true;
}
break;
case MG_EV_HTTP_CHUNK:
hm = (struct http_message *) ev_data;
if (strHttpCB)
{
if (strHttpCB->httpThunk)
{
strHttpCB->httpThunk(hm->body.p, hm->body.len, NULL);
nc->flags = MG_F_DELETE_CHUNK;
}
}
break;
case MG_EV_HTTP_REPLY:// http
hm = (struct http_message *) ev_data;
switch (hm->resp_code) {
case 200://
{
if (strHttpCB)
{
if (strHttpCB->httpReply)
{
strHttpCB->httpReply(hm->message.p, hm->message.len, NULL);
}
}
nc->flags |= MG_F_SEND_AND_CLOSE;
m_bExitFlag = true;
}
break;
case 302:// URI
{
// Cookie
struct mg_str *url = mg_get_http_header(hm, "Location");
// Location
string strURL;
strURL.append(url->p, url->len);
mg_connect_http(&m_MgrHandle, ev_handler, NULL, strURL.c_str(), NULL, NULL);
}
break;
default:
break;
}
break;
case MG_EV_CLOSE:
if (!m_bExitFlag) {
m_bExitFlag = true;
}
break;
default:
break;
}
}