[英]Sending a JSON to an API Url through Ruby on Rails
I have a json object that I'm sending to Google's QXP Express API. 我有一个要发送到Google的QXP Express API的json对象。 The idea is that I send the object with the relevant travel information. 我的想法是向我发送带有相关旅行信息的对象。 In terminal, through curl, it's very easy to send it. 在终端中,通过curl可以很容易地发送它。 I just use the following curl command. 我只是使用以下curl命令。 Doc.json is the file name of the json. Doc.json是json的文件名。
curl -d @doc.json --header "Content-Type: application/json" https://www.googleapis.com/qpxExpress/v1/trips/search?key=AIzaSyAaLHEBBLCI4aHLNu2jHiiAQGDbCunBQX0
This is my code to do it in Ruby. 这是我在Ruby中执行的代码。
uri = URI('https://www.googleapis.com/qpxExpress/v1/trips/search?key=MYAPIKEY')
req = Net::HTTP::Post.new uri.path
req.body = {
"request" => {
"passengers" => {
"adultCount" => 1
},
"slice" => [
{
"origin" => "BOS",
"destination" => "LAX",
"date" => "2014-10-14"
},
{
"origin" => "LAX",
"destination" => "BOS",
"date" => "2014-11-14"
}
]
}
}.to_json
res = Net::HTTP.start(uri.host, uri.port, :use_ssl => true) do |http|
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
http.ssl_version = :SSLv3
http.request req
end
puts res.body
However I'm getting back the following error. 但是我回来了以下错误。
{
"error": {
"errors": [
{
"domain": "global",
"reason": "parseError",
"message": "This API does not support parsing form-encoded input."
}
],
"code": 400,
"message": "This API does not support parsing form-encoded input."
}
}
I just need to send it with the json file, but nothing I can find online covers sending json's to APIs. 我只需要将其与json文件一起发送,但是我找不到在线内容涵盖将json发送到API的内容。 Please help, I'm very stuck. 请帮助,我很困。
It is always matter of taste what tools you prefer, but as for me i am currently using the rest-client gem for accessing REST APIs. 总是喜欢使用哪种工具,但是就我而言,我目前正在使用rest-client gem访问REST API。 With this library your example could be written like this: 使用这个库,您的示例可以这样写:
require 'json'
require 'rest-client'
response = RestClient.post 'https://www.googleapis.com/qpxExpress/v1/trips/search?key=AIzaSyAaLHEBBLCI4aHLNu2jHiiAQGDbCunBQX0',
{
request: {
passengers: {
adultCount: 1
},
slice: [
{
origin: "BOS",
destination: "LAX",
date: "2014-10-14"
},
{
origin: "LAX",
destination: "BOS",
date: "2014-11-14"
}
]
}
}.to_json,
:content_type => :json
puts response.body
But if you want a Net::HTTP only solution, this might not be a suitable answer for you. 但是,如果您只需要Net :: HTTP解决方案,那么这可能不适合您。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.