Ruby

データストレージ API

Ruby
sample.rb
# This is a sample ruby script code for IIJ IoT Data Storage Web API.
# For more information please refer to the manual.

# require packages
# if you do not install packages, please use 'gem' to install.
require 'rubygems'
require 'time'
require 'net/http'
require 'base64'
require 'openssl'
require 'xmlsimple'

BASE_URL = 'https://s3api.iot.iij.jp'  # not edit
HOST = 's3api.iot.iij.jp'              # not edit

access_key = ''             # your access key
secret_key = ''             # your secret key
content_md5 = ''            # if you upload file, you have to write.
content_type = ''           # not edit
date = Time.now.httpdate    # now date
root = ''                   # if you use payload, you specify root of xml.
# if you needed. We expect xml.
payload2hash = {}
payload = XmlSimple.xml_out(payload2hash, RootName: root)
content_length = payload.length
http_verb = 'GET'           # or POST, PUT, DELETE, HEAD
bucket_name = '/sample'     # specify your bucket
query = ''                  # if you needed. e.g. ?id=hoge
canonicalized_headers = ''  # if you use optional headers, you have to write.
canonicalized_resource = bucket_name + query

string2sign = http_verb + "\n" +
              content_md5 + "\n" +
              content_type + "\n" +
              date + "\n" +
              canonicalized_headers +
              bucket_name

# create signature
hmac = OpenSSL::HMAC.digest('sha1', secret_key.encode('utf-8'), string2sign.encode('utf-8'))
signature = Base64.encode64(hmac).chomp!

uri = URI(BASE_URL + canonicalized_resource)
request = Net::HTTP::Get.new(uri.request_uri)
# request = Net::HTTP::Post.new(uri.request_uri)
# request = Net::HTTP::Put.new(uri.request_uri)
# request = Net::HTTP::Delete.new(uri.request_uri)
# request = Net::HTTP::Head.new(uri.request_uri)

request['Authorization'] = "IIJGIO " + access_key + ":" + signature
request['Content-MD5'] = content_md5
request['Content-Type'] = content_type
request['Content-Length'] = content_length
request['Date'] = date
request['Host'] = HOST
# request.body = payload

http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
response = http.request(request)

puts("Status Code: " + response.code)
puts("Body:\n" + response.body)