Merge pull request #12 from mamantoha/set-referer-header

Sets a Referer header
master
Kanezoh 2021-11-16 17:37:50 +09:00 committed by GitHub
commit 114a7fbcbe
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 24 additions and 2 deletions

View File

@ -65,4 +65,18 @@ describe "Mechanize Agent test" do
File.exists?("mechanizecr_example.html").should eq true File.exists?("mechanizecr_example.html").should eq true
File.delete("mechanizecr_example.html") File.delete("mechanizecr_example.html")
end end
it "should set referer header" do
page_url = "http://example.com/form"
agent = Mechanize.new
page = agent.get(page_url)
form = page.forms[0]
form.field_with("name").value = "foo"
form.field_with("email").value = "bar"
page = agent.submit(form)
page.not_nil!.code.should eq 200
agent.request_headers["Referer"].should eq(page_url)
end
end end

View File

@ -19,11 +19,12 @@ module MechanizeCr
@user_agent = "" @user_agent = ""
end end
def fetch(uri, method = :get, headers = HTTP::Headers.new, params = Hash(String, String).new, def fetch(uri, method = :get, headers = ::HTTP::Headers.new, params = Hash(String, String).new,
referer = (current_page unless history.empty?)) referer = (current_page unless history.empty?))
uri = resolve_url(uri, referer) uri = resolve_url(uri, referer)
set_request_headers(uri, headers) set_request_headers(uri, headers)
set_user_agent set_user_agent
set_request_referer(referer)
uri, params = resolve_parameters(uri, method, params) uri, params = resolve_parameters(uri, method, params)
response = http_request(uri, method, params) response = http_request(uri, method, params)
body = response.not_nil!.body body = response.not_nil!.body
@ -47,7 +48,7 @@ module MechanizeCr
headers.delete("Content-Type") headers.delete("Content-Type")
headers.delete("Content-Length") headers.delete("Content-Length")
@context.not_nil!.get(uri) fetch(uri)
end end
def http_request(uri, method, params) def http_request(uri, method, params)
@ -94,6 +95,13 @@ module MechanizeCr
end end
end end
# Sets a Referer header.
def set_request_referer(referer : MechanizeCr::Page?)
return unless referer
request_headers["Referer"] = referer.uri.to_s
end
private def resolve_parameters(uri, method, params) private def resolve_parameters(uri, method, params)
case method case method
when :get when :get