曲径通幽论坛

 找回密码
 立即注册
搜索
查看: 6722|回复: 0
打印 上一主题 下一主题

[Curl] 直接 POST 到静态页

[复制链接]

4918

主题

5880

帖子

3万

积分

GROAD

曲径通幽,安觅芳踪。

Rank: 6Rank: 6

积分
34395
跳转到指定楼层
楼主
发表于 2010-3-24 19:55:48 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
说明
Apache、IIS、Nginx等绝大多数web服务器,都不允许静态文件响应POST请求,否则会返回“HTTP/1.1 405 Method not allowed”错误。这里演示演示 curl 的示例程序,可以看看是不是这样子。

程序代码
#include <stdio.h>
#include <string.h>
#include <curl/curl.h>

int main(void)
{
  CURL *curl;
  CURLcode res;

  static const char *postthis="test";

  curl = curl_easy_init();
  if(curl) {
    curl_easy_setopt(curl, CURLOPT_URL, "http://www.groad.net/index.html");
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postthis);

    /* 如果我们不提供 POSTFIELDSIZE, libcurl 自己会 strlen() */
    curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (long)strlen(postthis));

    res = curl_easy_perform(curl);

    curl_easy_cleanup(curl);
  }
  return 0;
}
编译连接
`curl-config --cc --cflags --libs` -o post post.c
运行测试
L$ ./post
[Plain Text] 纯文本查看 复制代码
<html>
<head><title>405 Not Allowed</title></head>
<body bgcolor="white">
<center><h1>405 Not Allowed</h1></center>
<hr><center>nginx/0.6.37</center>
</body>
</html>
上面就是 POST 后被服务器返回的消息,说明服务器不支持响应给静态页面发出的 POST 。

如果直接用命令测试 curl 可以:
$ curl -d test http://www.groad.net/index.html
<html>
<head><title>405 Not Allowed</title></head>
<body bgcolor="white">
<center><h1>405 Not Allowed</h1></center>
<hr><center>nginx/0.6.37</center>
</body>
</html>
上面命令中,-d 选项表示要向页面 POST 数据,而 -d 选项后面紧跟着的就是你想要提交的数据。

在某些应用中,也许希望让服务器里的静态页面响应 POST 请求,比如可以重定向到首页,这需要通过修改服务器相关的配置文件或选项。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|曲径通幽 ( 琼ICP备11001422号-1|公安备案:46900502000207 )

GMT+8, 2025-5-3 11:26 , Processed in 0.092888 second(s), 23 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表