libcurl 在上传数据前延迟 1 秒,命令行 curl 不会 [英] libcurl delays for 1 second before uploading data, command-line curl does not
问题描述
我正在使用 libcurl 将 API 命令发送到本地服务(即在 127.0.0.1 上).
I am using libcurl to send an API command to a local service (i.e. on 127.0.0.1).
该程序旨在替换 shell 脚本(使用 curl
程序.)
The program is intended to replace a shell script (that uses the curl
program.)
一切正常,除了某处有 1 秒的延迟,即从我调用 curl_easy_perform()
到第一次调用我的读取回调函数时过去了 1 秒.
Everything is working, except that there is a 1-second delay somewhere, i.e 1 second elapses from the time I call curl_easy_perform()
to when my read callback function is first called.
C 程序正在使用这些选项(省略了错误检查和回调代码):
The C program is using these options (error checking & callback code omitted):
curl_easy_setopt(curl, CURLOPT_URL, "http://127.0.0.1:12345/x");
curl_easy_setopt(curl, CURLOPT_UPLOAD, 1);
curl_easy_setopt(curl, CURLOPT_INFILESIZE, (long)getLengthOfCommandObject());
curl_easy_setopt(curl, CURLOPT_READFUNCTION, &myReadFunction);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &myWriteFunction);
但是如果我像这样从 shell 运行 curl
:
But if I run curl
from the shell like this:
$ curl --data-binary '<command>' http://127.0.0.1:12345/x
它立即发送请求,不会有 1 秒的延迟.
it sends the request immediately, without suffering from the 1-second delay.
可能导致延迟的原因是什么,我可以设置一个选项来阻止它吗?
What might be causing the delay, and is there an option I can set to prevent it?
编辑服务器基于mongoose
推荐答案
延迟的原因是:
- libcurl 是 发送一个
Expect: 100-Continue代码>标题
- 服务器(基于 mongoose)是 未配置为自动发送
100 Continue
响应. - libcurl 等待该响应最多 1 秒.如果在此时间之后它没有收到它,那么它仍然会继续发送请求正文.
客户端的一个解决方案是禁用 Expect
标头,如下所示:
A solution on the client side is to disable the Expect
header like so:
headers = curl_slist_append(NULL, "Expect:");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
// ...
result = curl_easy_perform(curl);
curl_slist_free_all(headers);
这篇关于libcurl 在上传数据前延迟 1 秒,命令行 curl 不会的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!