未收到使用Indy发送的JSON,因为它是由StripeAPI发送的
我正在向条带 API 发送一个带有 Indy http 组件的 JSON,但它没有被 API 接收,因为它是在我收到“错误请求”响应时接收的:
jsnObj := TJSONObject.Create;
jsnObj.AddPair('amount', TJSONNumber.Create('111'));
jsnObj.AddPair('currency', 'eur');
jsnObj.AddPair('customer', 'cus_JNxQsqf6BoK8Rt');
jsnObj.AddPair('description', 'My First Test');
ss := TStringStream.Create(jsnObj.ToString, TEncoding.UTF8);
rs := TStringStream.Create;
IdHTTP1.Request.BasicAuthentication := True;
IdHTTP1.Request.Username := ApiKey ; // test private key
IdHTTP1.Post('https://api.stripe.com/v1/charges', ss, rs);
StatusBar1.SimpleText := IdHTTP1.ResponseText;
要发送的 JSON 是:
{
"amount": 111,
"currency": "eur",
"customer": "cus_JNxQsqf6BoK8Rt",
"description": "My First Test"
}
API 仪表板报告已收到此信息:
{
"{"amount":111,"currency":"eur","customer":"cus_JNxQsqf6BoK8Rt","description":"My First Test"}": null
}
HTTP 组件应该做一些事情,以便以这种方式发送它,包括一个空值,也许是因为在请求中包含了用户名?对于其他 API,相同的 HTTP 组件总是发送它要发送的内容。Stripe 支持表明问题出在我这边。条带文档指定了这一点:
curl -X POST https://api.stripe.com/v1/charges
-u STRIPE_SECRET_KEY:
-d amount=2000
-d currency=usd
-d source=tok_visa
-d description="Charge for aiden.jones@example.com"
有人知道问题出在哪里吗?
回答
Stripe 文档中提供的 CURL 示例根本没有以 JSON 格式发送数据。根据CURL 文档,它name=value以application/x-www-form-urlencoded格式发送对:
-d, --data
(HTTP MQTT) 将 POST 请求中的指定数据发送到 HTTP 服务器,就像浏览器在用户填写 HTML 表单并按下提交按钮时所做的一样。这将导致 curl 使用内容类型 application/x-www-form-urlencoded 将数据传递给服务器。与-F, --form比较。
在发布请求时使用TStrings重载,例如:TIdHTTP.Post()application/x-www-form-urlencoded
var
postData: TStringList;
rs: string;
...
postData := TStringList.Create;
try
postData.Add('amount=111');
postData.Add('currency=eur');
postData.Add('customer=cus_JNxQsqf6BoK8Rt');
postData.Add('description=My First Test');
IdHTTP1.Request.BasicAuthentication := True;
IdHTTP1.Request.Username := ApiKey; // test private key
rs := IdHTTP1.Post('https://api.stripe.com/v1/charges', postData);
StatusBar1.SimpleText := IdHTTP1.ResponseText;
finally
postData.Free;
end;