http-requestor 0.0.4 → 1.0.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -11,8 +11,8 @@ A Wrapper around Net/HTTP which allows you to perform HTTP Requests in a simple
11
11
 
12
12
  === Initialize a domain, and send request to multiple paths
13
13
 
14
- http = HttpRequestor.new("http://www.mydomain.com")
15
- # This will initialize the HttpRequestor class
14
+ http = HTTP::Requestor.new("http://www.mydomain.com")
15
+ # This will initialize the HTTP::Requestor class
16
16
 
17
17
  get_request = http.get(path, parameters, headers)
18
18
  post_request = http.post(path, parameters, headers)
@@ -25,7 +25,7 @@ A Wrapper around Net/HTTP which allows you to perform HTTP Requests in a simple
25
25
 
26
26
  === Get a response right away
27
27
 
28
- HttpRequestor.request(domain, request_type, path, parameters, headers)
28
+ HTTP::Requestor.request(domain, request_type, path, parameters, headers)
29
29
  # domain => for example: "http://www.some_domain.com"
30
30
  # request_type => GET|POST|PUT|DELETE
31
31
  # path => for example: "/some_path"
@@ -34,7 +34,7 @@ A Wrapper around Net/HTTP which allows you to perform HTTP Requests in a simple
34
34
 
35
35
  OR you can do it the other way
36
36
 
37
- HttpRequestor.request_with_url(url, request_type, data, headers)
37
+ HTTP::Requestor.request_with_url(url, request_type, data, headers)
38
38
  # url => for example: "http://www.some_domain.com/some_path_value"
39
39
  # request_type => GET|POST|PUT|DELETE
40
40
  # parameters => this is an optional parameter, if you want to send some parameters alongwith the request, you can pass a hash with
@@ -42,11 +42,24 @@ OR you can do it the other way
42
42
 
43
43
  === HTTP Basic Authentication
44
44
 
45
- HttpRequestor.send_basic_auth_request(url, username, password)
45
+ HTTP::Requestor.send_basic_auth_request(url, username, password)
46
46
  # url => for example: "http://www.some_domain.com/some_path_value" only GET URL's supported currently
47
47
  # username => basic_auth_username
48
48
  # password => basic_auth_password
49
+
50
+ === Multipart Form Post
51
+
52
+ uri = "http://some_domain/somepath"
53
+ data = {:file => File.open("testfile.txt")}
54
+ response = HTTP::Requestor.multipart_request(uri, "post | put", data)
55
+
56
+ # If you already have the instance of HTTP::Requestor class then you can upload files as follows:
49
57
 
58
+ http = HTTP::Requestor.new("http://www.mydomain.com")
59
+ response = http.post_multipart(some_path, {:file => File.open("testfile.txt")})
60
+ response = http.put_multipart(some_path, {:file => File.open("testfile.txt")})
61
+
62
+
50
63
  == Issues and Suggestions
51
64
 
52
65
  Please report all the issues in the Github Issues Page, suggestions are also welcome.
