add request headers

This commit is contained in:
Kanezoh 2021-05-01 23:22:37 +09:00
parent 57e0b6c52e
commit aa2bb5701a
3 changed files with 23 additions and 4 deletions

View File

@ -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

View File

@ -4,23 +4,33 @@ 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)
end
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

View File

@ -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