gpt4 book ai didi

Ruby HTTP 获取参数

转载 作者:数据小太阳 更新时间:2023-10-29 06:40:54 24 4
gpt4 key购买 nike

如何通过 ruby​​ 发送带参数的 HTTP GET 请求?

我尝试了很多例子,但都失败了。

最佳答案

我知道这篇文章很旧,但是为了那些由谷歌带到这里的人,有一种更简单的方法可以以 URL 安全的方式对您的参数进行编码。我不确定为什么我没有在其他地方看到这个,因为该方法记录在 Net::HTTP 页面上。我已经看到 Arsen7 描述的方法也是其他几个问题的公认答案。

Net::HTTP 中提到文档是 URI.encode_www_form(params):

# Lets say we have a path and params that look like this:
path = "/search"
params = {q: => "answer"}

# Example 1: Replacing the #path_with_params method from Arsen7
def path_with_params(path, params)
encoded_params = URI.encode_www_form(params)
[path, encoded_params].join("?")
end

# Example 2: A shortcut for the entire example by Arsen7
uri = URI.parse("http://localhost.com" + path)
uri.query = URI.encode_www_form(params)
response = Net::HTTP.get_response(uri)

您选择哪个示例在很大程度上取决于您的用例。在我当前的项目中,我使用了一种类似于 Arsen7 推荐的方法以及更简单的 #path_with_params 方法,并且没有 block 格式。

# Simplified example implementation without response
# decoding or error handling.

require "net/http"
require "uri"

class Connection
VERB_MAP = {
:get => Net::HTTP::Get,
:post => Net::HTTP::Post,
:put => Net::HTTP::Put,
:delete => Net::HTTP::Delete
}

API_ENDPOINT = "http://dev.random.com"

attr_reader :http

def initialize(endpoint = API_ENDPOINT)
uri = URI.parse(endpoint)
@http = Net::HTTP.new(uri.host, uri.port)
end

def request(method, path, params)
case method
when :get
full_path = path_with_params(path, params)
request = VERB_MAP[method].new(full_path)
else
request = VERB_MAP[method].new(path)
request.set_form_data(params)
end

http.request(request)
end

private

def path_with_params(path, params)
encoded_params = URI.encode_www_form(params)
[path, encoded_params].join("?")
end

end

con = Connection.new
con.request(:post, "/account", {:email => "test@test.com"})
=> #<Net::HTTPCreated 201 Created readbody=true>

关于Ruby HTTP 获取参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6843352/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com