基於curl簡單的get/post封裝
#include <curl.h>
#include <memory>
static size_t string_write(char *ptr, size_t size, size_t nmemb, std::string &str)
{
size_t total = size * nmemb;
if (total) str.append(ptr, total);
return total;
}
QString HttpCurlRequest(QString url, QString postData = "")
{
char error[CURL_ERROR_SIZE];
std::string writeData;
auto curl_deleter = [](CURL* curl) {curl_easy_cleanup(curl);};
using Curl = std::unique_ptr<CURL, decltype(curl_deleter)>;
Curl curl{curl_easy_init(), curl_deleter};
if (curl) {
struct curl_slist *header = nullptr;
header = curl_slist_append(header,"Content-Type: application/json");
header = curl_slist_append(header,"Referer: https://xxx");
header = curl_slist_append(header,"Cookie: uid=64665xxx");
curl_easy_setopt(curl.get(), CURLOPT_URL, url.toStdString().c_str());
curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, header);
curl_easy_setopt(curl.get(), CURLOPT_ERRORBUFFER, error);
curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, string_write);
curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &writeData);
curl_easy_setopt(curl.get(), CURLOPT_COOKIEFILE,"");
curl_easy_setopt(curl.get(), CURLOPT_SSL_ENABLE_ALPN, 0); //support LIBCURL_VERSION_NUM >= 0x072400
if(postData.length() > 0)
{
curl_easy_setopt(curl.get(), CURLOPT_POSTFIELDS, postData.toStdString().c_str()); //post
}
CURLcode code = curl_easy_perform(curl.get());
curl_slist_free_all(header);
return (code != CURLE_OK) ? QString::fromUtf8(error) : QString::fromUtf8(writeData.c_str());
}
}
調用:
QString postUrl = "https://xxx.com/node/?d=lotxr";
QString postData = "{\"axxd\":1327}";
QString postRetStr = HttpCurlRequest(postUrl, postData);
QDBG << postRetStr;
QString getUrl = "https://xxx.com/node/?d=lxxer&c=tixx";
QString getRetStr = HttpCurlRequest(getUrl);
QDBG << getRetStr;