我正试图将一个DateTime格式的RFC3339传递给API,但由于格式不正确,它一直被拒绝。是否有不同的方式来转换成正确的格式?
require 'cgi'
require 'date'
require 'uri'
startTime=CGI.escape(DateTime.new(2016, 6, 6, 15, 47, 40).strftime("%Y-%m-%dT%H:%M:%SZ"))
endTime=CGI.escape(DateTime.now.strftime("%Y-%m-%dT%H:%M:%SZ"))
puts startTime #start=2014-06-19T15%3A47%3A40Z me:2016-05-19T16%3A47%3A04-04%3A00
puts endTime
hist_data=getData(startTime,endTime)
def getData(startTime,endTime)
base="https://api-fxtrade.oanda.com/v1/candles?instrument="
curr="EUR_USD"
granularity="H1"
#https://api-fxtrade.oanda.com/v1/candles?instrument=EUR_USD&start=2014-06-19T15%3A47%3A40Z&end=2014-06-19T15%3A47%3A50Z
myurl = "#{ base }#{ curr }&candleFormat=bidask&granularity=#{ granularity }&dailyAlignment=0&alignmentTimezone=America%2FNew_York&start=#{startTime}&end=#{endTime}"
puts myurl
response =HTTParty.get(URI::encode(myurl))
#{"time"=>"2016-06-03T20:00:00.000000Z", "openBid"=>1.1355, "openAsk"=>1.13564, "highBid"=>1.13727, "highAsk"=>1.13752, "lowBid"=>1.13541, "lowAsk"=>1.13554, "closeBid"=>1.13651, "closeAsk"=>1.13684, "volume"=>2523, "complete"=>true}
response
end但是,当我使用此代码时,结束网站url是有效的。我的代码的全部输出如下:
https://api-fxtrade.oanda.com/v1/candles?instrument=EUR_USD&candleFormat=bidask&granularity=H1&dailyAlignment=0&alignmentTimezone=America%2FNew_York&start=2016-06-06T15%3A47%3A40Z&end=2016-06-08T21%3A53%3A44Z知道为什么在运行该方法时它不起作用,但是当我粘贴URL时,它就能工作了吗?我认为这是一个编码问题,但我肯定是在编码方法中的URL。
发布于 2016-06-09 03:22:39
正如我在上面的注释中所说的,通过自己编码查询参数并使用插值/连接来构建URL,您正在使事情变得非常困难。
我猜想问题在于您正在使用CGI.escape对查询参数进行单独编码,然后第二次使用URI.encode对查询参数进行编码。换句话说,你在对它们进行双重编码。
顺便说一句,CGI.escape和URI.encode做同样的事情,或多或少(前者是deprecated)。还不清楚你为什么同时使用,但这是没有意义的,因为你不应该使用任何一个。你应该让HTTParty帮你做。
为HTTParty.get提供一个基本URL,并使用:query选项向它传递您的(原始的,即未编码的)查询参数的哈希,它将正确地为您完成所有编码。作为一种副作用,它可以编写更清晰的代码:
require "httparty"
require "date"
DATETIME_FMT = "%FT%TZ" # RFC 3339
BASE_URI = "https://api-fxtrade.oanda.com/v1/candles"
DEFAULT_PARAMS = {
instrument: "EUR_USD",
candleFormat: "bidask",
granularity: "H1",
dailyAlignment: 0,
alignmentTimezone: "America/New_York",
}.freeze
def get_data(start_time, end_time)
params = DEFAULT_PARAMS.merge(
start: start_time.strftime(DATETIME_FMT),
end: end_time.strftime(DATETIME_FMT)
)
HTTParty.get(BASE_URI, query: params)
end
start_time = DateTime.new(2016, 6, 6, 15, 47, 40)
end_time = DateTime.now
hist_data = get_data(start_time, end_time)https://stackoverflow.com/questions/37715708
复制相似问题