libcurl不发送json-Data

时间:2017-07-12 10:52:08

标签: flask http-post libcurl flask-restful

我尝试将一些json-Code从c ++传递给Python Flask Rest Api。但不幸的是,这不起作用,也没有看到我的错误:(

这是我的c-Code:

#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-Server的输出如下所示:

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

所以在我看来,json-Data没有传递给flask-function。 我尝试了与文本基本相同的功能。

当我从命令行尝试使用curl-Call进行同样的操作时,它可以正常工作。 卷曲命令:

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

Flask-Server的输出:

{'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 个答案:

答案 0 :(得分:0)

运行代码并使用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");