CURL *curl;CURLcode res;struct curl_slist *headers=NULL; // init to NULL is important headers = curl_slist_append(headers, "Accept: application/json"); curl = curl_easy_init();if(curl) {curl_easy_setopt(curl, CURLOPT_URL, "http://web.com/api/json/123");//cant get json filecurl_easy_setopt(curl, CURLOPT_URL, "http://web.com/pages/123.html");//this returns entire webpagecurl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);curl_easy_setopt(curl, CURLOPT_RETURNTRANSFER, true); res = curl_easy_perform(curl);if(CURLE_OK == res) {char *ct;// ask for the content-type res = curl_easy_getinfo(curl, CURLINFO_CONTENT_TYPE, &ct);if((CURLE_OK == res) && ct) printf("We received Content-Type: %s\n", ct);}} // always cleanup curl_easy_cleanup(curl);
//参考答案1
std::string ServerContent::DownloadJSO
N (std::string URL)
{
CURL *curl;
Curlcode Res;
struct Curl_slist *headers=null; Init to NULL is important
Std::ostringstream OSS;
Curl_slist_append (Headers, "Accept:application/json");
Curl_slist_append (Headers, "Content-type:application/json");
Curl_slist_append (Headers, "charsets:utf-8");
Curl = Curl_easy_init ();
if (Curl) {
Curl_easy_setopt (Curl, Curlopt_httpheader, headers);
Curl_easy_setopt (Curl, Curlopt_url, url.c_str ());
Curl_easy_setopt (curl, curlopt_httpget,1);
Curl_easy_setopt (Curl, Curlopt_httpheader, headers);
Curl_easy_setopt (Curl,curlopt_writefunction,writer);
res = curl_easy_perform (curl);
if (CURLE_OK = = res) {
Char *ct;
res = Curl_easy_getinfo (curl, Curlinfo_content_type, &ct);
if ((CURLE_OK = = res) && CT)
return *downloadedresponse;
}
}
}
How to use curl and explain JSON