以下是我的URL请求:
curl -X POST -u apikey:secret 'https://numbers.api.sinch.com/v1/projects/{project ID}/availableNumbers:rentAny' \
-d '{
"regionCode": "US",
"type": "LOCAL",
"numberPattern": {
"pattern": "206",
"searchPattern": "START"
},
"smsConfiguration": {
"servicePlanId": "{service plan ID}"
}
}'
我收到了200个回复,一切都按预期进行。
下面是我对Ruby的rest-client
所做的:
opts = {
:method=>:post,
:payload=>{"smsConfiguration"=>{"servicePlanId"=>"service plan ID"}, "numberPattern"=>{"pattern"=>"206", "searchPattern"=>"START"}, "regionCode"=>"US", "type"=>"LOCAL"},
:url=>"https://numbers.api.sinch.com/v1/projects/{project ID}/availableNumbers:rentAny",
:headers=>{},
:user=>"API key",
:password=>"secret"
}
begin
RestClient::Request.execute(opts)
rescue RestClient::BadRequest => e
puts e.response.body
end
返回400响应。声明中写道:
"{\"error\":{\"code\":400,\"message\":\"invalid character 's' looking for beginning of value\",\"status\":\"INVALID_ARGUMENT\",\"details\":[]}}\n"
我期望从我的rest-client
得到200个响应,使用与我的CURL请求相同的数据。
1条答案
按热度按时间ig9co6j11#
如果API在请求体中期望JSON文档,则需要告诉RestClient这一点,否则,它将生成内容类型为
application/x-www-form-urlencoded
和表单编码体的POST请求。在body上使用
to_json
来编码它,并添加headers: { content_type: :json }
来告诉RestClient发出JSON请求。请注意,在第一个示例中,在CURL请求中还包括
Content-Type
和Accept
头会更正确,但在没有设置这些头的情况下,API似乎可能会假定JSON。但是,RestClient不能做出这种假设,您需要明确地告诉它您打算发送JSON。