如何在POST请求中模拟HTML表单提交?

26

我有一个用于从应用程序向服务器发送错误报告的HTML表单。我需要在程序中模拟此行为。相应的POST请求(或一系列请求)将是什么样子?

<form name="bugreport" method="post" enctype="multipart/form-data" action="http://my-server.com/bugreport.php">
    <div name="SentData">
        <textarea name="logfile" class="UserVisible"></textarea><br>
        <textarea name="configfile" class="UserVisible"></textarea><br>
    </div>
    <textarea name="usercomment" class="invisible"></textarea><br>
    <input name="useremail" type="text" class="invisible">
    <input class="invisible" type="submit" value="Send">
</form> 
1个回答

44

一个POST请求包含一些头部和一个请求体。当你提交一个表单时,浏览器URL编码所有表单字段的名称和值,然后以这种格式将它们放入请求体中:

fieldname1=fieldvalue1&fieldname2=fieldvalue2

也就是说,请求体看起来像一个典型的查询字符串。


以下是您表单请求的示例:

这是您表单请求的样式:

POST /bugreport.php HTTP/1.1
Host: www.example.com
Content-Type: application/x-www-form-urlencoded
Content-Length: [size of the request body]

logfile=blabla&configfile=more+blabla&usercomment=hello&useremail=

为了确保您的程序与浏览器的操作一致,您可以使用Firebug的网络面板,在Firefox中提交表单,然后检查请求头和请求体。


谢谢!FireBug真的很有帮助(不过,一旦你知道了原理,就不需要它了)。 - Violet Giraffe
假设服务器能够处理它们,HTTP协议是否允许content-type x-www-form-urlencoded的“垃圾数据”?例如:logfileblabla&configfile=====mo+uselo&&&useremail=&=&=&+ - Pacerier
谢谢。这就是我在寻找的东西。 - Joey

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接