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