如何解决使用 libcurl 作为 std::string 返回 post 值
如何提取表单中 id
字段中的值并将其声明为 std::string
当这个函数被调用时,它会向提供的链接发出一个post请求,并将结果输出到客户端的命令行
int push_(void)
{
CURL* curl;
CURLcode res;
/* In windows,this will init the winsock stuff */
curl_global_init(CURL_GLOBAL_ALL);
/* get a curl handle */
curl = curl_easy_init();
if (curl) {
/* First set the URL that is about to receive our POST. This URL can
just as well be a https:// URL if that is what should receive the
data. */
curl_easy_setopt(curl,CURLOPT_URL,"http://localhost/api/0000/push");
/* Now specify the POST data */
// the form on the server side has a single field
curl_easy_setopt(curl,CURLOPT_POSTFIELDS,"id=");
/* Perform the request,res will get the return code */
res = curl_easy_perform(curl);
/* Check for errors */
if (res != CURLE_OK)
fprintf(stderr,"curl_easy_perform() failed: %s\n",curl_easy_strerror(res));
/* always cleanup */
curl_easy_cleanup(curl);
}
curl_global_cleanup();
return 0;
}
id 作为输入提供
fffffffffffffffffffffffffffffffffffffffffffffffffffffffff
服务器响应
fffffffffffffffffffffffffffffffffffffffffffffffffffffffff<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>Redirecting...</title>
<h1>Redirecting...</h1>
<p>You should be redirected automatically to target URL: <a href="/login">/login</a>.
我已经提取了 id 值,但我不知道如何从 html 标签中拆分 id
解决方法
您必须添加一个回调函数 CurlWrite_CallbackFunc_StdString
才能从 post 请求中获取数据
#include <iostream>
#include <string>
#include <curl/curl.h>
size_t CurlWrite_CallbackFunc_StdString(void* contents,size_t size,size_t nmemb,std::string* s)
{
size_t newLength = size * nmemb;
try
{
s->append((char*)contents,newLength);
}
catch (std::bad_alloc& e)
{
//handle memory problem
return 0;
}
return newLength;
}
std::string h3ll0() {
CURL* curl;
CURLcode res;
curl_global_init(CURL_GLOBAL_DEFAULT);
curl = curl_easy_init();
std::string s;
if (curl)
{
curl_easy_setopt(curl,CURLOPT_URL,"localhost/api/0000/hello");
// Add post data to get the command line from the server post request
curl_easy_setopt(curl,CURLOPT_POSTFIELDS,"id=");
// A calback function that copies the data from the post request output
curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,CurlWrite_CallbackFunc_StdString);
// Write the copied data to the variable s to return it
curl_easy_setopt(curl,CURLOPT_WRITEDATA,&s);
/* Perform the request,res will get the return code */
res = curl_easy_perform(curl);
/* Check for errors */
if (res != CURLE_OK)
{
fprintf(stderr,"curl_easy_perform() failed: %s\n",curl_easy_strerror(res));
}
/* always cleanup */
curl_easy_cleanup(curl);
}
//std::cout << s << std::endl;
//std::cout << "Program finished!" << std::endl;
return s;
}
int main() {
std::string result = h3ll0();
std::cout << result << std::endl;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。