c++ libcurl json rest(时间: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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:时间:2019-05-16 标签:c++libcurljsonrest


基础教程推荐
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01