我刚刚注册了stackoverflow帐户,因为我在使用C应用程序发送多部分/表单数据时遇到了严重麻烦。我可以使用许多图书馆发送邮件,但出于教育目的,我正在从头开始做所有事情,因此请耐心等待。

问题是,当我使用应用程序发送请求时,服务器恰巧返回了400 Bad Request。我看到了类似的问题here on stackoverflow,但仍然无法解决该请求。以下是我收到的请求和服务器返回的屏幕快照。

screenshot of program when run

// this is the temp_send which is incomplete
// adds the post data later
char *temp_send="POST http://localhost/france/test.php HTTP/1.1\r\n"
                "Host: localhost\r\n"
                "Accept: image/gif, image/jpeg, */*\r\n"
                "Accept-Language: en-us\r\n"
                "Content-Type: multipart/form-data; boundary=---------------------------7d41b838504d8\r\n"
                "Accept-Encoding: gzip, deflate\r\n"
                "User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)\r\n"
                "Connection: keep-alive\r\n"
                "Cache-Control: no-cache\r\n\r\n"
                "---------------------------7d41b838504d8 Content-Disposition: form-data; name=\"name\"\r\n"
                "%s\r\n"
                "---------------------------7d41b838504d8--\r\n";

char *postdata="testval";

char *sendbuf=NULL;
sendbuf=(char*)malloc(sizeof(char)*SENDLEN);
sprintf(sendbuf, temp_send, postdata);


注意:<pre>标记中以某种方式返回了“ testval”,但我需要消除错误。我意识到这是一个广泛的问题,但我只需要缩小multipart / form-data的发送范围。

注意2:我也知道我可以使用application/x-www-form-urlencoded,并且已经可以使用它了,但是由于我要进行的文件上传要复杂得多,因此我需要使用multipart-form/data,并且我尝试使用首先使用纯文本以减少复杂性

最佳答案

我终于知道了如何使用multipart / post-data发布简单数据。我使用了提琴手,看看如何传递数据。内容长度恰好是238,我还没有尝试使用其他数据,但是将内容长度设置为238或更大似乎总是可行的。这是现在的代码。

char *sendbuf="POST http://localhost/france/test.php HTTP/1.1\r\n"
                        "Host: localhost\r\n"
                        "Content-Length: 238\r\n"   // content-length >=238
                        "Content-Type: multipart/form-data; boundary=----12345\r\n\r\n"
                        "------12345\r\n"
                        "Content-Disposition: form-data; name=\"name\"\r\n\r\n"
                        "This is the first string\r\n"
                        "------12345\r\n"
                        "Content-Disposition: form-data; name=\"hell\"\r\n\r\n"
                        "this is another string\r\n"
                        "------12345\r\n";


重要信息:发送数据时,内容长度似乎很重要,并且-的数量在边界之后也更多。如果边界有k个破折号,那么以下破折号似乎总是k + 2

09-07 19:18
查看更多