gpt4 book ai didi

c++ - 如何在 C++ 中使用 libcurl 发送和接收 POST 请求?

转载 作者:可可西里 更新时间:2023-11-01 17:22:49 34 4
gpt4 key购买 nike

我正在使用 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;
}

这是来自:https://curl.haxx.se/libcurl/c/CURLOPT_POSTFIELDS.html 的示例代码

结果真的让我很困惑。从终端我可以看到发送了 POST 请求,但是从网页我无法检索到任何数据。该网页是打印出 $_POST 的非常简单的 php 代码。 terminal screenshotwebpage screenshot

谁能帮我解决这个问题?为什么我无法从网页获取 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;
}

此外,您还会找到一个很好的教程 here .

关于c++ - 如何在 C++ 中使用 libcurl 发送和接收 POST 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51317221/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com