如何更改URI对象的path属性?

问题描述 投票:0回答:1

我只想使用略有不同的URI来调用API。该代码段符合我的要求,但是我想知道是否有更有效的方法。

require 'net/http'
require 'json'

# These URIs differ only in the path
orders = URI('https://hft-api.lykke.com/api/Orders?orderType=Unknown')
asset_pairs = URI('https://hft-api.lykke.com/api/AssetPairs')

lykke_req = Net::HTTP::Get.new(orders)
lykke_req['User-Agent'] = 'curl/7.67.0'
lykke_req['api-key'] = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
lykke_req['Accept'] = 'application/json'

response = Net::HTTP.start(orders.hostname,
                           orders.port,
                           :use_ssl => true) {|http| http.request(lykke_req)}

puts JSON.parse(response.body)

lykke_req = Net::HTTP::Get.new(asset_pairs)
lykke_req['User-Agent'] = 'curl/7.67.0'
lykke_req['Accept'] = 'application/json'

response = Net::HTTP.start(asset_pairs.hostname,
                           asset_pairs.port,
                           :use_ssl => true) {|http| http.request(lykke_req)}

puts JSON.parse(response.body)

我要做的是重用相同的代码,但URI略有不同。

对于我的lykke_req对象,我可以写

puts lykke_req
puts lykke_req.path

这给了我

#<Net::HTTP::Get:0x00007f947f1fdce8>
/api/Orders?orderType=Unknown

所以在我看来,我要做的就是更改lykke_req.path的值。但是我不知道该怎么做。我正在寻找这样的东西

lykke_req.path = "/api/AssetPairs"

失败的原因

undefined method `path=' for #<Net::HTTP::Get GET> (NoMethodError)

我在official documentation page上找到了这个,但是我找不到[R]的意思。它是只读的吗?我真的必须经历每次创建新URI对象然后每次创建一个新的Net :: HTTP :: Get对象的麻烦吗?

路径[R]

ruby net-http
1个回答
0
投票

这里的问题是您试图更改网络请求对象而不是uri对象:

irb(main):001:0> uri = URI('https://hft-api.lykke.com/api/Orders?orderType=Unknown')
=> #<URI::HTTPS https://hft-api.lykke.com/api/Orders?orderType=Unknown>
irb(main):002:0> uri.path = '/foo'
=> "/foo"
irb(main):003:0> uri.to_s

但是我真的只是将其包装在一个类中,以便您可以封装和结构化代码并避免重复:

class LykkeAPIClient
  BASE_URI = URI('https://hft-api.lykke.com/api')

  def initalize(api_key:)
    @api_key = api_key
  end

  def get_orders
    get '/Orders?orderType=Unknown'
  end

  def get_asset_pairs
    get '/AssetPairs'
  end

  def get(path)
    req = Net::HTTP::Get.new(BASE_URI.join(path))
    req['User-Agent'] = 'curl/7.67.0'
    req['Accept'] = 'application/json'
    req['api-key'] = @api_key
    response = Net::HTTP.start(req.hostname, req.port, use_ssl: true) do |http|
      http.request(uri)
    end
    # @todo check response status!
    JSON.parse(response.body)
  end
end

@client = LykkeAPIClient.new(api_key: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')
@orders = @client.get_orders
© www.soinside.com 2019 - 2024. All rights reserved.