【发布时间】:2014-03-17 14:53:43
【问题描述】:
首先,我对 HTTP 命令和 libcurl 库还很陌生,所以我很有可能对一些基本的东西不了解。也就是说,我正在尝试在基于 Windows 的 MFC 应用程序上复制通过内部服务器发送到设备的 HTTP POST 命令。本质上,我正在发送一个小位图图像和一个命令。我使用 Fiddler 捕获了命令,它看起来像:
POST /Service/MyCommand HTTP/1.1
Authorization: MyAuth
Content-Type: image/bmp
User-Agent: Mozilla/4.0 (Windows 7 6.1) Java/1.7.0_51
Host: MyHost:MyPort
Accept: MyAccept
Connection: MyConnection
Content-Length: 15606
/* BMP Data */
我在复制它时遇到了两个问题(使用 libcurl)。首先,我的“Service/MyCommand”发布命令出现在标题的最后,而不是在“POST /”之后。我试图移动它,但它不会出现在我的 WireShark 过滤器窗口中。其次,当我尝试将内容长度设置为 15606 时,与原来的一样,WireShark 上的协议从“POST”切换到“TCP”。我附上了下面的代码。
int CHttpPost::fnSendContent()
{
using namespace std;
int Error = 0;
CString str;
CURL* curl;
CURLcode res;
struct curl_httppost *formpost=NULL;
struct curl_httppost *lastptr=NULL;
struct curl_slist *headerlist=NULL;
static const char buf[] = "a"; // not sure what to do with this
curl_global_init(CURL_GLOBAL_ALL);
curl_formadd(&formpost, &lastptr, CURLFORM_COPYNAME, "importfile", CURLFORM_FILE, "MyImage.bmp", CURLFORM_CONTENTTYPE, "image/bmp", CURLFORM_END);
curl_formadd(&formpost, &lastptr, CURLFORM_COPYNAME, "action", CURLFORM_COPYCONTENTS, "upload", CURLFORM_END);
curl = curl_easy_init();
headerlist = curl_slist_append(headerlist, buf);
headerlist = curl_slist_append(headerlist, "Authorization: MyAuth");
headerlist = curl_slist_append(headerlist, "Content-Type: image/bmp");
headerlist = curl_slist_append(headerlist, "User-Agent: Mozilla/4.0 (Windows 7 6.1) Java/1.7.0_51");
headerlist = curl_slist_append(headerlist, "Accept: MyAccept");
headerlist = curl_slist_append(headerlist, "Connection: MyConnection");
headerlist = curl_slist_append(headerlist, "Content-Length: 15606");
//Set URL to recevie POST
curl_easy_setopt(curl, CURLOPT_VERBOSE, true);
curl_easy_setopt(curl,CURLOPT_POST, true);
curl_easy_setopt(curl, CURLOPT_HEADER, true);
curl_easy_setopt(curl, CURLOPT_URL, "MyHost:MyPort");
curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "Service/MyCommand");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerlist);
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
curl_global_cleanup();
return Error;
}
也非常感谢您提出的任何其他建议或更正。
编辑:我把“Service/MyCommand”放在postfield而不是URL中是个白痴。我显然误解了其中一个教程。但是,我的内容长度问题仍然存在。
【问题讨论】:
标签: c++ http-headers http-post libcurl