add params

master
Kanezoh 2021-05-02 21:13:20 +09:00
parent 303dac9795
commit dc54a60490
3 changed files with 20 additions and 8 deletions

View File

@ -2,5 +2,6 @@ require "./src/mechanize.cr"
agent = Mechanize.new
agent.request_headers = HTTP::Headers{"Foo" => "Bar"}
page = agent.get("https://example.com/")
params = {"hoge" => "hoge"}
page = agent.get("http://example.com/", params: params)
puts page

View File

@ -7,9 +7,9 @@ class Mechanize
@agent = MechanizeCr::HTTP::Agent.new
end
def get(uri : String | URI, headers = HTTP::Headers.new)
def get(uri : String | URI, headers = HTTP::Headers.new, params : Hash(String, String | Array(String)) = Hash(String,String).new)
method = :get
page = @agent.fetch uri, method, headers
page = @agent.fetch uri, method, headers, params
#add_to_history(page)
#yield page if block_given?
page

View File

@ -10,21 +10,22 @@ module MechanizeCr
@request_headers = ::HTTP::Headers.new
end
def fetch(uri, method = :get, headers = HTTP::Headers.new)
def fetch(uri, method = :get, headers = HTTP::Headers.new, params = Hash(String,String).new)
add_request_headers(headers)
response = http_request uri, method
params = hash_to_params(params)
response = http_request uri, method, params
puts response.not_nil!.body
end
def http_request(uri, method)
def http_request(uri, method, params)
uri = URI.parse(uri)
request = ::HTTP::Client.new(uri.host.not_nil!)
path = compose_path(uri, params)
case uri.scheme.not_nil!.downcase
when "http", "https" then
case method
when :get
request.get(uri.path, headers: request_headers)
request.get(path, headers: request_headers)
end
end
end
@ -34,6 +35,16 @@ module MechanizeCr
request_headers[k] = v
end
end
private def hash_to_params(params)
URI::Params.encode(params)
end
private def compose_path(uri, params)
path = uri.path
path += "?#{params}" unless params.empty?
path
end
end
end
end