C++ libEvent Http协议(客户端)

#include <errno.h>
#include <stdlib.h>
#include <string>
#include <time.h>

#include <event2/event.h>
#include <event2/buffer.h>
#include <event2/http.h>
#include <event2/http_struct.h>
#include <event2/keyvalq_struct.h>
#include <event2/listener.h>
#include <event2/util.h>
#include <event2/bufferevent.h>

extern
std::string EncodeUtf8fromString(std::string in);//发string类型的时候用

extern
std::string DecodeUtf8fromString(std::string in);//收string类型的时使用

void http_request_done(struct evhttp_request *req, void *arg){
    char buf[1024];
    int s = evbuffer_remove(req->input_buffer, &buf, sizeof(buf)-1);
    buf[s] = '\0';
    //printf("%s\n", buf);
    //terminate event_base_dispatch()
    event_base_loopbreak((struct event_base *)arg);
}

int main(int argc, char **argv)
{
    WSADATA wsa_data;
    WSAStartup(0x0201, &wsa_data);

    //定义url
    char* url = "http://10.10.180.208:8080/singleStation/transport/notice";
    struct evhttp_uri* uri = evhttp_uri_parse(url);
    if (!uri)
    {
        fprintf(stderr, "parse url failed!\n");
        return -1;
    }
    //初始化base
    struct event_base* base = event_base_new();
    if (!base)
    {
        fprintf(stderr, "create event base failed!\n");
        return 1;
    }
    //获取host
    const char* host = evhttp_uri_get_host(uri);
    if (!host)
    {
        fprintf(stderr, "parse host failed!\n");
        return 1;
    }
    //解析url
    int port = evhttp_uri_get_port(uri);
    if (port < 0) port = 80;
    const char* request_url = url;
    const char* path = evhttp_uri_get_path(uri);
    if (path == NULL || strlen(path) == 0)
    {
        request_url = "/";
    }
    struct evhttp_connection *conn;
    conn = evhttp_connection_base_new(base, NULL, host, port);
    if (!conn)
    {
        fprintf(stderr, "create evhttp connection failed!\n");
        return 1;
    }
    //设置超时
    evhttp_connection_set_timeout(conn, 600);
    evhttp_connection_set_retries(conn, -1);
    //创建request
    struct evhttp_request *req;
    req = evhttp_request_new(http_request_done, base);
    //添加header
    evhttp_add_header(req->output_headers, "Host", host);
    evhttp_add_header(req->output_headers, "Content-Type", "application/json");
    //创建json
    char *post_data = "{\"robot_ip\":\"127.0.0.1\",\"desc\":\"测试\",\"need_confirm\":1}";
    std::string data = EncodeUtf8fromString(post_data);
    evbuffer_add(req->output_buffer, data.data(), strlen(data.data()));
    int result = evhttp_make_request(conn, req, EVHTTP_REQ_POST, request_url);
    printf("result:%d \n", result);
    event_base_dispatch(base);

    return 0;
}

猜你喜欢

转载自blog.csdn.net/xiaoshunzi111/article/details/112358991