Flask libcurl不发送json数据 我尝试将一些JSON代码从C++传递到Python烧瓶REST API。但不幸的是,这不起作用,a不明白我的错误:
这是我的c代码:Flask libcurl不发送json数据 我尝试将一些JSON代码从C++传递到Python烧瓶REST API。但不幸的是,这不起作用,a不明白我的错误:,flask,http-post,libcurl,flask-restful,Flask,Http Post,Libcurl,Flask Restful,这是我的c代码: #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();
#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;
}
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命令:
curl -i -H "Content-Type: application/json" -X POST -d '{"title":"Read a book"}' http://localhost:5000/todo/api/v1.0/tasks/debug
来自Flask服务器的输出:
{'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 -
有什么帮助吗?在我运行代码并使用Wireshark查看HTTP请求后,我发现内容类型头没有设置为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");
你能试着改用吗?我试过了,但在两种情况下都没有
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");