Ruby:net/http可以同时发出GET和POST请求吗?

Mar*_*rco 6 ruby uri

是否可以同时传递GET和POST参数?

uri = URI.parse("http://www.example.com/post.php?a=1&b=2")

req = Net::HTTP::Post.new(uri.path, {
    'Referer' => "http://www.example.com/referer",
    'User-Agent'=> "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)",
    'Cookie' => $cookie
})

req.set_form_data({
    'foo' => 'bar',
    'bar' => 'foo'
})

http = Net::HTTP.new(uri.host, uri.port)
http.open_timeout = 40
http.read_timeout = 20

# Request page:
begin
    resp = http.request(req)
rescue Exception
    puts "Exception requesting the page; returning"
end
Run Code Online (Sandbox Code Playgroud)

在上面的脚本中,只发送POST参数并忽略GET查询

Mit*_*ell 4

创建请求时,您只需确保将 GET 参数保留在路径中:

req = Net::HTTP::Post.new("#{uri.path}?#{uri.query}", {
    'Referer' => "http://www.example.com/referer",
    'User-Agent'=> "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)",
    'Cookie' => $cookie
})
Run Code Online (Sandbox Code Playgroud)

uri.path请注意,我在其后面附加了?and ,而不是仅仅。uri.query这应该传递 GET 参数以及 POST 参数。