Last active
August 29, 2015 14:01
-
-
Save goofmint/cca4b45c4b4aac60a61c to your computer and use it in GitHub Desktop.
POST or GET to Nifty Cloud Mobile Backend
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
# -*- coding: utf-8 -*- | |
require 'time' | |
require 'openssl' | |
require 'Base64' | |
require "net/http" | |
require "uri" | |
APPLICATION_KEY = 'your_application_key' | |
CLIENT_KEY = 'client_key' | |
DOMAIN = "mb.api.cloud.nifty.com" | |
def ncmb_query(method, path, queries = {}) | |
encoded_queries = {} | |
queries.each do |k, v| | |
encoded_queries[URI.encode(k.to_s)] = URI.encode(v.to_s) | |
end | |
params_base = { | |
"SignatureMethod" => "HmacSHA256", | |
"SignatureVersion" => "2", | |
"X-NCMB-Application-Key" => APPLICATION_KEY | |
} | |
params = params_base.merge(encoded_queries) | |
now = Time.now.utc.iso8601 | |
params = params.merge "X-NCMB-Timestamp" => now | |
params = Hash[params.sort{|a, b| a[0].to_s <=> b[0].to_s}] | |
query = encoded_queries.collect{|k,v| "#{k}=#{v}"}.join('&') | |
signature_base = <<-EOS | |
#{method} | |
#{DOMAIN} | |
#{path} | |
#{params.collect{|k,v| "#{k}=#{v}"}.join("&")} | |
EOS | |
signature_base.chomp! | |
signature = Base64.encode64(OpenSSL::HMAC.digest(OpenSSL::Digest::Digest.new('sha256'), CLIENT_KEY, signature_base)).strip() | |
http = Net::HTTP.new(DOMAIN, 443) | |
http.use_ssl=true | |
headers = {"X-NCMB-Application-Key" => params_base["X-NCMB-Application-Key"], | |
"X-NCMB-Signature" => signature, | |
"X-NCMB-Timestamp" => now, | |
"Content-Type" => 'application/json'} | |
path = path + (query == '' ? "" : "?"+query) | |
if method == "GET" | |
return http.get(path, headers).body | |
else | |
return http.post(path, headers).body | |
end | |
end | |
if __FILE__ == $PROGRAM_NAME | |
path = "/2013-09-01/classes/TestClass" # 実行するURL | |
queries = {:count => "1", :limit => "20", :order => "-createDate", :skip => "0", :where => '{"message":"test"}'} # クエリ | |
puts ncmb_query "POST", path, queries | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment