将大文本传递到bash curl URL

Nic*_*ick 3 bash curl

我正在从将文本作为输入的Web API检索json结果。例:

curl http://www.example.com/annotate?text=${long_text}&input_format=html&output=json
Run Code Online (Sandbox Code Playgroud)

我收到参数列表的错误太长。然后我改为:

curl -d "text=${long_text}&input_format=html&output=json" http://www.example.com/annotate?
Run Code Online (Sandbox Code Playgroud)

我仍然遇到相同的错误。我从html文件中读取了$ {long_text},因为api不接受文件作为参数。有什么建议可以克服这个错误?

Cha*_*ffy 5

命令行长度的限制由操作系统强制执行-bash不能做任何事情。(实际上,这不仅是命令行长度,还包括命令行和所有导出的环境变量的总大小)。


您可以告诉您curl从文件中读取数据作为解决方法:

# create a temporary file, and arrange for it to be deleted on exit
tempfile=$(mktemp "${TMPDIR:-/tmp}/curldata.XXXXXX")
trap 'rm -rf "$tempfile"' 0 ERR

# put the data you want to POST in that file
# this doesn't have the same error because printf is a bash builtin
printf '%s' "text=${long_text}&input_format=html&output=json" >"$tempfile"

# ...and pass the filename, prefixed with an @, to curl
curl --data "@$tempfile" http://example.com/annotate
Run Code Online (Sandbox Code Playgroud)

如果您不想管理一个临时文件,可以从stdin中读取:

curl --data "@-" http://example.com/annotate \
  <<<"text=${long_text}&input_format=html&output=json"
Run Code Online (Sandbox Code Playgroud)

或者,如果您需要对输入文件进行urlencode编码,则可以告诉curl您这样做,并从所述文件本身读取该文件:

curl --data-urlencode text@htmlfile -d input_format=html -d output=json \
  http://example.com/annotate
Run Code Online (Sandbox Code Playgroud)