@@ -0,0 +1,148 @@
1
+ require "net/http"
2
+ require "net/https"
3
+ require "uri"
4
+
5
+ module HTTP
6
+ class Requestor
7
+ #============== Instance Methods ===================
8
+ def initialize(domain, options={})
9
+ domain = "http://#{domain}" if domain.match(/^(http|https):\/\//).nil?
10
+
11
+ @defaults = {:domain => domain}
12
+ @uri = URI.parse(@defaults[:domain])
13
+ if @uri.scheme == "http"
14
+ @http = Net::HTTP.new(@uri.host, @uri.port)
15
+ else
16
+ @http = Net::HTTP.new(@uri.host, @uri.port)
17
+ @http.use_ssl = true
18
+ @http.verify_mode = OpenSSL::SSL::VERIFY_NONE
19
+ end
20
+ end
21
+
22
+ def get(path,data={},headers=nil)
23
+ data_to_query(data)
24
+ if headers == nil
25
+ response = @http.send_request('GET', path, @defaults[:data])
26
+ else
27
+ response = @http.send_request('GET', path, @defaults[:data], headers)
28
+ end
29
+ response
30
+ end
31
+
32
+ def post(path,data={},headers=nil)
33
+ data_to_query(data)
34
+ if headers == nil
35
+ response = @http.send_request('POST', path, @defaults[:data])
36
+ else
37
+ response = @http.send_request('POST', path, @defaults[:data], headers)
38
+ end
39
+ response
40
+ end
41
+
42
+ def put(path,data={},headers=nil)
43
+ data_to_query(data)
44
+ if headers == nil
45
+ response = @http.send_request('PUT', path, @defaults[:data])
46
+ else
47
+ response = @http.send_request('PUT', path, @defaults[:data], headers)
48
+ end
49
+ response
50
+ end
51
+
52
+ def delete(path,data={},headers=nil)
53
+ data_to_query(data)
54
+ if headers == nil
55
+ response = @http.send_request('DELETE', path, @defaults[:data])
56
+ else
57
+ response = @http.send_request('DELETE', path, @defaults[:data], headers)
58
+ end
59
+ response
60
+ end
61
+
62
+ def data_to_query(data)
63
+ @defaults[:data] = (data.nil? || data.empty?) ? "" : data.to_query
64
+ end
65
+
66
+ #============== Class Methods ===================
67
+ def self.request(domain, request_type, request_path, data={}, headers={}, options={})
68
+ request_type.to_s.upcase!
69
+ request_type = valid_request_types[0] unless valid_request_types.include?(request_type)
70
+ req = self.new(domain, options)
71
+ if request_type == "GET"
72
+ return req.get(request_path, data, headers)
73
+ elsif request_type == "POST"
74
+ return req.post(request_path, data, headers)
75
+ elsif request_type == "PUT"
76
+ return req.put(request_path, data, headers)
77
+ elsif request_type == "DELETE"
78
+ return req.delete(request_path, data, headers)
79
+ end
80
+ end
81
+
82
+ def self.request_with_url(url, request_type, data={}, headers={})
83
+ uri = URI.parse(url)
84
+ return self.request("#{uri.scheme}://#{uri.host}:#{uri.port}", request_type, uri.request_uri, data, headers)
85
+ end
86
+
87
+ def self.send_basic_auth_request(url, username, password)
88
+ uri = URI.parse(url)
89
+
90
+ http = Net::HTTP.new(uri.host, uri.port)
91
+ request = Net::HTTP::Get.new(uri.request_uri)
92
+ request.basic_auth(username, password)
93
+ http.request(request)
94
+ end
95
+
96
+ def self.valid_request_types
97
+ ["GET", "POST", "UPDATE", "DELETE"]
98
+ end
99
+ end
100
+ end
101
+
102
+ #================ ActiveSupport Like object#to_query methods =========================
103
+ class Hash
104
+ def to_query(namespace = nil)
105
+ collect do |key, value|
106
+ value.to_query(namespace ? "#{namespace}[#{key}]" : key)
107
+ end.sort * '&'
108
+ end
109
+ end
110
+
111
+ class Array
112
+ def to_query(key)
113
+ prefix = "#{key}[]"
114
+ collect { |value| value.to_query(prefix) }.join '&'
115
+ end
116
+ end
117
+
118
+ class String
119
+ def to_query(key)
120
+ require 'cgi' unless defined?(CGI) && defined?(CGI::escape)
121
+ "#{CGI.escape(key.to_param)}=#{CGI.escape(to_param.to_s)}"
122
+ end
123
+
124
+ def to_param
125
+ to_s
126
+ end
127
+ end
128
+
129
+ class Symbol
130
+ def to_query(key)
131
+ to_s.to_query(key)
132
+ end
133
+
134
+ def to_param
135
+ to_s
136
+ end
137
+ end
138
+
139
+ class File
140
+ require 'mime/types'
141
+ def original_filename
142
+ path.split("/").last
143
+ end
144
+
145
+ def content_type
146
+ MIME::Types.type_for(original_filename).first
147
+ end
148
+ end
@@ -0,0 +1,95 @@
1
+ module HTTP
2
+ class Requestor
3
+ def post_multipart(path="", data={},headers=nil)
4
+ @uri = URI.parse(@defaults[:domain] + path) unless path.empty?
5
+ build_data(data)
6
+ req = Net::HTTP::Post.new(@uri.request_uri)
7
+ req.initialize_http_header(headers) unless headers.nil?
8
+ req.body = @post_body
9
+ req["Content-Type"] = "multipart/form-data; boundary=#{@boundary}"
10
+ res = @http.request(req)
11
+ @post_body = ""
12
+ @boundary = ""
13
+ res
14
+ end
15
+
16
+ def put_multipart(path="", data={},headers=nil)
17
+ @uri = URI.parse(@defaults[:domain] + path) unless path.empty?
18
+ build_data(data)
19
+ req = Net::HTTP::Put.new(@uri.request_uri)
20
+ req.initialize_http_header(headers) unless headers.nil?
21
+ req.body = @post_body
22
+ req["Content-Type"] = "multipart/form-data; boundary=#{@boundary}"
23
+ res = @http.request(req)
24
+ @post_body = ""
25
+ @boundary = ""
26
+ res
27
+ end
28
+
29
+ def self.multipart_request(domain, request_type, data={}, headers={}, options={})
30
+ request_type.to_s.upcase!
31
+ request_type = valid_request_types[0] unless valid_request_types.include?(request_type)
32
+ req = self.new(domain, options)
33
+
34
+ if request_type == "POST"
35
+ return req.post_multipart("", data, headers)
36
+ elsif request_type == "PUT"
37
+ return req.put_multipart("", data, headers)
38
+ end
39
+ end
40
+
41
+ private
42
+ def create_boundary
43
+ chars = ('a'..'z').to_a + ('A'..'Z').to_a + ('0'..'9').to_a
44
+ boundary = ""
45
+ 20.times { boundary = boundary + chars.sample }
46
+ boundary
47
+ end
48
+
49
+ def build_data(data)
50
+ @boundary = create_boundary
51
+ @post_body = ""
52
+
53
+ create_post_body(data)
54
+
55
+ @post_body << "\r\n--#{@boundary}--\r\n"
56
+ end
57
+
58
+ def create_post_body(parameters, datafile="")
59
+ parameters.each_pair do |key, value|
60
+ unless value.nil?
61
+ disposition = datafile.empty? ? key : "#{datafile}[#{key}]"
62
+ if value.is_a?(File)
63
+ @post_body << "\r\n--#{@boundary}\r\n"
64
+ @post_body << "Content-Disposition: form-data; name=\"#{disposition}\"; filename=\"#{value.original_filename}\"\r\n"
65
+ @post_body << "Content-Type: #{value.content_type}\r\n"
66
+ @post_body << "\r\n"
67
+ @post_body << File.read(value)
68
+ elsif [Hash].include?(value.class)
69
+ create_post_body(value, disposition)
70
+ elsif value.is_a?(Array)
71
+ value.each do |a|
72
+ if [Hash].include?(a.class)
73
+ create_post_body(a, "#{disposition}[]")
74
+ elsif [File].include?(a.class)
75
+ @post_body << "\r\n--#{@boundary}\r\n"
76
+ @post_body << "Content-Disposition: form-data; name=\"#{disposition}[]\"; filename=\"#{a.original_filename}\"\r\n"
77
+ @post_body << "Content-Type: #{a.content_type}\r\n"
78
+ @post_body << "\r\n"
79
+ @post_body << File.read(a)
80
+ else
81
+ @post_body << "\r\n--#{@boundary}\r\n"
82
+ @post_body << "Content-Disposition: form-data; name=\"#{disposition}[]\"\r\n\r\n"
83
+ @post_body << "#{a}"
84
+ end
85
+ end
86
+ else
87
+ @post_body << "\r\n--#{@boundary}\r\n"
88
+ @post_body << "Content-Disposition: form-data; name=\"#{disposition}\"\r\n\r\n"
89
+ @post_body << "#{value}"
90
+ end
91
+ end
92
+ end
93
+ end
94
+ end
95
+ end
@@ -1,22 +1,44 @@
1
- require "../lib/http-requestor"
1
+ require "../lib/http_requestor"
2
+ require "../lib/http_requestor_multipart"
2
3
  require "test/unit"
3
4
 
4
5
  class HttpRequestorTest < Test::Unit::TestCase
5
-
6
- def test_should_raise_error_for_invalid_url_scheme
7
- assert_raise(InvalidURISchemeException) { HttpRequestor.new("some://www.invalid_url_scheme.com") }
6
+ def test_should_get_data_when_request_type_not_specified
7
+ assert_equal("200", HTTP::Requestor.request("http://en.wikibooks.org", "", "/wiki/Ruby_Programming/Unit_testing#A_Simple_Introduction").code )
8
8
  end
9
9
 
10
- def test_should_not_raise_error_for_valid_url_scheme
11
- assert_nothing_raised(InvalidURISchemeException) { HttpRequestor.new("http://www.google.com") }
12
- assert_nothing_raised(InvalidURISchemeException) { HttpRequestor.new("https://www.yahoo.com") }
10
+ def test_should_post_file_properly
11
+ headers = {"application_api_key" => "bltc5b185cd6884ae87", "application_uid" => "blt2f37284c14b6b453"}
12
+ uri = "http://localhost:3000/files.json"
13
+ f=File.open("testfile.txt", "w+")
14
+ f.syswrite("This is testing")
15
+ f.close
16
+ data = {:object => {:title => "This is from http-requestor", :file1 => File.open("testfile.txt")}}
17
+
18
+ assert_equal("201", HTTP::Requestor.multipart_request(uri, "post", data, headers).code)
13
19
  end
20
+
21
+ def test_should_post_file_properly_with_instance_method_used
22
+ http = HTTP::Requestor.new("http://localhost:3000")
23
+
24
+ headers = {"application_api_key" => "bltc5b185cd6884ae87", "application_uid" => "blt2f37284c14b6b453"}
25
+ path = "/files.json"
26
+ f=File.open("testfile.txt", "w+")
27
+ f.syswrite("This is testing")
28
+ f.close
29
+ data = {:object => {:title => "This is from http-requestor", :file1 => File.open("testfile.txt")}}
14
30
 
15
- def test_should_raise_error_on_invalid_request_type
16
- assert_raise(InvalidRequestTypeException) { HttpRequestor.request("http://en.wikibooks.org", "OPTIONS", "/wiki/Ruby_Programming/Unit_testing#A_Simple_Introduction") }
31
+ assert_equal("201", http.post_multipart(path, data, headers).code)
17
32
  end
18
33
 
19
- def test_should_not_raise_error_on_valid_request_type
20
- assert_nothing_raised(InvalidRequestTypeException) { HttpRequestor.request("http://en.wikibooks.org", "GET", "/wiki/Ruby_Programming/Unit_testing#A_Simple_Introduction") }
34
+ def test_should_post_multiple_files
35
+ headers = {"application_api_key" => "bltc5b185cd6884ae87", "application_uid" => "blt2f37284c14b6b453"}
36
+ uri = "http://localhost:3000/multiplefiles.json"
37
+ f=File.open("testfile.txt", "w+")
38
+ f.syswrite("This is testing")
39
+ f.close
40
+ data = {:object => {:title => ["Title 1", "Title 2"], :file => [File.open("testfile.txt"), File.open("testfile.txt")]}}
41
+
42
+ assert_equal("201", HTTP::Requestor.multipart_request(uri, "post", data, headers).code)
21
43
  end
22
44
  end
@@ -0,0 +1 @@
1
+ This is testing
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: http-requestor
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.0.4
4
+ version: 1.0.0
5
5
  prerelease:
6
6
  platform: ruby
7
7
  authors:
@@ -9,20 +9,35 @@ authors:
9
9
  autorequire:
10
10
  bindir: bin
11
11
  cert_chain: []
12
- date: 2012-09-27 00:00:00.000000000Z
13
- dependencies: []
14
- description: A Wrapper around Net/HTTP which allows you to perform HTTP Requests.
12
+ date: 2012-11-23 00:00:00.000000000Z
13
+ dependencies:
14
+ - !ruby/object:Gem::Dependency
15
+ name: mime-types
16
+ requirement: &28629120 !ruby/object:Gem::Requirement
17
+ none: false
18
+ requirements:
19
+ - - ! '>='
20
+ - !ruby/object:Gem::Version
21
+ version: 1.17.2
22
+ type: :runtime
23
+ prerelease: false
24
+ version_requirements: *28629120
25
+ description: ! " A Wrapper around Net/HTTP which allows you to perform HTTP Requests.\n
26
+ \ Gives you a simple API interface to send multipart requests.\n"
15
27
  email: rohit0981989@gmail.com
16
28
  executables: []
17
29
  extensions: []
18
30
  extra_rdoc_files: []
19
31
  files:
20
- - lib/http-requestor.rb
32
+ - lib/http_requestor.rb
33
+ - lib/http_requestor_multipart.rb
21
34
  - MIT-LICENSE
22
35
  - README.rdoc
23
36
  - test/http_requestor_test.rb
37
+ - test/testfile.txt
24
38
  homepage: http://github.com/rohit9889/http-requestor
25
- licenses: []
39
+ licenses:
40
+ - MIT
26
41
  post_install_message:
27
42
  rdoc_options: []
28
43
  require_paths:
@@ -41,9 +56,10 @@ required_rubygems_version: !ruby/object:Gem::Requirement
41
56
  version: '0'
42
57
  requirements: []
43
58
  rubyforge_project:
44
- rubygems_version: 1.8.17
59
+ rubygems_version: 1.8.5
45
60
  signing_key:
46
61
  specification_version: 3
47
62
  summary: A Wrapper around Net/HTTP which allows you to perform HTTP Requests.
48
63
  test_files:
49
64
  - test/http_requestor_test.rb
65
+ - test/testfile.txt
@@ -1,134 +0,0 @@
1
- require "net/http"
2
- require "net/https"
3
- require "uri"
4
-
5
- class HttpRequestor
6
-
7
- #============== Instance Methods ===================
8
-
9
- def initialize(domain, options={})
10
- raise InvalidURISchemeException, "Please send a valid URI scheme." if domain.match(/(http|https):\/\//).nil?
11
-
12
- @defaults = {:domain => domain}
13
- uri = URI.parse(@defaults[:domain])
14
- if uri.scheme == "http"
15
- @http = Net::HTTP.new(uri.host, uri.port)
16
- else
17
- @http = Net::HTTP.new(uri.host, uri.port)
18
- @http.use_ssl = true
19
- @http.verify_mode = OpenSSL::SSL::VERIFY_NONE
20
- end
21
- end
22
-
23
- def get(path,data={},headers=nil)
24
- data = data_to_query(data)
25
- if headers == nil
26
- response = @http.send_request('GET',path,data)
27
- else
28
- response = @http.send_request('GET',path,data,headers)
29
- end
30
- response
31
- end
32
-
33
- def post(path,data={},headers=nil)
34
- data = data_to_query(data)
35
- if headers == nil
36
- response = @http.send_request('POST',path,data)
37
- else
38
- response = @http.send_request('POST',path,data,headers)
39
- end
40
- response
41
- end
42
-
43
- def put(path,data={},headers=nil)
44
- data = data_to_query(data)
45
- if headers == nil
46
- response = @http.send_request('PUT',path,data)
47
- else
48
- response = @http.send_request('PUT',path,data,headers)
49
- end
50
- response
51
- end
52
-
53
- def delete(path,data={},headers=nil)
54
- data = data_to_query(data)
55
- if headers == nil
56
- response = @http.send_request('DELETE',path,data)
57
- else
58
- response = @http.send_request('DELETE',path,data,headers)
59
- end
60
- response
61
- end
62
-
63
- def data_to_query(data)
64
- return (data.nil? || data.empty?) ? "" : data.to_query
65
- end
66
-
67
- #============== Class Methods ===================
68
- def self.request(domain, request_type, request_path, data={}, headers={})
69
- request_type.upcase!
70
- raise InvalidRequestTypeException, "Please pass a valid request type." unless valid_request_types.include?(request_type)
71
- req = HttpRequestor.new(domain)
72
- if request_type == "GET"
73
- return req.get(request_path, data, headers)
74
- elsif request_type == "POST"
75
- return req.post(request_path, data, headers)
76
- elsif request_type == "PUT"
77
- return req.put(request_path, data, headers)
78
- elsif request_type == "DELETE"
79
- return req.delete(request_path, data, headers)
80
- end
81
- end
82
-
83
- def self.request_with_url(url, request_type, data={}, headers={})
84
- uri = URI.parse(url)
85
- return self.request("#{uri.scheme}://#{uri.host}:#{uri.port}", request_type, uri.request_uri, data, headers)
86
- end
87
-
88
- def self.send_basic_auth_request(url, username, password)
89
- uri = URI.parse(url)
90
-
91
- http = Net::HTTP.new(uri.host, uri.port)
92
- request = Net::HTTP::Get.new(uri.request_uri)
93
- request.basic_auth(username, password)
94
- http.request(request)
95
- end
96
-
97
- def self.valid_request_types
98
- ["GET", "POST", "UPDATE", "DELETE"]
99
- end
100
- end
101
-
102
- #================ ActiveSupport Like object#to_query methods =========================
103
- class Hash
104
- def to_query(namespace = nil)
105
- collect do |key, value|
106
- value.to_query(namespace ? "#{namespace}[#{key}]" : key)
107
- end.sort * '&'
108
- end
109
- end
110
-
111
- class Array
112
- def to_query(key)
113
- prefix = "#{key}[]"
114
- collect { |value| value.to_query(prefix) }.join '&'
115
- end
116
- end
117
-
118
- class String
119
- def to_query(key)
120
- require 'cgi' unless defined?(CGI) && defined?(CGI::escape)
121
- "#{CGI.escape(key.to_param)}=#{CGI.escape(to_param.to_s)}"
122
- end
123
-
124
- def to_param
125
- to_s
126
- end
127
- end
128
-
129
- #================= Exceptions ======================
130
- class InvalidRequestTypeException < Exception
131
- end
132
-
133
- class InvalidURISchemeException < Exception
134
- end