lib/under_os/http/request.rb in under-os-1.0.0 vs lib/under_os/http/request.rb in under-os-1.1.0
- old
+ new
@@ -1,11 +1,13 @@
#
# Options:
#
-# * :method - GET, POST, ...
-# * :cookies - Hash of cookie values
-# * :stream - boolean, in case you want to stream stuff
+# * :method - GET, POST, ...
+# * :cookies - Hash of cookie values
+# * :stream - boolean, in case you want to stream stuff
+# * :params - the POST/PUT/PATCH params hash
+# * :encoding - the POST data encoding
#
# Events:
#
# * :response - when response header is received
# * :data - when a chunk of data is received
@@ -35,14 +37,18 @@
def send
@request = build_request
@receiver = Receiver.new(self, @options[:stream])
@connection = NSURLConnection.alloc.initWithRequest(@request, delegate:@receiver)
@connection.start
+
+ return self
end
def cancel
@connection.cancel
+
+ return self
end
def method
method = @options[:method] || :get
method = method.to_s.upcase
@@ -56,34 +62,45 @@
def cookies
@options[:cookies] || {}
end
+ def params
+ @options[:params] || {}
+ end
+
+ def encoding
+ @options[:encoding] || 'utf-8'
+ end
+
protected
def build_request
- url = NSURL.URLWithString(NSString.stringWithFormat(@url))
+ query = params.to_query
+ url = build_url(query)
+
NSMutableURLRequest.requestWithURL(url).tap do |request|
- request.setHTTPMethod self.method
- #request.setHTTPBody self.params
+ request.setHTTPMethod method
- cookies = self.cookies.map do |key, value|
- NSHTTPCookie.cookieWithProperties({
- NSHTTPCookieDomain => url.host,
- NSHTTPCookiePath => "/",
- NSHTTPCookieName => key.to_s,
- NSHTTPCookieValue => value.to_s
- })
+ headers.merge(UnderOs::HTTP::Cookies.new(cookies, url).headers).each do |key, value|
+ request.addValue value, forHTTPHeaderField:key
end
- request.setAllHTTPHeaderFields NSHTTPCookie.requestHeaderFieldsWithCookies(cookies) if cookies.size > 0
-
- headers.each do |key, value|
- request.addValue value, forHTTPHeaderField:key
+ if %w[POST PUT PATCH DELETE].include?(method) && !query.empty?
+ request.addValue "application/x-www-form-urlencoded;charset=#{encoding}", forHTTPHeaderField:"Content-Type"
+ request.setHTTPBody query.to_data(encoding)
end
+ end
+ end
- # [newRequest addValue:@"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
- # [newRequest setHTTPBody:[query dataUsingEncoding:NSUTF8StringEncoding]];
+ def build_url(query)
+ url = @url
+
+ if method == "GET" && !query.empty?
+ url += url.include?('?') ? '&' : '?'
+ url += query
end
+
+ NSURL.URLWithString(url)
end
end