本文介紹了時間:2019-05-16 標簽:c++libcurljsonrest的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我正在嘗試使用 libcurl 從 C++ 中的 REST 網頁下載 json 文件.如果我轉到網頁,以下代碼有效,但如果我嘗試訪問 json 則無法下載....
I am trying to download a json file from a REST webpage in C++ with libcurl. The following code works if I go to the webpage but it doesnt download if I try to access the json ....
我認為這應該是一個簡單的修復,但我找不到任何對此的參考......
I think it should be an easy fix but I cant find any reference to this ...
如果我轉到網頁,它會打開 json 但此代碼僅返回 text/html;字符集=utf-8
If I go to webpage it opens the json but this code only returns text/html; charset=utf-8
??????????
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");
curl_easy_setopt(curl, CURLOPT_HTTPGET,1);
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
//curl_easy_setopt(curl, CURLOPT_URL, "http://web.com/123.html");//this works!!!
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
", ct);
}
}
/* always cleanup */
curl_easy_cleanup(curl);
推薦答案
std::string ServerContent::DownloadJSON(std::string URL)
{
CURL *curl;
CURLcode res;
struct curl_slist *headers=NULL; // init to NULL is important
std::ostringstream oss;
headers = curl_slist_append(headers, "Accept: application/json");
headers = curl_slist_append(headers, "Content-Type: application/json");
headers = curl_slist_append(headers, "charset: 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_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;
}
}
curl_slist_free_all(headers);
}
static std::string *DownloadedResponse;
static int writer(char *data, size_t size, size_t nmemb, std::string *buffer_in)
{
// Is there anything in the buffer?
if (buffer_in != NULL)
{
// Append the data to the buffer
buffer_in->append(data, size * nmemb);
// How much did we write?
DownloadedResponse = buffer_in;
return size * nmemb;
}
return 0;
}
這篇關于時間:2019-05-16 標簽:c++libcurljsonrest的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!