使用libmicrohttpd处理POST请求

Pie*_*rre 2 c++ http put

我必须使用libmicrohttpd设置REST服务器。GET请求没有问题,但是我不明白我在处理POST(实际上是PUT)请求(JSON格式)时做错了什么。这是代码:

int MHD_answer_to_connection (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) {


  // Initializes parser/camera/settings...
  static Parser parser;

  // The first time only the headers are valid, do not respond in the first round
  static int dummy;
  if (*con_cls != &dummy) {
    *con_cls = &dummy;
    return MHD_YES;
  }

  // Parse URL to get the resource
  int resource = parser.getRequestedResource(url);

  // Check wether if it's a GET or a POST method
  if(strcmp(method, MHD_HTTP_METHOD_GET) == 0) {
    parser.processGetRequest(resource);
  }
  else {
    parser.processPutRequest(upload_data, *upload_data_size);
  }

  // Building HTTP response (headers+data)
  MHD_Response* httpResponse = parser.getResponse();

  int ret = MHD_queue_response (connection, MHD_HTTP_OK, httpResponse);

  if (ret != MHD_YES) {
    Logger::get().error("Error queuing message");
  }

  MHD_destroy_response (httpResponse);
  // Clear context pointer
  *con_cls = NULL; 

  return ret;
}
Run Code Online (Sandbox Code Playgroud)

每次尝试发送包含一些数据的PUT请求时,都会收到“内部应用程序错误,正在关闭连接”。问题可能来自以下其中一项:

  • 功能的第一次调用时发布/不发布响应

  • 是否修改* upload_data_size(以指示已完成处理)

  • 良好的*con_cls = NULL教学位置

谢谢!

sil*_*rog 5

我也使用GNU libmicrohttpd,并且在其存储库中找到了一个简单的POST演示。

该演示有点简单:它有一个询问您姓名的表格,因此当您键入姓名并单击“发送”按钮时,将在answer_to_connection()函数中处理发布的数据:

static int answer_to_connection (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 (0 == strcmp (method, "POST"))
    {
      struct connection_info_struct *con_info = *con_cls;

      if (*upload_data_size != 0)
        {
          MHD_post_process (con_info->postprocessor, upload_data,
                            *upload_data_size);
          *upload_data_size = 0;

          return MHD_YES;
        }
      else if (NULL != con_info->answerstring)
        return send_page (connection, con_info->answerstring);
    }
...
Run Code Online (Sandbox Code Playgroud)


小智 5

我遇到了同样的问题,并通过一些调试找到了解决方案。

当库使用 调用您的处理程序时request_data,您不允许对任何响应进行排队(MHD_queue_response返回MHD_NO)。您需要等到最后的处理程序调用 no request_datato call MHD_queue_response

据我所知,这种行为没有记录在案。