add params

This commit is contained in:
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 = Mechanize.new
agent.request_headers = HTTP::Headers{"Foo" => "Bar"} 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 puts page

View File

@ -7,9 +7,9 @@ class Mechanize
@agent = MechanizeCr::HTTP::Agent.new @agent = MechanizeCr::HTTP::Agent.new
end 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 method = :get
page = @agent.fetch uri, method, headers page = @agent.fetch uri, method, headers, params
#add_to_history(page) #add_to_history(page)
#yield page if block_given? #yield page if block_given?
page page

View File

@ -10,21 +10,22 @@ module MechanizeCr
@request_headers = ::HTTP::Headers.new @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, params = Hash(String,String).new)
add_request_headers(headers) add_request_headers(headers)
params = hash_to_params(params)
response = http_request uri, method response = http_request uri, method, params
puts response.not_nil!.body puts response.not_nil!.body
end end
def http_request(uri, method) def http_request(uri, method, params)
uri = URI.parse(uri) uri = URI.parse(uri)
request = ::HTTP::Client.new(uri.host.not_nil!) request = ::HTTP::Client.new(uri.host.not_nil!)
path = compose_path(uri, params)
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: request_headers) request.get(path, headers: request_headers)
end end
end end
end end
@ -34,6 +35,16 @@ module MechanizeCr
request_headers[k] = v request_headers[k] = v
end end
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 end
end end