Home > Net >  Keep getting 400 Bad Request: invalid header name with libcurl with the X-API-Key header
Keep getting 400 Bad Request: invalid header name with libcurl with the X-API-Key header

Time:10-08

Basically, I'm just trying to run this curl command on my C application with libcurl.

curl  http://127.0.0.1:8384/rest/events -H "X-API-Key: WuCS7KQtyoRxbWDZ4zsSbjUdU4T"

The command works perfectly fine on the command prompt. But when I try to use it with libcurl, I keep getting the 400 Bad Request: invalid header name error. I browsed through a few other similar threads, but I could not find the solution. I'm really at my wits end now. :( The spacing and syntax looks good.... thanks for the help.

Here's the code:

static size_t my_write( void* buffer, size_t size, size_t nmemb, void* param )
    {
        std::string& text = *static_cast< std::string* >( param );
        size_t totalsize = size * nmemb;
        text.append( static_cast< char* >( buffer ), totalsize );
        return totalsize;
    }
    int main()
    {
        std::string result;
        CURL* curl;
        CURLcode res;
        curl_global_init( CURL_GLOBAL_DEFAULT );
        curl = curl_easy_init();
        if ( curl ) 
        {
            curl_easy_setopt( curl, CURLOPT_URL, "http://127.0.0.1:8384/rest/events" );
            curl_easy_setopt( curl, CURLOPT_WRITEFUNCTION, my_write );
            curl_easy_setopt( curl, CURLOPT_WRITEDATA, &result );
            curl_easy_setopt( curl, CURLOPT_VERBOSE, 1L );
    
    
            struct curl_slist *header = NULL;
            header = curl_slist_append( header, "-H \"X-API-Key: WuCS7KQtyoRxbWDZ4zsSbjUdU4T\"" );

            curl_easy_setopt( curl, CURLOPT_HTTPHEADER, header );

            res = curl_easy_perform( curl );
            curl_easy_cleanup( curl );
        }
        curl_global_cleanup();
        std::cout << result << "\n\n";
    }

CodePudding user response:

DON'T include the -H switch when calling curl_slist_append(). That switch is meant only for the command-line curl.exe app. It tells the app that the following data should be passed to curl_slist_append().

Use this instead:

curl_slist *header = curl_slist_append(NULL, "X-API-Key: WuCS7KQtyoRxbWDZ4zsSbjUdU4T");
  • Related