在Ruby中urllib2的等效代码是什么

0 投票
1 回答
535 浏览
提问于 2025-04-18 12:48

我想传递网址、请求头和查询参数。下面是用Python写的代码。我想用Ruby来实现这个功能。我在网上查了一下,发现Net::HTTP是正确的方法。但是这个方法不接受查询参数,还报错了。那么,Ruby中有什么代码可以和下面的Python代码等效呢?

我还添加了两个文件的下载链接。

Python代码

Ruby代码

我希望在Ruby中也能得到和Python一样的结果。

nonce=1404996712857&method=neworder&rate=1&order_type=buy&quantity=1  //post_data(query params)

headers = {'key': '1234567894444444', 'sign': 'jhjhgyyqw7y890190800iihuhugdhugabnmKOP'}

Python

url_request_object = urllib2.Request("%s/%s" % (BASE_API_URL,url_suffix),
                                         post_data,
                                         headers)
response = urllib2.urlopen(url_request_object)

Ruby

response = Net::HTTP.post_form(uri, :body => post_data,:header => headers )
puts response.body

错误信息:

{"status": false, "message": "method required", "systime": 1404996498.0}

1 个回答

0

这应该能帮到你。

require 'net/http'

html_request = Net::HTTP.new('site.com', 80)
path = '/path/where/form/is'
headers = {'Host' => 'site.com', 'Connection' => 'keep-alive', 'Key' => '1234567894444444', 'sign' => 'jhjhgyyqw7y890190800iihuhugdhugabnmKOP'}
post_data = 'nonce=1404996712857&method=neworder&rate=1&order_type=buy&quantity=1'

response = html_request.post(path, post_data, headers)
response_string = response.body.to_s

撰写回答