使用httparty
我正在向GET请求:
https://api.marktplaats.nl/api3/categories.json?oauth_token=1me6jq76h8t6rim747m7bketkd&api_ver=3.7&session=ebc565b8-659f-40f6-9d0a-96986f1d1595&screenWidth=62&screenHeight=111&app_ver=Android3.1.0
代码A:
require 'httparty'
class Marktplaats
def categories
HTTParty.get('https://api.marktplaats.nl/api3/categories.json?oauth_token=1me6jq76h8t6rim747m7bketkd&api_ver=3.7&session=ebc565b8-659f-40f6-9d0a-96986f1d1595&screenWidth=62&screenHeight=111&app_ver=Android3.1.0')
end
end
代码B:
require 'httparty'
class Marktplaats
@oauth_token = '1me6jq76h8t6rim747m7bketkd'
def categories
HTTParty.get("https://api.marktplaats.nl/api3/categories.json?oauth_token=#{@oauth_token}&api_ver=3.7&session=ebc565b8-659f-40f6-9d0a-96986f1d1595&screenWidth=62&screenHeight=111&app_ver=Android3.1.0")
end
end
做的时候:
m = Marktplaats.new
m.categories
代码A有效,但代码B没有。
在代码B的GET调用上调用.request.last_uri.to_s
返回:
https://api.marktplaats.nl/api3/categories.json?oauth_token=&api_ver=3.7&session=ebc565b8-659f-40f6-9d0a-96986f1d1595&screenWidth=62&screenHeight=111&app_ver=Android3.1.0
可能出现什么问题?
答案 0 :(得分:5)
这是在类级别与实例级之间定义变量的情况。您已在类级别定义@oauth_token
,但尝试在实例级别使用它,但不能。尝试将代码更改为:
class Marktplaats
def initialize
@oauth_token = '1me6jq76h8t6rim747m7bketkd'
end
def categories
HTTParty.get("https://api.marktplaats.nl/api3/categories.json?oauth_token=#{@oauth_token}&api_ver=3.7&session=ebc565b8-659f-40f6-9d0a-96986f1d1595&screenWidth=62&screenHeight=111&app_ver=Android3.1.0")
end
end
OR,它使用一个在类和实例级别都可访问的常量(但不应该更改)。:
class Marktplaats
OAUTH_TOKEN = '1me6jq76h8t6rim747m7bketkd'
def categories
HTTParty.get("https://api.marktplaats.nl/api3/categories.json?oauth_token=#{OAUTH_TOKEN}&api_ver=3.7&session=ebc565b8-659f-40f6-9d0a-96986f1d1595&screenWidth=62&screenHeight=111&app_ver=Android3.1.0")
end
end
答案 1 :(得分:2)
您正在创建一个类 - 实例变量,但在方法中使用本地实例变量。这样做:
require 'httparty'
class Marktplaats
OAUTH_TOKEN= '1me6jq76h8t6rim747m7bketkd'
def categories
HTTParty.get("https://api.marktplaats.nl/api3/categories.json?oauth_token=#{OAUTH_TOKEN}&api_ver=3.7&session=ebc565b8-659f-40f6-9d0a-96986f1d1595&screenWidth=62&screenHeight=111&app_ver=Android3.1.0")
end
end