|
发表于 2020-6-15 00:13:00
|
显示全部楼层
广东省广州市
提供一个例子给你参考下
- #include <iostream>
- #include <string>
- #include "curl/curl.h"
- // reply of the requery
- size_t req_reply(void* ptr, size_t size, size_t nmemb, void* stream)
- {
- cout << "----->reply" << endl;
- string* str = (string*)stream;
- cout << *str << endl;
- (*str).append((char*)ptr, size * nmemb);
- return size * nmemb;
- }
- CURLcode curl_get_req(const std::string& url, std::string& response)
- {
- // init curl
- CURL* curl = curl_easy_init();
- // res code
- CURLcode res;
- if (curl)
- {
- // set params
- curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); // url
- curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0); // if want to use https
- curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0); // set peer and host verify false
- curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
- curl_easy_setopt(curl, CURLOPT_READFUNCTION, NULL);
- curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, req_reply);
- curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void*)&response);
- curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
- curl_easy_setopt(curl, CURLOPT_HEADER, 1);
- curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 10); // set transport and time out time
- curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10);
- // start req
- res = curl_easy_perform(curl);
- }
- // release curl
- curl_easy_cleanup(curl);
- return res;
- }
- int main(int argc, char** argv)
- {
- FILE* fp = fopen("test.jpg", "wb");
- std::string resp = "";
- curl_get_req("http://www.baidu.com/aa.png", resp);
- fwrite(resp.data(), resp.size(), 1, fp);
- fclose(fp);
- return 0;
- }
复制代码 |
|