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

发布于 2024-09-04 21:15:42 字数 638 浏览 3 评论 0原文

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

Is it possible to pass both the GET and POST parameters at the same time?

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

In the script above, only the POST parameters get sent and the GET query is ignored

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

没︽人懂的悲伤 2024-09-11 21:15:42

创建请求时,您只需确保将 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.path uri.query 到它。这应该传递 GET 参数以及 POST 参数。

When creating the request you just need to make sure to keep the GET params in the path:

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
})

Notice that instead of just uri.path, I append the ? and uri.query to it. This should pass the GET parameters as well as the POST ones.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文