httpsimple 1.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (5) hide show
  1. data/Gemfile +6 -0
  2. data/LICENSE +20 -0
  3. data/README.md +78 -0
  4. data/lib/httpsimple.rb +136 -0
  5. metadata +49 -0
data/Gemfile ADDED
@@ -0,0 +1,6 @@
1
+ source :rubygems
2
+ gemspec
3
+
4
+ group :test do
5
+ gem 'fakeweb'
6
+ end
data/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2012 Shawn Adams
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,78 @@
1
+ # httpsimple
2
+
3
+ Thin wrapper around net/http. Handles HTTPS and follows redirects.
4
+
5
+ ## Install
6
+
7
+ $ gem install httpsimple
8
+
9
+ ## Examples
10
+
11
+ ### GET requests are simple
12
+ ```Ruby
13
+ require 'httpsimple'
14
+ # With parameters
15
+ response = HttpSimple.get('http://www.service.com/user', :username => 'bob')
16
+ # Without
17
+ response = HttpSimple.get('http://www.service.com/user')
18
+ ```
19
+ <tt>response</tt> is a Net::HTTPOk object.
20
+
21
+ ### POST requests are simple
22
+ ```Ruby
23
+ # Parameter as a Hash will send an application/x-www-form-urlencoded request
24
+ response = HttpSimple.post('http://www.service.com/user', :username => 'bob')
25
+ # You can also pass a string for the post body
26
+ response = HttpSimple.post('http://www.service.com/user', 'I am the post body!')
27
+ ```
28
+
29
+ ### Headers are simple
30
+ ```Ruby
31
+ url = 'http://service.com/user_add'
32
+ response = HttpSimple.post(url, '<user>bob</user>') do |simple|
33
+ # 'simple' is an instance of HttpSimple::Http
34
+ simple.headers["Content-Type"] = "text/xml"
35
+ end
36
+ ```
37
+
38
+ ### Other stuff you can set
39
+ ```Ruby
40
+ url = 'https://www.service.com/login'
41
+ response = HttpSimple.post(url, :username => 'bob', :password => '1234') do |simple|
42
+ # More headers
43
+ simple.headers['Accept'] = 'gzip, deflate'
44
+ # Read time out (default 90)
45
+ simple.timeout = 120
46
+ # Max number of redirects to follow (default 3)
47
+ simple.max_redirects = 2
48
+ # Turn off ssl cert verification - dangerous
49
+ simple.strict_ssl = false
50
+ end
51
+ ```
52
+
53
+ ## Response handlers
54
+
55
+ You can register a code block to run when a certain http status code is received. Your code block
56
+ should accept three arguments:
57
+
58
+ 1. Net::HTTP object.
59
+ 2. Net::HTTPRequest object.
60
+ 3. Net::HTTPResponse object.
61
+
62
+ ```Ruby
63
+ simple = HttpSimple.new
64
+ simple.add_handler(200) do |http, req, res|
65
+ puts res.code # 200
66
+ end
67
+ simple.add_handler(301, 302) do |http, req, res|
68
+ puts "#{req.path} was redirected to #{res['location']}!"
69
+ end
70
+ res = simple.get("http://www.example.com")
71
+ ```
72
+
73
+ ### Remove response handlers
74
+ ```Ruby
75
+ simple.remove_handler(200)
76
+ ```
77
+
78
+
data/lib/httpsimple.rb ADDED
@@ -0,0 +1,136 @@
1
+ require 'net/http'
2
+ require 'uri'
3
+
4
+ module HttpSimple
5
+ def self.get(url, data=nil, &block)
6
+ request(url, :get, data, &block)
7
+ end
8
+
9
+ def self.post(url, data=nil, &block)
10
+ request(url, :post, data, &block)
11
+ end
12
+
13
+ def self.new
14
+ Http.new
15
+ end
16
+
17
+ def self.request(url, get_or_post, data, &block)
18
+ http = Http.new
19
+ block.call(http) unless block.nil?
20
+ http.send(get_or_post, url, data)
21
+ end
22
+ private_class_method :request
23
+
24
+ # Raised when max redirects exceeded.
25
+ class HTTPMaxRedirectError < StandardError
26
+ def initialize(max)
27
+ super("Max redirects (#{max}) exceeded.")
28
+ end
29
+ end
30
+
31
+ class Http
32
+ attr_accessor :headers, :max_redirects,
33
+ :strict_ssl, :timeout, :handlers
34
+ attr_reader :url
35
+
36
+ def initialize
37
+
38
+ @headers = {}
39
+ @max_redirects = 3
40
+ @strict_ssl = true
41
+ @timeout = 90
42
+ # Response handlers
43
+ @handlers = {}
44
+
45
+ end
46
+
47
+ def add_handler(*status_codes, &handler)
48
+ # Add response handle for http status code. ie 200, 302, 400
49
+ if block_given?
50
+ status_codes.each { |code| @handlers[code.to_s.to_sym] = handler }
51
+ end
52
+ end
53
+
54
+ def remove_handler(*status_codes)
55
+ # Remove response handler for http status code.
56
+ status_codes.each { |code| @handlers.delete(code.to_s.to_sym) }
57
+ end
58
+
59
+ def get(url, params=nil)
60
+ uri = URI(url)
61
+ uri.query = URI.encode_www_form(params) unless params.nil?
62
+ request = Net::HTTP::Get.new(uri.to_s)
63
+
64
+ if block_given?
65
+ yield uri, request
66
+ else
67
+ fetch(uri, request, @max_redirects)
68
+ end
69
+
70
+ end
71
+
72
+ def post(url, body=nil)
73
+ uri = URI(url)
74
+ request = Net::HTTP::Post.new(uri.to_s)
75
+
76
+ case body
77
+ when String
78
+ request.body = body
79
+ when Hash
80
+ request.set_form_data(body)
81
+ end
82
+
83
+ if block_given?
84
+ yield uri, request
85
+ else
86
+ fetch(uri, request, @max_redirects)
87
+ end
88
+
89
+ end
90
+
91
+ def fetch(uri, request, limit=1)
92
+ http = Net::HTTP.new(uri.host, uri.port)
93
+ http.use_ssl = uri.scheme == 'https'
94
+ http.verify_mode = OpenSSL::SSL::VERIFY_NONE unless @scrict_ssl
95
+ http.read_timeout = @timeout
96
+
97
+ @headers.each_pair { |k,v| request[k] = v } unless @headers.empty?
98
+
99
+ response = http.start do |http|
100
+ http.request(request)
101
+ end
102
+
103
+ code = response.code.to_sym
104
+ if @handlers.key?(code)
105
+ @handlers[code].call(http, request, response)
106
+ end
107
+
108
+ case response
109
+ when Net::HTTPSuccess
110
+ return response
111
+ when Net::HTTPRedirection
112
+ raise HTTPMaxRedirectError.new(@max_redirects) if limit == 0
113
+ block = lambda { |url, req| fetch(url, req, limit - 1) }
114
+ if request.is_a? Net::HTTP::Get
115
+ get(response['location'], &block)
116
+ elsif request.is_a? Net::HTTP::Post
117
+ post(response['location'], &block)
118
+ end
119
+ when Net::HTTPResponse
120
+ response.error!
121
+ end
122
+
123
+ end
124
+ private :fetch
125
+
126
+ def get_path(uri)
127
+ if uri.path.length == 0 and uri.query.nil?
128
+ "/"
129
+ elsif uri.query.nil?
130
+ uri.path
131
+ else
132
+ "#{uri.path}?#{uri.query}"
133
+ end
134
+ end
135
+ end
136
+ end
metadata ADDED
@@ -0,0 +1,49 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: httpsimple
3
+ version: !ruby/object:Gem::Version
4
+ version: '1.0'
5
+ prerelease:
6
+ platform: ruby
7
+ authors:
8
+ - Shawn Adams
9
+ autorequire:
10
+ bindir: bin
11
+ cert_chain: []
12
+ date: 2012-05-10 00:00:00.000000000 Z
13
+ dependencies: []
14
+ description: ! " Simple wrapper around Ruby's net/http library. It supports \n redirects
15
+ and HTTPS.\n"
16
+ email: ruby.httpsimple@gmail.com
17
+ executables: []
18
+ extensions: []
19
+ extra_rdoc_files: []
20
+ files:
21
+ - Gemfile
22
+ - README.md
23
+ - LICENSE
24
+ - lib/httpsimple.rb
25
+ homepage: https://github.com/boris317/httpsimple
26
+ licenses: []
27
+ post_install_message:
28
+ rdoc_options: []
29
+ require_paths:
30
+ - lib
31
+ required_ruby_version: !ruby/object:Gem::Requirement
32
+ none: false
33
+ requirements:
34
+ - - ! '>='
35
+ - !ruby/object:Gem::Version
36
+ version: 1.8.7
37
+ required_rubygems_version: !ruby/object:Gem::Requirement
38
+ none: false
39
+ requirements:
40
+ - - ! '>='
41
+ - !ruby/object:Gem::Version
42
+ version: '0'
43
+ requirements: []
44
+ rubyforge_project:
45
+ rubygems_version: 1.8.23
46
+ signing_key:
47
+ specification_version: 3
48
+ summary: Simple wrapper around Ruby's net/http
49
+ test_files: []