如何直接获取 libmicrohttpd 库中POST上来的整个数据

  • Post author:
  • Post category:其他

          由于 libmicrohttpd 库在处理POST数据的时候是与表单的形势处理的, HTTP协议中表单的提交和解析有特定的格式。但是在我们的需求中,我们POST上来的数据可能只是一个普通的XML体,并不是按照表单格式提交上来的数据,我们需要处理整个的XML体, 这个时候, libmicrohttpd 不能获取到整个 POST上来的BODY, 追踪源码,我们可以添加一点点代码即可获取该数据。修改的源码如下 :

/**
* Get a particular header value.  If multiple
* values match the kind, return any one of them.
*
* @param connection connection to get values from
* @param kind what kind of value are we looking for
* @param key the header to look for, NULL to lookup 'trailing' value without a key
* @return NULL if no such item was found
*/
const char * MHD_lookup_connection_value (struct MHD_Connection *connection, enum MHD_ValueKind kind, const char *key)
{
	struct MHD_HTTP_Header *pos;

	if (NULL == connection)
		return NULL;

        if (kind == MHD_POSTDATA_KIND) return connection->read_buffer;//只需要添加改行代码即可

	for (pos = connection->headers_received; NULL != pos; pos = pos->next)
		if ((0 != (pos->kind & kind)) && 
			( (key == pos->header) || ( (NULL != pos->header) &&
			(NULL != key) &&
			(0 == strcasecmp (key, pos->header))) ))
			return pos->value;    
	return NULL;
}

在上层应用层 ,我们可以用如下的代码来获取BODY数据:

	const char* length = MHD_lookup_connection_value (connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_CONTENT_LENGTH);
	if (length == NULL)
		return NULL;

	const char* body = MHD_lookup_connection_value (connection, MHD_POSTDATA_KIND, NULL);
	if (body == NULL)
	        return NULL;

			
	size_t len = strlen(body);

上面代码中的 body 即是我们POST提交上来的整个数据块。


版权声明:本文为langeldep原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。