0

我想在 Ruby 中做一个 XMLHttpRequest POST。我不想使用像 Watir 这样的框架。像机械化或斯克鲁比之类的东西就可以了。我怎样才能做到这一点?

4

3 回答 3

2

机械化:

require 'mechanize'
agent = Mechanize.new
agent.post 'http://www.example.com/', :foo => 'bar'
于 2012-06-11T23:28:23.437 回答
2

'net/http' 示例,(ruby 1.9.3):

您只需将 XMLHttpRequest 的附加标头添加到您的 POST 请求中(见下文)。

require 'net/http'
require 'uri'  # convenient for using parts of an URI

uri = URI.parse('http://server.com/path/to/resource')

# create a Net::HTTP object (the client with details of the server):
http_client = Net::HTTP.new(uri.host, uri.port)

# create a POST-object for the request:
your_post = Net::HTTP::Post.new(uri.path)

# the content (body) of your post-request:
your_post.body = 'your content'

# the headers for your post-request (you have to analyze before,
# which headers are mandatory for your request); for example:
your_post['Content-Type'] = 'put here the content-type'
your_post['Content-Length'] = your_post.body.size.to_s
# ...
# for an XMLHttpRequest you need (for example?) such header:
your_post['X-Requested-With'] = 'XMLHttpRequest'

# send the request to the server:
response = http_client.request(your_post)

# the body of the response:
puts response.body

于 2015-10-15T19:28:49.107 回答
1

XMLHTTPRequest 是一个浏览器概念,但既然您问的是 Ruby,我假设您想要做的只是模拟来自 ruby​​ 脚本的此类请求?为此,有一个名为HTTParty的 gem ,它非常易于使用。

这是一个简单的例子(假设你有 gem - 安装它gem install httparty):

require 'httparty'
response = HTTParty.get('http://twitter.com/statuses/public_timeline.json')
puts response.body, response.code, response.message, response.headers.inspect
于 2012-06-11T10:43:45.503 回答