bash - 如何在带有多参数的bash curl命令中使用--data-binary
问题描述
<?php
$post_data = array(
'filename'=>new \CurlFile($uploadPath),
'jsondata'=> json_encode($params,JSON_UNESCAPED_UNICODE)
$toPdfApi='https://example.com/convert2PDF'
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL,$toPdfApi);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl,CURLOPT_BINARYTRANSFER,true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'multipart/form-data',
'application/x-www-form-urlencoded'));
curl_setopt($curl, CURLOPT_POSTFIELDS,$post_data);
$result = curl_exec($curl);
然后我将其转换为 bash shell 命令
curl -i -X POST -H "Content-Type: multipart/form-data" -H "Content-Type: application/x-www-form-urlencoded" --data-binary 'filename=@/root/test.txt' --data-binary 'jsondata={"fileName":"test","id":"xxx","backlink":"https://example.com/hello"}' https://example.com/convert2PDF
但响应结果仍然不对
HTTP/1.1 200 OK
Date: Fri, 01 Jun 2018 14:41:37 GMT
Content-Type: application/x-www-form-urlencoded
Transfer-Encoding: chunked
Server: Jetty(9.4.5.v20170502)
error
有人可以帮忙吗?是我隐蔽的 bash shell 吗?
如果我使用以下命令 [将 -data-binary 替换为 -F ],我会得到正确的状态,但是从 php 代码中我知道我应该在 bash curl 中添加 CURLOPT_BINARYTRANSFER ,否则https://example.com/convert2PDF无法获得正确的帖子数据。
curl -i -X POST -H "Content-Type: multipart/form-data" -H "Content-Type: application/x-www-form-urlencoded" -F 'filename=@/root/test.txt' -F 'jsondata={"fileName":"test","id":"xxx","backlink":"https://example.com/hello"}' https://example.com/convert2PDF
HTTP/1.1 100 Continue
HTTP/1.1 200 OK
Date: Fri, 01 Jun 2018 16:29:35 GMT
Content-Type: application/x-www-form-urlencoded
Transfer-Encoding: chunked
Server: Jetty(9.4.5.v20170502)
success
我想得到响应的状态是 200,结果在 --data-binary 模式下是成功的,我该怎么做才能更新我的 bash 命令?
解决方案
的全部意义--data-binary
在于它是一大块字节。您只能发送一个,因为每个 HTTP 请求只有一个正文,并且只能有一个顶级内容类型。
您似乎正在尝试构建一个包含两部分的多部分请求正文,一部分包含文件数据,另一部分包含键/值对。
要通过命令行发送包含一些元数据的文件,您可以执行以下操作:
curl -F'id=xxx' -F 'name=foo' -F'file=@test.txt;type=text/plain' http://example.com
这将发送一个多部分请求,PHP 后端可以访问来自 $_POST 的元数据和来自 $_FILES 的文件数据。
所需的确切方法取决于后端期望接收的内容,但您尚未发布。
例如,以下内容将与 --data-binary 一起使用(根据您的问题),但参数和文件数据都将在后端以不同的方式访问。
curl --data-binary '@test.txt' 'http://example.com?id=xxx&name=foo'
推荐阅读
- amazon-web-services - 我如何使用 circleci 自动化我的 aws ecs 构建和 dockerisation
- php - Laravel 5.6 $errors 检查表单提交了吗?
- dns - 如何更改 Google 域合成记录的 TTL 值?
- ios - 在保持相同 avAudioSession 类别的同时控制 iOS 音频源音量
- c# - 忽略最顶层窗口的鼠标和键盘事件
- java - CSV 到双数组列表
- python - 如何在python中绘制双变量数据的饼图
- c# - CS1061“对象”不包含“原始文本”的定义
- javascript - 复制对象的选定元素
- android - 如何将 Uber Driver API 集成到我的移动应用程序产品中