我需要通过 ssl 套接字在以下地址建立连接:stream-api-integration.betfair.com(端口 443),并使用 libcurl 读取来自服务器的消息。我是使用这个库的新手。我试图搜索有关此问题的信息,但没有找到我需要的信息。
如果连接建立成功,服务器应返回以下响应:{"op": "connection", "connection Id": "100-040320153715-29795"}。
我该怎么做呢?
PS 同时,我使用 libcurl 向 https 发送 post 请求没有问题。如果这有任何帮助,我将提供成功执行发布请求的代码。问题仅在于 ssl 套接字。
#include <curl/curl.h>
#include <string.h>
#include <sstream>
#include <iostream>
size_t writeToStream(char* buffer, size_t size, size_t nitems, std::ostream* stream)
{
size_t realwrote = size * nitems;
stream->write(buffer, static_cast<std::streamsize>(realwrote));
if (!(*stream)){
realwrote = 0;
}
return realwrote;
}
int main(int argc, char *argv[])
{
std::string url = "https://identitysso-cert.betfair.com/api/certlogin";
std::string acceptHeader = "Accept: application/json");
std::string appHeader = "X-Application: myappkey");
std::string contentTypeHeader = "Content-Type: application/x-www-form-urlencoded";
curl_slist* slist = nullptr;
slist = curl_slist_append(slist, acceptHeader.c_str());
slist = curl_slist_append(slist, appHeader.c_str());
slist = curl_slist_append(slist, contentTypeHeader.c_str());
std::stringstream result;
char errorBuffer[CURL_ERROR_SIZE];
CURL *curl = curl_easy_init();
if(curl != nullptr){
curl_easy_setopt(curl, CURLOPT_CAINFO, "../cacert.pem");
curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errorBuffer);
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_ALL);
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist);
std::string certFilePath = "../client-2048.crt";
std::string keyFilePath = "../client-2048.key";
curl_easy_setopt(curl, CURLOPT_SSLCERT, certFilePath.c_str());
curl_easy_setopt(curl, CURLOPT_SSLKEY, keyFilePath.c_str());
std::string payload = "username=myusername&password=mypassword";
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postFields.c_str());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeToStream);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &result);
curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errorBuffer);
errorBuffer[0] = 0;
int responseCode = -1;
CURLcode curlResult = curl_easy_perform(curl);
if (curlResult == CURLE_OK){
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &responseCode);
std::cout<<"response code: "<<responseCode<<std::endl;
std::cout<<result.str()<<std::endl;
}
else{
std::cout<<"Failed:("<<std::endl;
throw std::runtime_error(errorBuffer);
}
}
return 0;
}