add params
This commit is contained in:
parent
303dac9795
commit
dc54a60490
3
main.cr
3
main.cr
@ -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
|
||||||
|
@ -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
|
||||||
|
@ -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
|
||||||
|
Loading…
Reference in New Issue
Block a user