Module: GMO::NetHTTPService

Defined in:
lib/gmo/http_services.rb

Class Method Summary collapse

Class Method Details

.included(base) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/gmo/http_services.rb', line 28

def self.included(base)
  base.class_eval do
    require "net/http" unless defined?(Net::HTTP)
    require "net/https"

    include GMO::HTTPService

    def self.make_request(path, args, verb, options = {})
      args.merge!({:method => verb}) && verb = "post" if verb != "get" && verb != "post"

      http = create_http(server(options), options)
      http.use_ssl = true

      http.start do |h|
        response = if verb == "post"
          h.post(path, encode_params(args))
        else
          h.get("#{path}?#{encode_params(args)}")
        end
        GMO::Response.new(response.code.to_i, response.body, response)
      end
    end

    protected

      def self.encode_params(param_hash)
        ((param_hash || {}).collect do |key_and_value|
          key_and_value[1] = GMO::JSON.dump(key_and_value[1]) if key_and_value[1].class != String
          # converting to Shift-JIS
          sjis_value = NKF.nkf('-s', key_and_value[1])
          "#{key_and_value[0].to_s}=#{CGI.escape sjis_value}"
        end).join("&")
      end

      def self.create_http(server, options)
        if options[:proxy]
          proxy = URI.parse(options[:proxy])
          http  = Net::HTTP.new \
            server, 443,
            proxy.host, proxy.port,
            proxy.user, proxy.password
        else
          http = Net::HTTP.new server, 443
        end
        if options[:timeout]
          http.open_timeout = options[:timeout]
          http.read_timeout = options[:timeout]
        end
        http
      end

  end
end