Ruby的REST客户端没有复制我的CURL请求,我不知道我做了什么不同的事情

imzjd6km  于 12个月前  发布在  Ruby
关注(0)|答案(1)|浏览(98)

以下是我的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请求相同的数据。

ig9co6j1

ig9co6j11#

如果API在请求体中期望JSON文档,则需要告诉RestClient这一点,否则,它将生成内容类型为application/x-www-form-urlencoded和表单编码体的POST请求。
在body上使用to_json来编码它,并添加headers: { content_type: :json }来告诉RestClient发出JSON请求。

RestClient::Request.execute(
  method: :post,
  payload: { "smsConfiguration" => { ... } }.to_json,
  headers: { 
    content_type: :json,
  },
  # ...
)

请注意,在第一个示例中,在CURL请求中还包括Content-TypeAccept头会更正确,但在没有设置这些头的情况下,API似乎可能会假定JSON。
但是,RestClient不能做出这种假设,您需要明确地告诉它您打算发送JSON。

相关问题