Vic*_*Vic 9 c++ curl http libcurl
我正在使用 c++ libcurl 向网页发送 POST 请求,但我正在努力测试它。使用的代码是:
#include <stdio.h>
#include <curl/curl.h>
#include <string>
using namespace std;
int main(void)
{
CURL *curl = curl_easy_init();
if(curl) {
const char *data = "submit = 1";
curl_easy_setopt(curl, CURLOPT_URL, "http://10.5.10.200/website/WebFrontend/backend/posttest.php");
/* size of the POST data */
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, 10L);
/* pass in a pointer to the data - libcurl will not copy */
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data);
curl_easy_perform(curl);
}
/* Perform the request, res will get the return code */
/* always cleanup */
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这是示例代码:https://curl.haxx.se/libcurl/c/CURLOPT_POSTFIELDS.html
结果真的让我很困惑。从终端我可以看到已发送 POST 请求,但从网页我无法检索任何数据。该网页是非常简单的 php 代码,打印出 $_POST。 终端截图和 网页截图
有人能帮我解决这个问题吗?为什么我无法从网页获取 POST 请求,如何解决此问题?任何人都可以给我一个更好的方法来测试代码吗?非常感谢你们!
您必须实现一个回调函数,curl 在收到每批数据时都会调用该函数。
在这里查看一个很好的例子:
https://gist.github.com/alghanmi/c5d7b761b2c9ab199157#file-curl_example-cpp
显然,您可以用 WriteCallback() 函数中所需的任何数据类型和处理来替换简单字符串。
复制/粘贴 alghanmi 的示例:
#include <iostream>
#include <string>
#include <curl/curl.h>
static size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp)
{
((std::string*)userp)->append((char*)contents, size * nmemb);
return size * nmemb;
}
int main(void)
{
CURL *curl;
CURLcode res;
std::string readBuffer;
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, "http://www.google.com");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
std::cout << readBuffer << std::endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
此外,您还可以在这里找到一个很好的教程。