Unsupported Protocol using Curl in C

2019-07-04 12:06发布

问题:

I am currently working on a project that requires using C to make an http get request. I am trying to do this using curl. However, I get a response that says

error: unable to request data from https://coinex.pw/api/v2/currencies:
Unsupported protocol

I am not sure if the error is coming from curl or from the server. Here is my code, borrowed from example code:

#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;
}

Any tips / hints are welcome.

回答1:

curl (and libcurl) gives an unsupported protocol error when they can't interpret the protocol part of the URL. In your case that means https:, which is a bit odd.

First check you can you use the curl tool from the command line to retrieve the URL.

curl -V will give you a list of the protocols curl (and thus libcurl) will support:

$ 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 

Check that https is there. It may be that your libcurl is not built against an SSL library or if it is that the SSL library is not installed.

Finally on this page: http://curl.haxx.se/libcurl/c/example.html you will note that is a simple https example (second one down). Please confirm that works with your libcurl. If so, I'd find out what your program is doing different. If not, I would find out what's wrong with your libcurl installation.



回答2:

try to use "http" but "https" in your URL.



标签: c http curl