在 C 语言中使用 Linux 的 HTTP 服务器接收 Qt 发送的 POST 请求的 POST 数据需要以下步骤:

  1. 在 Linux 上建立一个 HTTP 服务器,可以使用一些开源的库,如 libmicrohttpd,libevent 等。这些库可以处理 HTTP 请求和响应。

  2. 在 Qt 中使用 QNetworkAccessManager 发送 POST 请求,设置请求的 URL、请求头和 POST 数据。

  3. 在 Linux 的 HTTP 服务器代码中,处理接收到的 POST 请求。根据 HTTP 请求头中的 Content-Type 判断 POST 数据的格式,一般有 'application/x-www-form-urlencoded' 和 'multipart/form-data' 两种格式。

    • 如果是 'application/x-www-form-urlencoded' 格式,POST 数据可以通过查询字符串的方式进行解析。可以使用 C 语言的标准库函数,如 strtok 和 strchr 等来解析 POST 数据。

    • 如果是 'multipart/form-data' 格式,POST 数据需要进行解析,可以使用一些开源的库,如 libcurl,libmultipart 等。这些库可以帮助解析 'multipart/form-data' 格式的数据。

  4. 在 Linux 的 HTTP 服务器代码中,将解析后的 POST 数据进行处理,可以保存到文件或者进行其他业务逻辑的处理。

下面是一个简单的例子,演示了如何使用 libmicrohttpd 库在 C 语言中建立一个简单的 HTTP 服务器,并接收 Qt 发送的 POST 请求的 POST 数据。

#include <microhttpd.h>
#include <stdio.h>
#include <string.h>

int handle_request(void *cls, struct MHD_Connection *connection,
                   const char *url, const char *method,
                   const char *version, const char *upload_data,
                   size_t *upload_data_size, void **con_cls) {
  if (strcmp(method, "POST") == 0) {
    // 处理 POST 请求
    struct MHD_PostProcessor *pp;
    const char *postdata;
    size_t postdata_size;
    
    // 创建 POST 处理器
    pp = MHD_create_post_processor(connection, 1024, iterate_postdata, NULL);
    if (pp == NULL) {
      return MHD_NO;
    }
    
    // 读取 POST 数据
    MHD_post_process(pp, upload_data, *upload_data_size);
    *upload_data_size = 0;
    
    // 获取 POST 数据
    postdata = MHD_post_process(pp, NULL, 0);
    postdata_size = strlen(postdata);
    
    // 处理 POST 数据
    // TODO: 根据需要进行处理
    
    // 销毁 POST 处理器
    MHD_destroy_post_processor(pp);
  }

  // 返回响应
  const char *response = "HTTP/1.1 200 OK\r\n\r\nHello, World!";
  struct MHD_Response *mhd_response =
      MHD_create_response_from_buffer(strlen(response), (void *)response,
                                      MHD_RESPMEM_PERSISTENT);
  int ret = MHD_queue_response(connection, MHD_HTTP_OK, mhd_response);
  MHD_destroy_response(mhd_response);

  return ret;
}

int main(int argc, char *argv[]) {
  struct MHD_Daemon *daemon;

  // 创建 HTTP 服务器
  daemon = MHD_start_daemon(MHD_USE_SELECT_INTERNALLY, 8080, NULL, NULL,
                            &handle_request, NULL, MHD_OPTION_END);
  if (daemon == NULL) {
    printf("Failed to start HTTP server\n");
    return 1;
  }

  // 运行 HTTP 服务器
  getchar();

  // 停止 HTTP 服务器
  MHD_stop_daemon(daemon);

  return 0;
}

这是一个简单的例子,仅供参考。实际情况中,可能需要根据具体需求进行更多的处理,如处理 POST 数据的解析、验证、存储等。

C 语言 Linux HTTP 服务器接收 Qt 发送的 POST 请求数据

原文地址: https://www.cveoy.top/t/topic/qjuu 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录