gpt4 book ai didi

ruby - 将数据字段添加到 Ruby 中的 rest-client 请求

转载 作者:太空宇宙 更新时间:2023-11-03 17:48:27 25 4
gpt4 key购买 nike

我在使用 rest-client gem 向 uber api 发出请求时遇到问题。我认为问题在于我试图将所需信息作为参数而不是数据字段传递到 url 中。示例 curl 请求在 -d 之后具有该参数,但我不知道如何使用 rest-client 实现它。感谢您的帮助。

此请求在控制台中有效:

curl -v -H "Authorization: Bearer " + session[:request_token] \
-H "Content-Type: application/json" -X POST -d \ '{"start_latitude":"37.334381","start_longitude":"-121.89432","end_latitude":"37.77703","end_longitude":"-122.419571","product_id":"a1111c8c-c720-46c3-8534-2fcdd730040d"}' \
https://sandbox-api.uber.com/v1/requests

来 self 的 Controller 的请求收到 406 错误, Not Acceptable 响应。

@uber_ride = JSON.load(RestClient::Request.execute(
:method => :post,
:url => "https://sandbox-api.uber.com/v1/sandbox/requests/product_id=#{@uberx_id}?start_latitude=#{lat_start}&start_longitude=#{lng_start}&end_latitude=#{lat_end}&end_longitude=#{lng_end}",
:headers => {'Authorization' => 'Bearer ' + session[:request_token], 'content_type' => 'application/json'}
))

我尝试为 data 添加一个额外的字段,但会出现 404 Resource Not Found 错误。

@uber_ride = JSON.load(RestClient::Request.execute(
:method => :post,
:url => "https://sandbox-api.uber.com/v1/sandbox/requests/",
:data => {'start_latitude' => lat_start, 'start_longitude' => lng_start, 'end_latitude' => lat_end, 'end_longitude' => lng_end, 'product_id' => @uberx_id},
:headers => {'Authorization' => 'Bearer ' + session[:request_token]},
:content_type => :json
))

最佳答案

我终于让它工作了。感谢@mudasobwa 建议将 data => 更改为 payload =>。我还必须在有效负载对象周围添加单引号,这样 rest-client gem 就不会将它从 json 中转换出来。例如:'{}'。最后,我不得不更改指定内容类型的方式,并在 :headers 中将其指定为 :content_type,而不是 'Content-Type'。请参阅下文了解正在运行的最终请求。变量是 .to_s 有点困惑,但 5 小时后,这是我唯一可以开始工作的电话。

@uber_ride = (RestClient::Request.execute(
:method => :post,
:url => "https://sandbox-api.uber.com/v1/requests",
:payload => '{"start_latitude":' + lat_start.to_s + ',"start_longitude":' + lng_start.to_s + ',"end_latitude":' + lat_end.to_s + ',"end_longitude":' + lng_end.to_s + ',"product_id":"' + @uberx_id.to_s + '"}',
:headers => {'Authorization' => 'Bearer ' + session[:request_token], :content_type => 'application/json'}
))

很高兴听到关于如何清理它的任何反馈。

关于ruby - 将数据字段添加到 Ruby 中的 rest-client 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29849886/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com