【发布时间】:2018-02-04 20:20:09
【问题描述】:
我正在开发一个 C++ 库,它使用 curl 库来执行对 Web 服务的 HTTP POST 请求。
我有一个函数负责执行 curl 和处理响应,这个函数调用另一个函数来设置 curl,因为它可以在多个地方使用相同的设置。
它已成功连接到 Web 服务,我可以看到返回的响应,但是没有任何发布数据发送到 Web 服务。
在我必须执行 HTTP 请求的代码下方。
第一个函数是curl执行的函数,它调用一个函数来初始化curl库,然后返回指向它的指针以供使用。
string response;
struct curl_slist *list = NULL;
const char * jsonString = ddEvent.getDDEventAsJSONString().c_str();
CURL *curl = this->initCurl(ddEvent, &response, list, &jsonString);
if (curl == NULL)
{
return false;
}
list = curl_slist_append(list, "Content-Type: application/json");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, list);
CURLcode res = curl_easy_perform(curl);
初始化curl的函数如下:
CURL * MyClass::initCurl(DDEvent ddEvent, string *response, struct curl_slist *list, const char **jsonString)
{
CURL *curl = NULL;
curl = curl_easy_init();
if (curl == NULL)
{
cout << "Failed to initialise curl" << endl;
return NULL;
}
stringstream url_stream;
url_stream << "http://192.168.1.123";
string url= dd_url_stream.str();
cout << "Using URL: " << url<< endl;
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 1);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, response);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &MyClass::curlResponseWriteCallback);
curl_easy_setopt(curl, CURLOPT_HEADER, 1);
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
curl_easy_setopt(curl, CURLOPT_POST, 1);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, *jsonString);
return curl;
}
另外,发布数据是一个 JSON 字符串,它不是一个键/值发布的表单数据。
下面是 curl 详细模式的输出
Using JSON string {"title":"HTTP Event Teesg","text":"Test warning event","alert_type":"success","tags":["simple_string_tag"]}
Using URL: http://192.168.1.123
* About to connect() to 192.168.1.123 port 80 (#0)
* Trying 192.168.1.123...
* Connected to 192.168.1.123 (192.168.1.123) port 80 (#0)
> POST / HTTP/1.1
Host: 192.168.1.123
Accept: */*
Content-Type: application/json
Content-Length: 0
< HTTP/1.1 200 OK
< Date: Sun, 04 Feb 2018 20:11:12 GMT
< Server: Apache/2.4.6 (CentOS) PHP/5.6.32
< X-Powered-By: PHP/5.6.32
< X-XSS-Protection: 1; mode=block
< Content-Length: 52
< Content-Type: text/html; charset=UTF-8
<
【问题讨论】:
-
您是否有理由不直接为 url 分配值
"http://192.168.1.123",而是使用 stringstream? -
我还看到您的 init 函数采用指向
std::basic_string的指针并将该指针传递给curl_easy_setopt(curl, CURLOPT_WRITEDATA, response);。你能验证这个函数期待的是std::basic_string *而不是char * -
最后评论,您可能需要“转义”帖子数据。不确定这是否已经完成,但阅读
CURLOPT_POSTFIELDS,数据应该是url encoded -
@smac89 实际 URL 指向第 3 方 Web 服务,因此会有其他参数,因为这个问题我将它指向了测试服务器上的本地网页,所以它通常不像那样
-
@smac89 关于您对响应指针的评论,响应字符串被正确填充,因为我可以看到响应被打印回来