代码之家  ›  专栏  ›  技术社区  ›  Andre

libcurl不发送json数据

  •  0
  • Andre  · 技术社区  · 8 年前

    #include <stdio.h>
    #include <curl/curl.h>
    #include <string>
    
    using namespace std;
    
    int main(void)
    {
            CURL *curl;
            CURLcode res;
    
            curl_global_init(CURL_GLOBAL_ALL);
    
            curl = curl_easy_init();
            if(curl) {
                    curl_easy_setopt(curl, CURLOPT_URL, "localhost:5000/todo/api/v1.0/tasks/debug");
                    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "{\"title\" : \"The Title\"}");
    
                    struct curl_slist *headers = NULL;
                    curl_slist_append(headers, "Accept: application/json");
                    curl_slist_append(headers, "Content-Type: application/json");
                    curl_slist_append(headers, "charsets: utf-8");
    
                    curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
                    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
    
                    res = curl_easy_perform(curl);
    
                    if(res != CURLE_OK)
                            fprintf(stderr, "curl_easy_perform() failed: %s\n",
                                            curl_easy_strerror(res));
    
                    curl_easy_cleanup(curl);
            }
            curl_global_cleanup();
            return 0;
    }
    

    这是烧瓶功能:

    #POST DEBUG
    @app.route("/todo/api/v1.0/tasks/debug", methods=['POST'])
    def echo():
            print(request.json)
            return "ReturnString \n"
    

    flask服务器的输出如下所示:

    None
    127.0.0.1 - - [12/Jul/2017 12:49:15] "POST /todo/api/v1.0/tasks/debug HTTP/1.1" 200 -
    

    所以在我看来,json数据并没有传递给flask函数。

    Curl命令:

    curl -i -H "Content-Type: application/json" -X POST -d '{"title":"Read a book"}' http://localhost:5000/todo/api/v1.0/tasks/debug
    

    烧瓶服务器的输出:

    {'title': 'Read a book'}
    127.0.0.1 - - [12/Jul/2017 13:11:54] "POST /todo/api/v1.0/tasks/debug HTTP/1.1" 200 -
    

    1 回复  |  直到 8 年前
        1
  •  1
  •   Bovarysme    8 年前

    在运行您的代码并使用Wireshark查看HTTP请求后,我发现 Content-Type 标题未设置为 application/json curl ... --libcurl example.c 并发现必须按如下方式添加请求头:

    struct curl_slist *headers = NULL;
    headers = curl_slist_append(headers, "Accept: application/json");
    headers = curl_slist_append(headers, "Content-Type: application/json");
    headers = curl_slist_append(headers, "charsets: utf-8");