Created
June 28, 2017 11:57
-
-
Save miyohide/91025fc62f1ab527ad7db08ede6e53a2 to your computer and use it in GitHub Desktop.
Amazonの商品データをrpaproxy経由で取ってくるサンプル
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'net/http' | |
require 'uri' | |
require 'timeout' | |
AMAZON_ECS_URL='http://rpaproxy.tdiary.org/rpaproxy/jp/' | |
SUBSCRIPTION_ID='xxxxxxxxxxxxxxxxxxxxxxxxxx' | |
API_VERSION='2007-01-17' | |
def amazon_fetch(url, limit = 10) | |
raise ArgumentError, 'HTTP redirect too deep' if limit == 0 | |
res = Net::HTTP.get_response(URI::parse(url)) | |
case res | |
when Net::HTTPSuccess | |
res.body | |
when Net::HTTPRedirection | |
amazon_fetch(res['location'].untaint, limit - 1) | |
else | |
raise ArgumentError, res.error! | |
end | |
end | |
def amazon_call(asin, id_type) | |
aid = 'xxxxxxxxx' | |
url = "#{AMAZON_ECS_URL}?Service=AWSECommerceService" | |
url << "&SubscriptionId=#{SUBSCRIPTION_ID}" | |
url << "&AssociateTag=#{aid}" | |
url << "&Operation=ItemLookup" | |
url << "&ItemId=#{asin}" | |
url << "&IdType=#{id_type}" | |
url << "&SearchIndex=Books" if id_type == 'ISBN' | |
# url << "&ResponseGroup=Medium" | |
# url << "&Version=#{API_VERSION}" | |
begin | |
Timeout.timeout(10) do | |
amazon_fetch(url) | |
end | |
rescue ArgumentError | |
end | |
end | |
xml = amazon_call('9784274050657', 'ISBN') | |
File.open('9784274050657.xml', 'wb') { |f| f.write(xml) } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment