使用libmicrohttpd处理POST请求 [英] Handling a POST request with libmicrohttpd
问题描述
我将使用libmicrohttpd来设置REST服务器。 GET请求没有问题,但我不明白我在处理POST(实际上是PUT)请求(JSON格式)时做错了什么。以下是代码:
I've to use libmicrohttpd to set up a REST server. There is no problem with the GET request, but I don't understand what I'm doing wrong to handle POST (PUT actually) request (JSON format). Here is the code :
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;
}
每次我尝试发送带有一些数据的PUT请求时,我都会得到内部应用程序错误,关闭连接。问题可能来自以下方面之一:
Everytime I try to send a PUT request with some data, I get the "Internal application error, closing connection". The problem may come from one of these things:
-
在第一次致电时发布/不发布回复
posting/not-posting response at the first call of the fucntion
修改* upload_data_size(表示处理已完成)
modifying or not the *upload_data_size (to indicate that processing is done)
好位置 * con_cls = NULL
指令
谢谢!
推荐答案
我遇到了同样的问题并通过一些调试发现了解决方案。
I ran into this same problem and discovered the solution through some debugging.
当库使用 request_data
调用您的处理程序时,不允许对任何响应进行排队( MHD_queue_response
返回 MHD_NO
)。你需要等到最后的处理程序调用没有 request_data
来调用 MHD_queue_response
。
When the library calls your handler with request_data
, you're not allowed to queue any responses (MHD_queue_response
returns MHD_NO
). You need to wait until the final handler call with no request_data
to call MHD_queue_response
.
据我所知,这个行为没有记录。
This behavior isn't documented as far as I can tell.
这篇关于使用libmicrohttpd处理POST请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!