Skip to content

Commit

Permalink
Added :headers option to HttpStream
Browse files Browse the repository at this point in the history
  • Loading branch information
Andrew Kane committed Aug 15, 2011
1 parent e323aaf commit 1696f52
Showing 1 changed file with 24 additions and 13 deletions.
37 changes: 24 additions & 13 deletions lib/yajl/http_stream.rb
Original file line number Diff line number Diff line change
Expand Up @@ -90,31 +90,42 @@ def self.request(method, uri, opts = {}, &block)
uri = URI.parse(uri)
end

user_agent = opts.has_key?('User-Agent') ? opts.delete(['User-Agent']) : "Yajl::HttpStream #{Yajl::VERSION}"
default_headers = {
"User-Agent" => opts["User-Agent"] || "Yajl::HttpStream #{Yajl::VERSION}",
"Accept" => "*/*",
"Accept-Charset" => "utf-8"
}

if method == "POST" || method == "PUT"
content_type = opts.has_key?('Content-Type') ? opts.delete(['Content-Type']) : "application/x-www-form-urlencoded"
default_headers["Content-Type"] = opts["Content-Type"] || "application/x-www-form-urlencoded"
body = opts.delete(:body)
if body.is_a?(Hash)
body = body.keys.collect {|param| "#{URI.escape(param.to_s)}=#{URI.escape(body[param].to_s)}"}.join('&')
end
default_headers["Content-Length"] = body.length
end

socket = opts.has_key?(:socket) ? opts.delete(:socket) : TCPSocket.new(uri.host, uri.port)
request = "#{method} #{uri.path}#{uri.query ? "?"+uri.query : nil} HTTP/1.1\r\n"
request << "Host: #{uri.host}\r\n"
request << "Authorization: Basic #{[uri.userinfo].pack('m').strip!}\r\n" unless uri.userinfo.nil?
request << "User-Agent: #{user_agent}\r\n"
request << "Accept: */*\r\n"
if method == "POST" || method == "PUT"
request << "Content-Length: #{body.length}\r\n"
request << "Content-Type: #{content_type}\r\n"
unless uri.userinfo.nil?
default_headers["Authorization"] = "Basic #{[uri.userinfo].pack('m').strip!}\r\n"
end

encodings = []
encodings << "bzip2" if defined?(Yajl::Bzip2)
encodings << "gzip" if defined?(Yajl::Gzip)
encodings << "deflate" if defined?(Yajl::Deflate)
request << "Accept-Encoding: #{encodings.join(',')}\r\n" if encodings.any?
request << "Accept-Charset: utf-8\r\n\r\n"
if encodings.any?
default_headers["Accept-Encoding"] = "#{encodings.join(',')}\r\n"
end

headers = default_headers.merge(opts[:headers] || {})

socket = opts.has_key?(:socket) ? opts.delete(:socket) : TCPSocket.new(uri.host, uri.port)
request = "#{method} #{uri.path}#{uri.query ? "?"+uri.query : nil} HTTP/1.1\r\n"
request << "Host: #{uri.host}\r\n"
headers.each do |k, v|
request << "#{k}: #{v}\r\n"
end
request << "\r\n"
if method == "POST" || method == "PUT"
request << body
end
Expand Down

0 comments on commit 1696f52

Please sign in to comment.