c++基于libevent库实现的客户端和服务端(GET和POST)
头文件:http_event.hpp
#ifndef __HTTP_EVENT_HPP__
#define __HTTP_EVENT_HPP__
#include <iostream>
#include <sstream>
#include "evhttp.h"
#include "event.h"
using namespace std;
// ev http server
class evHttpServer
{
private:
string ip;
int port;
struct evhttp *http_server = NULL;
struct event_base *base = NULL;
public:
evHttpServer(string ip, int port) : ip(ip), port(port){};
// 创建http 绑ip端口
bool serverConnect();
// 设置服务超时时间
void setHttpTimeout(int timeout);
/*
接口注册
@param path 接口路径 如"/get_task"
@param cb 处理该接口的回调
@param cb_arg 回调的参数
*/
void interfaceRegister(const char *path,
void (*cb)(struct evhttp_request *, void *),
void *cb_arg = NULL);
// 循环监听
void loopListen();
~evHttpServer();
public:
/*
http响应
@param code - 响应码
@param reason - 响应码对应的说明, 为NULL,使用默认的响应码说明
@param body - body, 为NULL, 没有body
*/
static void reply(evhttp_request *request, int code, const char *reason, const char *body);
// Get回调函数例子
static void cbGETSample(struct evhttp_request *request, void *arg);
// 解析request获取GET请求参数
static char *findGetParam(struct evhttp_request *request, struct evkeyvalq *params, const char *query_char);
// Post回调函数例子
static void cbPOSTSample(struct evhttp_request *request, void *arg);
};
// ev http client
class evhttpClient
{
private:
string ip;
int port;
string path = "";
string body = "";
int timeout = 10;
public:
/*
@param path 资源路径可以包含GET请求参数部分
如"/getparam?param1=123456¶m2=456789"
*/
evhttpClient(string ip, int port, string path);
// 直接传入URL进行初始化
evhttpClient(string url);
// 添加GET请求参数
void addGetParam(string name, string value);
// 设置包体
void setBody(string body);
// 返回请求的url
string getUrl();
// 设置请求超时时间
void setTimeout(int timeout);
/*
发送GET/POST请求
@param type http请求类型
EVHTTP_REQ_GET 1
EVHTTP_REQ_POST 2
*/
bool sendHttpRequest(evhttp_cmd_type type);
~evhttpClient();
private:
// 请求回调函数,可以自行在类外实现
static void requestCallback(struct evhttp_request *request, void *arg);
};
#endif
源文件:http