美文网首页
libmicrohttpd获取http body

libmicrohttpd获取http body

作者: pandazhong | 来源:发表于2018-10-13 14:18 被阅读0次

    libmicrohttpd是一个c实现的轻量级,高性能的http server,可以嵌入程序中,但是这个库获取http的body比较麻烦。

    #include <stdio.h>

    #include <string>

    #include <stdlib.h>

    #include "microhttpd.h"

    #define PAGE "<html><head><title>panda/title>"\

    "</head><body>hello, i am panda, nice to meet you.</body></html>"

    struct postStatus {

    bool status;

    char *buff;

    };

    bool getHttpBody(void *cls, MHD_Connection *connection, const char *url, const char *method, const char *version,

    const char *upload_data, size_t *upload_data_size, void **ptr,std::string &body)

    {

    struct postStatus *post = NULL;

    post = (struct postStatus*)*ptr;

    if (post == NULL) {

    post = (postStatus *)malloc(sizeof(struct postStatus));

    post->status = false;

    *ptr = post;

    }

    if (!post->status) {

    post->status = true;

    return false;

    }

    else {

    if (*upload_data_size != 0) {

    post->buff = (char *)malloc(*upload_data_size + 1);

    memset(post->buff, 0, *upload_data_size + 1);

    _snprintf(post->buff, *upload_data_size, "%s", upload_data);

    *upload_data_size = 0;

    return false;

    }

    else {

    body = post->buff;

    free(post->buff);

    }

    }

    if (post != NULL)

    {

    free(post);

    }

    return true;

    }

    int onProcess(void *cls, MHD_Connection *connection, const char *url, const char *method, const char *version,

    const char *upload_data, size_t *upload_data_size, void **ptr)

    {

    const char * page = (const char *)cls;

    struct MHD_Response * response;

    int ret;

    std::string body;

    if (getHttpBody(connection, connection,  url, method, version, upload_data, upload_data_size, ptr, body) == false)

    {

    return MHD_YES;

    }

    printf("%s\n", body.c_str());

    // 第三个参数建议建议使用MHD_RESPMEM_MUST_COPY

    response = MHD_create_response_from_buffer(strlen(page), (void*)page, MHD_RESPMEM_MUST_COPY);

    ret = MHD_queue_response(connection, MHD_HTTP_OK, response);

    MHD_destroy_response(response);

    return ret;

    }

    int main(int argc, char* argv[])

    {

    struct MHD_Daemon *d;

    d = MHD_start_daemon(

    MHD_USE_AUTO | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,

    4000, // http端口号

    NULL, NULL, &onProcess, PAGE,

    MHD_OPTION_END);

    if (d == NULL)

    return 1;

    (void)getc(stdin);

    MHD_stop_daemon(d);

    return 0;

    }

    相关文章

      网友评论

          本文标题:libmicrohttpd获取http body

          本文链接:https://www.haomeiwen.com/subject/cheoaftx.html