我想编写一个简单的程序,通过 POST 或 GET 从表单中获取数据。一个简单的形式可以说是将两个数字相加。
我看到 libcurl 能够与 http 协议交谈,但我没有看到与此问题相关的任何示例。
我所看到的只是如何将数据发送到网页,而不是如何获取它。
感谢您的时间。
基于我的另一个项目的快速n-dirty,非常未经测试的例子 - 没有明示或暗示的保证。这假设二进制文件已正确部署在 Web 服务器上(例如,在cgi-bin
Apache 服务器上的目录下)并且输入表单已设置为正确调用它:
<form action="http://my-url.com/cgi-bin/adder" method="get"> <!-- or method="post" -->
<label for="v1">V1:</label><input type="text" name="v1"><br>
<label for="v2">V2:</label><input type="text" name="v2"><br>
<input type="submit" name="submitbutton" value="Add">
</form>
然后你的 C 代码看起来像
#include <stdio.h>
#include <stdlib.h>
int main( int argc, char **argv )
{
char *interface = getenv( "GATEWAY_INTERFACE" );
/**
* If interface is NULL, then we were not invoked through CGI.
* For this example we just fail silently.
*/
if ( !interface )
exit( EXIT_FAILURE );
char *method = getenv( "REQUEST_METHOD" );
/**
* If method is NULL, then we were not invoked through CGI;
* for this example we'll just fail silently
*/
if ( !method )
exit( EXIT_FAILURE );
if ( strcmp( method, "GET" ) == 0 )
{
/**
* We were invoked from a Web client with the HTTP GET method -
* input parameters will be in the QUERY_STRING environment
* variable as "param=value¶m=value"
*/
char *query_string = getenv( "QUERY_STRING" );
do_stuff_with( query_string );
}
else if ( strcmp( method, "POST" ) == 0 )
{
/**
* We were invoked from a Web client with the HTTP POST method -
* input parameters will be received via standard input
*/
char query_string[SOME_SIZE];
if ( fgets( query_string, sizeof query_string, stdin ) )
{
do_stuff_with( query_string );
}
else
// handle error
}
else
{
/**
* Input method is not GET or POST, log an error and fail
*/
fputs( "Don't know how to handle this request\n", stderr );
exit( EXIT_FAILURE );
}
}
任何返回到 Web 客户端的响应都将通过标准输出写入:
printf( "Content-type: text/xml\r\n\r\n" );
printf( "<!DOCTYPE HTML><html><head><title>Adder result</title></head>" );
printf( "<body><p>Result of add is %d</p></body></html>", add_result );
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句