我有一个可用的libsoup客户端,它使用 HTTP POST 和基本身份验证发送数据。身份验证是libsoup
通过回调处理的——当服务器需要身份验证时,通过回调libsoup
向它发出信号——然后该函数将传递给SoupAuthsoup_auth_authenticate()
类型的给定对象以及用户名和密码。
#include <iostream>
#include <iomanip>
#include <string>
#include <libsoup/soup.h>
using namespace std;
void authenticate(SoupSession *session, SoupMessage *msg, SoupAuth *auth, gboolean retrying, gpointer data) {
soup_auth_authenticate(auth, "foo", "bar");
}
int main() {
SoupSession* session = soup_session_new_with_options(SOUP_SESSION_USER_AGENT, "stackoverflow",
SOUP_SESSION_ADD_FEATURE_BY_TYPE, SOUP_TYPE_COOKIE_JAR,
NULL);
g_signal_connect(session, "authenticate", G_CALLBACK(authenticate), nullptr);
SoupMessage* post_msg = soup_message_new("POST", "https://example.org/work.php");
string formdata = "first_name=Captain&last_name=Picard";
soup_message_set_request(post_msg, "application/x-www-form-urlencoded", SOUP_MEMORY_COPY, formdata.c_str(), formdata.size());
soup_session_send_message(session, post_msg);
cout << left << setw(22) << "status code: " << right << post_msg->status_code << "\n";
cout << left << setw(22) << "reason phrase: " << right << post_msg->reason_phrase << "\n";
cout << left << setw(22) << "response body length: " << right << post_msg->response_body->length << "\n";
cout << left << setw(22) << "response body data: " << right << post_msg->response_body->data << "\n";
// TODO call soup_session_send_message() again with modified username and password
return EXIT_SUCCESS;
}
你可以用g++ -o sample sample.cpp -Wall -pedantic -g `pkg-config libsoup-2.4 --cflags --libs`
. 当您需要对此进行测试时,请更改为您提供工作端点的example.org
域flapflap.eu
。
当我想在后续呼叫中发送不同的用户名或密码时,我应该怎么做?该库将不再使用回调,因为身份验证已设置并正在工作。
我需要创建一个新的SoupSession
吗?或者我可以访问当前SoupAuth
并soup_auth_authenicate()
直接调用吗?我想让客户快速工作。
谢谢您的帮助