【问题标题】:Ruby: Can net/http make a GET and POST request simultaneously?Ruby:net/http 可以同时发出 GET 和 POST 请求吗?
【发布时间】:2011-02-28 11:58:13
【问题描述】:

是否可以同时传递 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

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

【问题讨论】:

    标签: ruby uri


    【解决方案1】:

    创建请求时,您只需确保将 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
    })
    

    请注意,我将?uri.query 附加到它上面,而不仅仅是uri.path。这应该传递 GET 参数以及 POST 参数。

    【讨论】:

    • 您先生是救生员。在过去的几个小时里,我一直在努力解决这个问题。
    • 您也可以只使用uri.request_uri 来构建带有路径和查询参数的请求字符串。
    猜你喜欢
    • 2012-09-22
    • 1970-01-01
    • 2021-11-16
    • 2018-10-08
    • 1970-01-01
    • 1970-01-01
    • 2019-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多