Class: EasyHTTP::Session

Inherits:
Object
  • Object
show all
Defined in:
lib/easy_http/session.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(url, options = {}) ⇒ Session

Returns a new instance of Session.



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/easy_http/session.rb', line 32

def initialize url, options = {}
  @cookies = nil # Initialize cookies store to nil
  @default_headers = {
    'User-Agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.101 Safari/537.11'
  } # Initialize default headers
  @options = options # Store Options

  # Store base URL
  @base_url = url.match(/^http/) ? url : "#{@options[:ssl] ? 'https' : 'http'}://#{url}"

  unless options[:port].nil?
    @base_url = "#{@base_url}:#{options[:port]}" unless @base_url.match(/":#{options[:port]}"^/)
  end

  # Store credentials
  @username = options[:username] unless options[:username].nil?
  @password = options[:password] unless options[:password].nil?

  @uri = URI(@base_url) # Parse URI Object

  @max_redirs = options[:max_redirs] || 5

  create_ua
end

Instance Attribute Details

#base_urlObject

Base URL



9
10
11
# File 'lib/easy_http/session.rb', line 9

def base_url
  @base_url
end

#cookiesObject

Session Cookies



21
22
23
# File 'lib/easy_http/session.rb', line 21

def cookies
  @cookies
end

#default_headersObject

Default headers



12
13
14
# File 'lib/easy_http/session.rb', line 12

def default_headers
  @default_headers
end

#default_response_charsetObject

Default request charset



27
28
29
# File 'lib/easy_http/session.rb', line 27

def default_response_charset
  @default_response_charset
end

#httpObject

Net:HTTP object



6
7
8
# File 'lib/easy_http/session.rb', line 6

def http
  @http
end

#max_redirsObject

Control redirects



30
31
32
# File 'lib/easy_http/session.rb', line 30

def max_redirs
  @max_redirs
end

#optionsObject

Options sent to the constructor



18
19
20
# File 'lib/easy_http/session.rb', line 18

def options
  @options
end

#passwordObject

HTTP Auth credentials



24
25
26
# File 'lib/easy_http/session.rb', line 24

def password
  @password
end

#uriObject

URI Objet for requests



15
16
17
# File 'lib/easy_http/session.rb', line 15

def uri
  @uri
end

#usernameObject

HTTP Auth credentials



24
25
26
# File 'lib/easy_http/session.rb', line 24

def username
  @username
end

Instance Method Details

#create_uaObject



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/easy_http/session.rb', line 57

def create_ua
  # Create the Session Object
  @http = Net::HTTP.new(uri.host, uri.port)

  # Set passed read timeout
  @http.read_timeout = options[:read_timeout] ||= 1000

  # Enable debug output
  @http.set_debug_output options[:debug]  unless options[:debug].nil?

  # Enable SSL if necessary
  @http.use_ssl = true if @options[:ssl]

  # Allow work with insecure servers
  @http.verify_mode = OpenSSL::SSL::VERIFY_NONE if @options[:insecure]
end

#get(path, query = nil, headers = {}) ⇒ Object

Method for GET request



80
81
82
# File 'lib/easy_http/session.rb', line 80

def get path, query = nil, headers = {}
  send_request :get, path, headers, :query => query
end

#marshal_dumpObject



154
155
156
# File 'lib/easy_http/session.rb', line 154

def marshal_dump
  [ @base_url, @default_headers, @uri, @options, @cookies , @username, @password, @default_response_charset ]
end

#marshal_load(data) ⇒ Object



158
159
160
161
# File 'lib/easy_http/session.rb', line 158

def marshal_load data
  @base_url, @default_headers, @uri, @options, @cookies , @username, @password, @default_response_charset = data
  create_ua
end

#post(path, data, headers = {}) ⇒ Object

Method for POST request



85
86
87
88
# File 'lib/easy_http/session.rb', line 85

def post path, data, headers = {}
  headers['Content-Type'] = 'application/x-www-form-urlencoded' if headers['Content-Type'].nil?
  send_request :post, path, headers, :data => data
end

#send_request(action, path, headers, request_options = {}, redir = 0) ⇒ Object

Send an HTTP request



91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'lib/easy_http/session.rb', line 91

def send_request action, path, headers, request_options = {}, redir = 0
  # Parse path to prevent errors
  path = "/#{path}" unless path.match(/^"\/"/)

  # Create the request
  case action
  when :get
    # Create a GET method
    request = Net::HTTP::Get.new(path)
  when :post
    # Create a POST method
    request = Net::HTTP::Post.new(path)

    # Set data to send
    if request_options[:data].is_a?(Hash)
      request.set_form_data request_options[:data]
    elsif request_options[:data].is_a?(String)
      request.body = request_options[:data]
    end

  else
    # Raises exception?¿
  end

  unless request.nil?
    # Enable auth if user parameter is set on constructor
    request.basic_auth(@username, @password) unless @username.nil?

    # Set rdefault and equest headers
    @default_headers.each { |k,v| request[k] = v}
    headers.each { |k,v| request[k] = v}

    # If we have activated store cookie, we define it for the request
    unless @cookies.nil?
      request['Cookie'] = request['Cookie'].nil? ? format_cookies : [request['Cookie'], format_cookies].join("; ")
    end
    # make request
    response = http.request(request)

    unless response.nil?
      # Store cookies if have enabled store it
      handle_cookies response unless @cookies.nil?

      # Generate and return response or follow redir
      case response
      when Net::HTTPSuccess
        return Response.new "#{base_url}#{path}", response, @default_response_charset
      when Net::HTTPRedirection
        if redir == @max_redirs
          return Response.new "#{base_url}#{path}", response, @default_response_charset
        else
          puts "redir (#{redir}) from #{path} to #{response['location']}"
          return send_request action, URI.parse(response['location']).path, headers, request_options, redir + 1

        end
      else
        return Response.new "#{base_url}#{path}", response, @default_response_charset
      end

    end
  end
end

#session_cookiesObject

Initialize store cookies for this session



75
76
77
# File 'lib/easy_http/session.rb', line 75

def session_cookies
  @cookies = {}
end