curl - 使用 Suitescript 实现与带有表单数据的 CURL POST 相同
问题描述
寻找 Suitescript / Javascript 专家,为我指明正确的方向。我正在创建一个连接到第三方 API 的预定脚本,并且 API 调用要求使用多部分表单数据通过 HTTP.POST 提交 GZIP 文件。我已经通过 CURL 进行了测试,所以我知道我的数据是有效的。这是 CURL 测试:
curl --location --request POST 'https://dev.themarket.co.nz/api/product/sku/sheet/upload' \
--header 'Content-Type: multipart/form-data' \
--header 'Authorization: <tokem goes here> ' \
--form 'data={"MerchantId": "5233", "Overwrite": 1,"FileFormatCode": "JSON", "SourceChannel": "MERCHANT", "SourceOrg": "Shop Until", "IgnoreExistingImage": 1 }' \
--form 'file=@/Users/tim/inventory.json.gz'
为了在 Suitescript 中创建等效的内容,我手动对数据进行编码,因为 Suitescript 没有创建多部分表单数据的功能。这很好,我可以成功地将 API 调用提交到远程系统,系统正确读取正文数据并提取消息的各个部分。但消息的第二部分是 GZIP 文件,文件内容已损坏。我不知道如何从 Netsuite 的文件柜中获取文件并以正确的方式对内容进行编码。我想我错过了一个编码步骤?
这是我的代码片段,下面是正文内容的外观。
var gz_content = gzippedFile.getContents();
var body = [];
body.push('--' + boundary);
body.push('Content-Disposition: form-data; name="data"');
body.push('');
body.push(form_data);
body.push('--' + boundary);
body.push('Content-Disposition: form-data; name="file"; filename="inventory.json.gz"');
body.push('Content-Type: application/x-gzip');
body.push('');
body.push(gz_content);
body.push('--' + boundary + '--');
body.push('');
response = https.post({
url: api_call,
headers: headers_themarket,
body: body.join('\r\n')
});
这就是多部分内容的样子:
--70834bf1-1439-4681-b1d4-fb3fa1f9efef
Content-Disposition: form-data; name="data"
{"MerchantId": "5233", "Overwrite": 1,"FileFormatCode": "JSON", "SourceChannel": "MERCHANT", "SourceOrg": "Shop Until", "IgnoreExistingImage": 1 }
--70834bf1-1439-4681-b1d4-fb3fa1f9efef
Content-Disposition: form-data; name="file"; filename="inventory.json.gz"
Content-Type: application/x-gzip
H4sIAAAAAAAC/6tW8swrS80ryS+q9MksLlGyUoiuVgrOLnXOT0kFcpQcXQ0MDIyVdJQcc3LykxNLMvPzgMIWFhY6SgGpRQWpJaWJOUABAx0lH6g0TGdKalpiaU6JUm1sLQCHcFtKZQAAAA==
--70834bf1-1439-4681-b1d4-fb3fa1f9efef--
解决方案
看起来您已经有了 gzip 压缩文件。如果是这样,当您使用 getContents() 时,您将收到一个 base64 结束编码的值。请参阅在带有 SuiteScript 2.0 的 NetSuite 中无法使用内容类型为 multipart/form-data 的 HTTP POST 请求发送文件
你需要类似的东西:
body.push('Content-Type: application/x-gzip');
body.push('Content-Transfer-Encoding: base64');
实际上,您的代码看起来像是基于该答案。传输编码部分隐藏在评论中。