[英]c++ libcurl json rest
我正在嘗試使用 libcurl 從 C++ 中的 REST 網頁下載 json 文件。 如果我轉到網頁,以下代碼有效,但如果我嘗試訪問 json 則不會下載....
我認為這應該是一個簡單的解決方法,但我找不到任何對此的參考......
如果我轉到網頁,它會打開 json,但此代碼僅返回 text/html; 字符集=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\n", 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;
}
我認為這與 HTTP 服務器上的配置有關。 首先,您應該發送某種類型的指示,表明您期望的是什么類型,例如,添加一個Accept
標頭,如下所示:
Accept: application/json
如果您沒有指定您期望的內容,服務器可能會在響應頭Content-Type
返回默認的 HTML,這就是curl
。
您是否從 curl 站點的教程代碼中嘗試過這種方法? http://curl.haxx.se/libcurl/c/sepheaders.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.