diff --git a/main.cr b/main.cr index 6bc360e..011b24b 100644 --- a/main.cr +++ b/main.cr @@ -3,9 +3,9 @@ require "./src/mechanize.cr" agent = Mechanize.new agent.request_headers = HTTP::Headers{"Foo" => "Bar"} params = {"hoge" => "hoge"} -#page = agent.get("http://example.com/", params: params) -query = {"foo" => "foo_value", "bar" => "bar_value"} -page = agent.post("http//example.com/", query: query) +page = agent.get("http://google.com/", params: params) +#query = {"foo" => "foo_value", "bar" => "bar_value"} +#page = agent.post("http//example.com/", query: query) #puts page.code #puts page.body #puts page.css("h1").first.inner_text diff --git a/src/mechanize.cr b/src/mechanize.cr index 1d0bc09..9da3313 100644 --- a/src/mechanize.cr +++ b/src/mechanize.cr @@ -1,6 +1,7 @@ require "./mechanize/http/agent" require "./mechanize/form" require "./mechanize/node" +require "./mechanize/page" class Mechanize VERSION = "0.1.0" @@ -44,9 +45,9 @@ class Mechanize headers.merge!(content_headers) # fetch the page - #page = @agent.fetch uri, :post, headers, [request_data]#, cur_page + page = @agent.fetch uri, :post, headers, [request_data]#, cur_page #add_to_history(page) - #page + page end def request_headers diff --git a/src/mechanize/http/agent.cr b/src/mechanize/http/agent.cr index 92e57e6..5f89567 100644 --- a/src/mechanize/http/agent.cr +++ b/src/mechanize/http/agent.cr @@ -14,8 +14,8 @@ module MechanizeCr def fetch(uri, method = :get, headers = HTTP::Headers.new, params = Hash(String,String).new) uri = URI.parse(uri) set_request_headers(headers) - params = hash_to_params(params) - response = http_request uri, method, params + uri, params = resolve_parameters(uri, method, params) + response = http_request(uri, method, params) body = response.not_nil!.body page = response_parse(response, body, uri) # save cookies @@ -24,13 +24,13 @@ module MechanizeCr end def http_request(uri, method, params) - client = ::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 - client.get(path, headers: request_headers) + ::HTTP::Client.get(uri, headers: request_headers) + when :post + #client.post(path) end end end @@ -41,14 +41,15 @@ module MechanizeCr 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 + private def resolve_parameters(uri, method, params) + case method + when :get + query = URI::Params.encode(params) + uri.query = query + return uri, nil + else + return uri, params + end end private def response_parse(response, body, uri)