get parameters

master
Kanezoh 2021-05-20 21:17:33 +09:00
parent 890d4e5449
commit 1dd6e72025
3 changed files with 20 additions and 18 deletions

View File

@ -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

View File

@ -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

View File

@ -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)
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
private def compose_path(uri, params)
path = uri.path
path += "?#{params}" unless params.empty?
path
end
private def response_parse(response, body, uri)