我目前正在做一个需要使用 C 来发出 http get 请求的项目。我正在尝试使用 curl 来做到这一点。但是,我得到的回复是
error: unable to request data from https://coinex.pw/api/v2/currencies:
Unsupported protocol
我不确定错误是来自 curl 还是来自服务器。这是我的代码,借鉴自示例代码:
#include <curl/curl.h>
static char *request(const char *url)
{
CURL *curl = NULL;
CURLcode status;
struct curl_slist *headers = NULL;
char *data = NULL;
long code;
curl_global_init(CURL_GLOBAL_ALL);
curl = curl_easy_init();
if(!curl)
goto error;
data = malloc(BUFFER_SIZE);
if(!data)
goto error;
struct write_result write_result = {
.data = data,
.pos = 0
};
curl_easy_setopt(curl, CURLOPT_URL, url);
headers = curl_slist_append(headers, "Content-type: application/json");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_response);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &write_result);
status = curl_easy_perform(curl);
if(status != 0)
{
fprintf(stderr, "error: unable to request data from %s:\n", url);
fprintf(stderr, "%s\n", curl_easy_strerror(status));
goto error;
}
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &code);
if(code != 200)
{
fprintf(stderr, "error: server responded with code %ld\n", code);
goto error;
}
curl_easy_cleanup(curl);
curl_slist_free_all(headers);
curl_global_cleanup();
/* zero-terminate the result */
data[write_result.pos] = '\0';
return data;
error:
if(data)
free(data);
if(curl)
curl_easy_cleanup(curl);
if(headers)
curl_slist_free_all(headers);
curl_global_cleanup();
return NULL;
}
欢迎任何提示/提示。
最佳答案
curl
(和 libcurl
)在无法解释 URL 的协议(protocol)部分时会给出不受支持的协议(protocol)错误。在您的情况下,这意味着 https:
,这有点奇怪。
首先检查您是否可以从命令行使用 curl
工具来检索 URL。
curl -V
将为您提供 curl
(以及 libcurl
)将支持的协议(protocol)列表:
$ curl -V
curl 7.22.0 (x86_64-pc-linux-gnu) libcurl/7.22.0 OpenSSL/1.0.1 zlib/1.2.3.4 libidn/1.23 librtmp/2.3
Protocols: dict file ftp ftps gopher http https imap imaps ldap pop3 pop3s rtmp rtsp smtp smtps telnet tftp
Features: GSS-Negotiate IDN IPv6 Largefile NTLM NTLM_WB SSL libz TLS-SRP
检查 https
是否存在。可能是您的 libcurl
不是针对 SSL 库构建的,或者是未安装 SSL 库。
最后在这个页面上:http://curl.haxx.se/libcurl/c/example.html您会注意到这是一个简单的 https 示例(第二个)。请确认它适用于您的 libcurl
。如果是这样,我会找出您的程序在做什么不同。如果没有,我会找出您的 libcurl
安装有什么问题。
关于c - 在 C 中使用 Curl 不支持的协议(protocol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21612132/