gpt4 book ai didi

html - Libcurl C++ - 如何发布此特定表单的表单数据?

转载 作者:行者123 更新时间:2023-11-30 03:22:00 25 4
gpt4 key购买 nike

如何使用 libcurl 和 C++ 发布并提交以下表单的表单数据?

<form id="loginContainer" class="controllerContainer" action="/j_spring_security_check" method="post">

<h2>Login</h2>
<hr>
<fieldset>

<div class="field">
<input class="standard" name="j_username" autocomplete="off" autocapitalize="off" size="25" placeholder="Enter Username">
</div>
<div class="field">
<input class="standard" name="j_password" type="password" value="" size="25" autocapitalize="off" autocomplete="off" placeholder="Enter Password (case-sensitive)">
</div>
<div class="field">
<button class="login" type="submit"></button>
</div>

</fieldset>

我尝试了 curl 网站上的几个例子,但没有一个对我有用。

编辑:这是我用来登录的功能

void loginToWebsite(std::string url, std::string userAgent, std::string username, std::string password)
{
CURL *curl;
CURLcode res;
curl = curl_easy_init();

if (curl) {
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_USERAGENT, userAgent.c_str());
curl_easy_setopt(curl, CURLOPT_POST, 1L);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, ("j_username=" + username + "&j_password=" + password).c_str());
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 3L);
curl_easy_setopt(curl, CURLOPT_COOKIEJAR, "cookies.txt");

res = curl_easy_perform(curl);
}

最佳答案

您正在泄漏 curl 对象。您需要调用curl_easy_cleanup()当您用完它时。

但是,更重要的是,您正在使用 CURLOPT_POSTFIELDS不正确。您正在向它传递一个指向临时 std::stringchar* 指针,该指针立即超出范围,到 curl_easy_perform() 被调用。你需要要么

您还需要对您发布的表单参数进行 url 编码。您可以使用 curl_easy_escape()为此。

话虽如此,尝试更像这样的事情:

#include <string>
#include <sstream>

void loginToWebsite(const std::string &url, const std::string &userAgent, const std::string &username, const std::string &password)
{
CURL *curl = curl_easy_init();
if (curl)
{
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_USERAGENT, userAgent.c_str());
curl_easy_setopt(curl, CURLOPT_POST, 1L);

std::ostringstream oss;

oss << "j_username=";
char *encoded = curl_easy_escape(curl, username.c_str(), username.length());
if (encoded)
{
oss << encoded;
curl_free(encoded);
}

oss << "&j_password=";
encoded = curl_easy_escape(curl, password.c_str(), password.length());
if (encoded)
{
oss << encoded;
curl_free(encoded);
}

std::string postdata = oss.str();
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postdata.c_str());

curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 3L);
curl_easy_setopt(curl, CURLOPT_COOKIEJAR, "cookies.txt");

CURLcode res = curl_easy_perform(curl);
// use res as needed...

curl_easy_cleanup(curl);
}
}

关于html - Libcurl C++ - 如何发布此特定表单的表单数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51575956/

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