Skip to content

Instantly share code, notes, and snippets.

@miyohide
Created June 28, 2017 11:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save miyohide/91025fc62f1ab527ad7db08ede6e53a2 to your computer and use it in GitHub Desktop.
Save miyohide/91025fc62f1ab527ad7db08ede6e53a2 to your computer and use it in GitHub Desktop.
Amazonの商品データをrpaproxy経由で取ってくるサンプル
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