From dc54a604906465ee3d10c9cd0592d5df4cc78514 Mon Sep 17 00:00:00 2001 From: Kanezoh Date: Sun, 2 May 2021 21:13:20 +0900 Subject: [PATCH] add params --- main.cr | 3 ++- src/mechanize.cr | 4 ++-- src/mechanize/http/agent.cr | 21 ++++++++++++++++----- 3 files changed, 20 insertions(+), 8 deletions(-) diff --git a/main.cr b/main.cr index 842bf3c..cce5aa6 100644 --- a/main.cr +++ b/main.cr @@ -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 diff --git a/src/mechanize.cr b/src/mechanize.cr index 94b04c7..0b6f565 100644 --- a/src/mechanize.cr +++ b/src/mechanize.cr @@ -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 diff --git a/src/mechanize/http/agent.cr b/src/mechanize/http/agent.cr index aa86ad5..a424162 100644 --- a/src/mechanize/http/agent.cr +++ b/src/mechanize/http/agent.cr @@ -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