add request headers
This commit is contained in:
parent
57e0b6c52e
commit
aa2bb5701a
3
main.cr
3
main.cr
@ -1,5 +1,6 @@
|
||||
require "./src/mechanize.cr"
|
||||
|
||||
agent = Mechanize.new
|
||||
page = agent.get "http://example.com/"
|
||||
agent.request_headers = HTTP::Headers{"Foo" => "Bar"}
|
||||
page = agent.get("https://example.com")
|
||||
puts page
|
||||
|
@ -4,25 +4,35 @@ require "http/client"
|
||||
module MechanizeCr
|
||||
module HTTP
|
||||
class Agent
|
||||
property :request_headers
|
||||
|
||||
def initialize()
|
||||
@request_headers = ::HTTP::Headers.new
|
||||
end
|
||||
|
||||
def fetch(uri, method = :get, headers = HTTP::Headers.new)
|
||||
response = http_request uri, method, headers
|
||||
add_request_headers(headers)
|
||||
response = http_request uri, method
|
||||
puts response.not_nil!.body
|
||||
end
|
||||
|
||||
def http_request(uri, method, headers)
|
||||
def http_request(uri, method)
|
||||
uri = URI.parse(uri)
|
||||
request = ::HTTP::Client.new(uri.host.not_nil!)
|
||||
case uri.scheme.not_nil!.downcase
|
||||
when "http", "https" then
|
||||
case method
|
||||
when :get
|
||||
request.get(uri.path, headers: headers)
|
||||
request.get(uri.path, headers: request_headers)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
private def add_request_headers(headers)
|
||||
headers.each do |k,v|
|
||||
request_headers[k] = v
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
@ -14,4 +14,12 @@ class Mechanize
|
||||
#yield page if block_given?
|
||||
page
|
||||
end
|
||||
|
||||
def request_headers
|
||||
@agent.request_headers
|
||||
end
|
||||
|
||||
def request_headers=(request_headers)
|
||||
@agent.request_headers = request_headers
|
||||
end
|
||||
end
|
||||
|
Loading…
Reference in New Issue
Block a user